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/RecursiveASTVisitor.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/SmallPtrSet.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/Triple.h"
50 #include <algorithm>
51 #include <cstring>
52 #include <functional>
53 #include <unordered_map>
54 
55 using namespace clang;
56 using namespace sema;
57 
58 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
59   if (OwnedType) {
60     Decl *Group[2] = { OwnedType, Ptr };
61     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
62   }
63 
64   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 }
66 
67 namespace {
68 
69 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
70  public:
71    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
72                         bool AllowTemplates = false,
73                         bool AllowNonTemplates = true)
74        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
75          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
76      WantExpressionKeywords = false;
77      WantCXXNamedCasts = false;
78      WantRemainingKeywords = false;
79   }
80 
81   bool ValidateCandidate(const TypoCorrection &candidate) override {
82     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
83       if (!AllowInvalidDecl && ND->isInvalidDecl())
84         return false;
85 
86       if (getAsTypeTemplateDecl(ND))
87         return AllowTemplates;
88 
89       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
90       if (!IsType)
91         return false;
92 
93       if (AllowNonTemplates)
94         return true;
95 
96       // An injected-class-name of a class template (specialization) is valid
97       // as a template or as a non-template.
98       if (AllowTemplates) {
99         auto *RD = dyn_cast<CXXRecordDecl>(ND);
100         if (!RD || !RD->isInjectedClassName())
101           return false;
102         RD = cast<CXXRecordDecl>(RD->getDeclContext());
103         return RD->getDescribedClassTemplate() ||
104                isa<ClassTemplateSpecializationDecl>(RD);
105       }
106 
107       return false;
108     }
109 
110     return !WantClassName && candidate.isKeyword();
111   }
112 
113   std::unique_ptr<CorrectionCandidateCallback> clone() override {
114     return std::make_unique<TypeNameValidatorCCC>(*this);
115   }
116 
117  private:
118   bool AllowInvalidDecl;
119   bool WantClassName;
120   bool AllowTemplates;
121   bool AllowNonTemplates;
122 };
123 
124 } // end anonymous namespace
125 
126 /// Determine whether the token kind starts a simple-type-specifier.
127 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
128   switch (Kind) {
129   // FIXME: Take into account the current language when deciding whether a
130   // token kind is a valid type specifier
131   case tok::kw_short:
132   case tok::kw_long:
133   case tok::kw___int64:
134   case tok::kw___int128:
135   case tok::kw_signed:
136   case tok::kw_unsigned:
137   case tok::kw_void:
138   case tok::kw_char:
139   case tok::kw_int:
140   case tok::kw_half:
141   case tok::kw_float:
142   case tok::kw_double:
143   case tok::kw___bf16:
144   case tok::kw__Float16:
145   case tok::kw___float128:
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   switch (Result.getResultKind()) {
377   case LookupResult::NotFound:
378   case LookupResult::NotFoundInCurrentInstantiation:
379     if (CorrectedII) {
380       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381                                AllowDeducedTemplate);
382       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383                                               S, SS, CCC, CTK_ErrorRecovery);
384       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385       TemplateTy Template;
386       bool MemberOfUnknownSpecialization;
387       UnqualifiedId TemplateName;
388       TemplateName.setIdentifier(NewII, NameLoc);
389       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390       CXXScopeSpec NewSS, *NewSSPtr = SS;
391       if (SS && NNS) {
392         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393         NewSSPtr = &NewSS;
394       }
395       if (Correction && (NNS || NewII != &II) &&
396           // Ignore a correction to a template type as the to-be-corrected
397           // identifier is not a template (typo correction for template names
398           // is handled elsewhere).
399           !(getLangOpts().CPlusPlus && NewSSPtr &&
400             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401                            Template, MemberOfUnknownSpecialization))) {
402         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403                                     isClassName, HasTrailingDot, ObjectTypePtr,
404                                     IsCtorOrDtorName,
405                                     WantNontrivialTypeSourceInfo,
406                                     IsClassTemplateDeductionContext);
407         if (Ty) {
408           diagnoseTypo(Correction,
409                        PDiag(diag::err_unknown_type_or_class_name_suggest)
410                          << Result.getLookupName() << isClassName);
411           if (SS && NNS)
412             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413           *CorrectedII = NewII;
414           return Ty;
415         }
416       }
417     }
418     // If typo correction failed or was not performed, fall through
419     LLVM_FALLTHROUGH;
420   case LookupResult::FoundOverloaded:
421   case LookupResult::FoundUnresolvedValue:
422     Result.suppressDiagnostics();
423     return nullptr;
424 
425   case LookupResult::Ambiguous:
426     // Recover from type-hiding ambiguities by hiding the type.  We'll
427     // do the lookup again when looking for an object, and we can
428     // diagnose the error then.  If we don't do this, then the error
429     // about hiding the type will be immediately followed by an error
430     // that only makes sense if the identifier was treated like a type.
431     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432       Result.suppressDiagnostics();
433       return nullptr;
434     }
435 
436     // Look to see if we have a type anywhere in the list of results.
437     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438          Res != ResEnd; ++Res) {
439       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
440           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
441         if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation())
442           IIDecl = *Res;
443       }
444     }
445 
446     if (!IIDecl) {
447       // None of the entities we found is a type, so there is no way
448       // to even assume that the result is a type. In this case, don't
449       // complain about the ambiguity. The parser will either try to
450       // perform this lookup again (e.g., as an object name), which
451       // will produce the ambiguity, or will complain that it expected
452       // a type name.
453       Result.suppressDiagnostics();
454       return nullptr;
455     }
456 
457     // We found a type within the ambiguous lookup; diagnose the
458     // ambiguity and then return that type. This might be the right
459     // answer, or it might not be, but it suppresses any attempt to
460     // perform the name lookup again.
461     break;
462 
463   case LookupResult::Found:
464     IIDecl = Result.getFoundDecl();
465     break;
466   }
467 
468   assert(IIDecl && "Didn't find decl");
469 
470   QualType T;
471   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472     // C++ [class.qual]p2: A lookup that would find the injected-class-name
473     // instead names the constructors of the class, except when naming a class.
474     // This is ill-formed when we're not actually forming a ctor or dtor name.
475     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478         FoundRD->isInjectedClassName() &&
479         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481           << &II << /*Type*/1;
482 
483     DiagnoseUseOfDecl(IIDecl, NameLoc);
484 
485     T = Context.getTypeDeclType(TD);
486     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489     if (!HasTrailingDot)
490       T = Context.getObjCInterfaceType(IDecl);
491   } else if (AllowDeducedTemplate) {
492     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494                                                        QualType(), false);
495   }
496 
497   if (T.isNull()) {
498     // If it's not plausibly a type, suppress diagnostics.
499     Result.suppressDiagnostics();
500     return nullptr;
501   }
502 
503   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504   // constructor or destructor name (in such a case, the scope specifier
505   // will be attached to the enclosing Expr or Decl node).
506   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507       !isa<ObjCInterfaceDecl>(IIDecl)) {
508     if (WantNontrivialTypeSourceInfo) {
509       // Construct a type with type-source information.
510       TypeLocBuilder Builder;
511       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512 
513       T = getElaboratedType(ETK_None, *SS, T);
514       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515       ElabTL.setElaboratedKeywordLoc(SourceLocation());
516       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518     } else {
519       T = getElaboratedType(ETK_None, *SS, T);
520     }
521   }
522 
523   return ParsedType::make(T);
524 }
525 
526 // Builds a fake NNS for the given decl context.
527 static NestedNameSpecifier *
528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529   for (;; DC = DC->getLookupParent()) {
530     DC = DC->getPrimaryContext();
531     auto *ND = dyn_cast<NamespaceDecl>(DC);
532     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533       return NestedNameSpecifier::Create(Context, nullptr, ND);
534     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536                                          RD->getTypeForDecl());
537     else if (isa<TranslationUnitDecl>(DC))
538       return NestedNameSpecifier::GlobalSpecifier(Context);
539   }
540   llvm_unreachable("something isn't in TU scope?");
541 }
542 
543 /// Find the parent class with dependent bases of the innermost enclosing method
544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545 /// up allowing unqualified dependent type names at class-level, which MSVC
546 /// correctly rejects.
547 static const CXXRecordDecl *
548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552       if (MD->getParent()->hasAnyDependentBases())
553         return MD->getParent();
554   }
555   return nullptr;
556 }
557 
558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559                                           SourceLocation NameLoc,
560                                           bool IsTemplateTypeArg) {
561   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
562 
563   NestedNameSpecifier *NNS = nullptr;
564   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565     // If we weren't able to parse a default template argument, delay lookup
566     // until instantiation time by making a non-dependent DependentTypeName. We
567     // pretend we saw a NestedNameSpecifier referring to the current scope, and
568     // lookup is retried.
569     // FIXME: This hurts our diagnostic quality, since we get errors like "no
570     // type named 'Foo' in 'current_namespace'" when the user didn't write any
571     // name specifiers.
572     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574   } else if (const CXXRecordDecl *RD =
575                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576     // Build a DependentNameType that will perform lookup into RD at
577     // instantiation time.
578     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579                                       RD->getTypeForDecl());
580 
581     // Diagnose that this identifier was undeclared, and retry the lookup during
582     // template instantiation.
583     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584                                                                       << RD;
585   } else {
586     // This is not a situation that we should recover from.
587     return ParsedType();
588   }
589 
590   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591 
592   // Build type location information.  We synthesized the qualifier, so we have
593   // to build a fake NestedNameSpecifierLoc.
594   NestedNameSpecifierLocBuilder NNSLocBuilder;
595   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597 
598   TypeLocBuilder Builder;
599   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600   DepTL.setNameLoc(NameLoc);
601   DepTL.setElaboratedKeywordLoc(SourceLocation());
602   DepTL.setQualifierLoc(QualifierLoc);
603   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604 }
605 
606 /// isTagName() - This method is called *for error recovery purposes only*
607 /// to determine if the specified name is a valid tag name ("struct foo").  If
608 /// so, this returns the TST for the tag corresponding to it (TST_enum,
609 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
610 /// cases in C where the user forgot to specify the tag.
611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612   // Do a tag name lookup in this scope.
613   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614   LookupName(R, S, false);
615   R.suppressDiagnostics();
616   if (R.getResultKind() == LookupResult::Found)
617     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618       switch (TD->getTagKind()) {
619       case TTK_Struct: return DeclSpec::TST_struct;
620       case TTK_Interface: return DeclSpec::TST_interface;
621       case TTK_Union:  return DeclSpec::TST_union;
622       case TTK_Class:  return DeclSpec::TST_class;
623       case TTK_Enum:   return DeclSpec::TST_enum;
624       }
625     }
626 
627   return DeclSpec::TST_unspecified;
628 }
629 
630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
632 /// then downgrade the missing typename error to a warning.
633 /// This is needed for MSVC compatibility; Example:
634 /// @code
635 /// template<class T> class A {
636 /// public:
637 ///   typedef int TYPE;
638 /// };
639 /// template<class T> class B : public A<T> {
640 /// public:
641 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
642 /// };
643 /// @endcode
644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645   if (CurContext->isRecord()) {
646     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647       return true;
648 
649     const Type *Ty = SS->getScopeRep()->getAsType();
650 
651     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652     for (const auto &Base : RD->bases())
653       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654         return true;
655     return S->isFunctionPrototypeScope();
656   }
657   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658 }
659 
660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661                                    SourceLocation IILoc,
662                                    Scope *S,
663                                    CXXScopeSpec *SS,
664                                    ParsedType &SuggestedType,
665                                    bool IsTemplateName) {
666   // Don't report typename errors for editor placeholders.
667   if (II->isEditorPlaceholder())
668     return;
669   // We don't have anything to suggest (yet).
670   SuggestedType = nullptr;
671 
672   // There may have been a typo in the name of the type. Look up typo
673   // results, in case we have something that we can suggest.
674   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675                            /*AllowTemplates=*/IsTemplateName,
676                            /*AllowNonTemplates=*/!IsTemplateName);
677   if (TypoCorrection Corrected =
678           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679                       CCC, CTK_ErrorRecovery)) {
680     // FIXME: Support error recovery for the template-name case.
681     bool CanRecover = !IsTemplateName;
682     if (Corrected.isKeyword()) {
683       // We corrected to a keyword.
684       diagnoseTypo(Corrected,
685                    PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                         : diag::err_unknown_typename_suggest)
687                        << II);
688       II = Corrected.getCorrectionAsIdentifierInfo();
689     } else {
690       // We found a similarly-named type or interface; suggest that.
691       if (!SS || !SS->isSet()) {
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName ? diag::err_no_template_suggest
694                                           : diag::err_unknown_typename_suggest)
695                          << II, CanRecover);
696       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699                                 II->getName().equals(CorrectedStr);
700         diagnoseTypo(Corrected,
701                      PDiag(IsTemplateName
702                                ? diag::err_no_member_template_suggest
703                                : diag::err_unknown_nested_typename_suggest)
704                          << II << DC << DroppedSpecifier << SS->getRange(),
705                      CanRecover);
706       } else {
707         llvm_unreachable("could not have corrected a typo here");
708       }
709 
710       if (!CanRecover)
711         return;
712 
713       CXXScopeSpec tmpSS;
714       if (Corrected.getCorrectionSpecifier())
715         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716                           SourceRange(IILoc));
717       // FIXME: Support class template argument deduction here.
718       SuggestedType =
719           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721                       /*IsCtorOrDtorName=*/false,
722                       /*WantNontrivialTypeSourceInfo=*/true);
723     }
724     return;
725   }
726 
727   if (getLangOpts().CPlusPlus && !IsTemplateName) {
728     // See if II is a class template that the user forgot to pass arguments to.
729     UnqualifiedId Name;
730     Name.setIdentifier(II, IILoc);
731     CXXScopeSpec EmptySS;
732     TemplateTy TemplateResult;
733     bool MemberOfUnknownSpecialization;
734     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735                        Name, nullptr, true, TemplateResult,
736                        MemberOfUnknownSpecialization) == TNK_Type_template) {
737       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738       return;
739     }
740   }
741 
742   // FIXME: Should we move the logic that tries to recover from a missing tag
743   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744 
745   if (!SS || (!SS->isSet() && !SS->isInvalid()))
746     Diag(IILoc, IsTemplateName ? diag::err_no_template
747                                : diag::err_unknown_typename)
748         << II;
749   else if (DeclContext *DC = computeDeclContext(*SS, false))
750     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751                                : diag::err_typename_nested_not_found)
752         << II << DC << SS->getRange();
753   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754     SuggestedType =
755         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756   } else if (isDependentScopeSpecifier(*SS)) {
757     unsigned DiagID = diag::err_typename_missing;
758     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759       DiagID = diag::ext_typename_missing;
760 
761     Diag(SS->getRange().getBegin(), DiagID)
762       << SS->getScopeRep() << II->getName()
763       << SourceRange(SS->getRange().getBegin(), IILoc)
764       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765     SuggestedType = ActOnTypenameType(S, SourceLocation(),
766                                       *SS, *II, IILoc).get();
767   } else {
768     assert(SS && SS->isInvalid() &&
769            "Invalid scope specifier has already been diagnosed");
770   }
771 }
772 
773 /// Determine whether the given result set contains either a type name
774 /// or
775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777                        NextToken.is(tok::less);
778 
779   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781       return true;
782 
783     if (CheckTemplate && isa<TemplateDecl>(*I))
784       return true;
785   }
786 
787   return false;
788 }
789 
790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791                                     Scope *S, CXXScopeSpec &SS,
792                                     IdentifierInfo *&Name,
793                                     SourceLocation NameLoc) {
794   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795   SemaRef.LookupParsedName(R, S, &SS);
796   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797     StringRef FixItTagName;
798     switch (Tag->getTagKind()) {
799       case TTK_Class:
800         FixItTagName = "class ";
801         break;
802 
803       case TTK_Enum:
804         FixItTagName = "enum ";
805         break;
806 
807       case TTK_Struct:
808         FixItTagName = "struct ";
809         break;
810 
811       case TTK_Interface:
812         FixItTagName = "__interface ";
813         break;
814 
815       case TTK_Union:
816         FixItTagName = "union ";
817         break;
818     }
819 
820     StringRef TagName = FixItTagName.drop_back();
821     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824 
825     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826          I != IEnd; ++I)
827       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828         << Name << TagName;
829 
830     // Replace lookup results with just the tag decl.
831     Result.clear(Sema::LookupTagName);
832     SemaRef.LookupParsedName(Result, S, &SS);
833     return true;
834   }
835 
836   return false;
837 }
838 
839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841                                   QualType T, SourceLocation NameLoc) {
842   ASTContext &Context = S.Context;
843 
844   TypeLocBuilder Builder;
845   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846 
847   T = S.getElaboratedType(ETK_None, SS, T);
848   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849   ElabTL.setElaboratedKeywordLoc(SourceLocation());
850   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852 }
853 
854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855                                             IdentifierInfo *&Name,
856                                             SourceLocation NameLoc,
857                                             const Token &NextToken,
858                                             CorrectionCandidateCallback *CCC) {
859   DeclarationNameInfo NameInfo(Name, NameLoc);
860   ObjCMethodDecl *CurMethod = getCurMethodDecl();
861 
862   assert(NextToken.isNot(tok::coloncolon) &&
863          "parse nested name specifiers before calling ClassifyName");
864   if (getLangOpts().CPlusPlus && SS.isSet() &&
865       isCurrentClassName(*Name, S, &SS)) {
866     // Per [class.qual]p2, this names the constructors of SS, not the
867     // injected-class-name. We don't have a classification for that.
868     // There's not much point caching this result, since the parser
869     // will reject it later.
870     return NameClassification::Unknown();
871   }
872 
873   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874   LookupParsedName(Result, S, &SS, !CurMethod);
875 
876   if (SS.isInvalid())
877     return NameClassification::Error();
878 
879   // For unqualified lookup in a class template in MSVC mode, look into
880   // dependent base classes where the primary class template is known.
881   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882     if (ParsedType TypeInBase =
883             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884       return TypeInBase;
885   }
886 
887   // Perform lookup for Objective-C instance variables (including automatically
888   // synthesized instance variables), if we're in an Objective-C method.
889   // FIXME: This lookup really, really needs to be folded in to the normal
890   // unqualified lookup mechanism.
891   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893     if (Ivar.isInvalid())
894       return NameClassification::Error();
895     if (Ivar.isUsable())
896       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897 
898     // We defer builtin creation until after ivar lookup inside ObjC methods.
899     if (Result.empty())
900       LookupBuiltin(Result);
901   }
902 
903   bool SecondTry = false;
904   bool IsFilteredTemplateName = false;
905 
906 Corrected:
907   switch (Result.getResultKind()) {
908   case LookupResult::NotFound:
909     // If an unqualified-id is followed by a '(', then we have a function
910     // call.
911     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912       // In C++, this is an ADL-only call.
913       // FIXME: Reference?
914       if (getLangOpts().CPlusPlus)
915         return NameClassification::UndeclaredNonType();
916 
917       // C90 6.3.2.2:
918       //   If the expression that precedes the parenthesized argument list in a
919       //   function call consists solely of an identifier, and if no
920       //   declaration is visible for this identifier, the identifier is
921       //   implicitly declared exactly as if, in the innermost block containing
922       //   the function call, the declaration
923       //
924       //     extern int identifier ();
925       //
926       //   appeared.
927       //
928       // We also allow this in C99 as an extension.
929       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930         return NameClassification::NonType(D);
931     }
932 
933     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934       // In C++20 onwards, this could be an ADL-only call to a function
935       // template, and we're required to assume that this is a template name.
936       //
937       // FIXME: Find a way to still do typo correction in this case.
938       TemplateName Template =
939           Context.getAssumedTemplateName(NameInfo.getName());
940       return NameClassification::UndeclaredTemplate(Template);
941     }
942 
943     // In C, we first see whether there is a tag type by the same name, in
944     // which case it's likely that the user just forgot to write "enum",
945     // "struct", or "union".
946     if (!getLangOpts().CPlusPlus && !SecondTry &&
947         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948       break;
949     }
950 
951     // Perform typo correction to determine if there is another name that is
952     // close to this name.
953     if (!SecondTry && CCC) {
954       SecondTry = true;
955       if (TypoCorrection Corrected =
956               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957                           &SS, *CCC, CTK_ErrorRecovery)) {
958         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959         unsigned QualifiedDiag = diag::err_no_member_suggest;
960 
961         NamedDecl *FirstDecl = Corrected.getFoundDecl();
962         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965           UnqualifiedDiag = diag::err_no_template_suggest;
966           QualifiedDiag = diag::err_no_member_template_suggest;
967         } else if (UnderlyingFirstDecl &&
968                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
969                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971           UnqualifiedDiag = diag::err_unknown_typename_suggest;
972           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973         }
974 
975         if (SS.isEmpty()) {
976           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977         } else {// FIXME: is this even reachable? Test it.
978           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980                                   Name->getName().equals(CorrectedStr);
981           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982                                     << Name << computeDeclContext(SS, false)
983                                     << DroppedSpecifier << SS.getRange());
984         }
985 
986         // Update the name, so that the caller has the new name.
987         Name = Corrected.getCorrectionAsIdentifierInfo();
988 
989         // Typo correction corrected to a keyword.
990         if (Corrected.isKeyword())
991           return Name;
992 
993         // Also update the LookupResult...
994         // FIXME: This should probably go away at some point
995         Result.clear();
996         Result.setLookupName(Corrected.getCorrection());
997         if (FirstDecl)
998           Result.addDecl(FirstDecl);
999 
1000         // If we found an Objective-C instance variable, let
1001         // LookupInObjCMethod build the appropriate expression to
1002         // reference the ivar.
1003         // FIXME: This is a gross hack.
1004         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005           DeclResult R =
1006               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007           if (R.isInvalid())
1008             return NameClassification::Error();
1009           if (R.isUsable())
1010             return NameClassification::NonType(Ivar);
1011         }
1012 
1013         goto Corrected;
1014       }
1015     }
1016 
1017     // We failed to correct; just fall through and let the parser deal with it.
1018     Result.suppressDiagnostics();
1019     return NameClassification::Unknown();
1020 
1021   case LookupResult::NotFoundInCurrentInstantiation: {
1022     // We performed name lookup into the current instantiation, and there were
1023     // dependent bases, so we treat this result the same way as any other
1024     // dependent nested-name-specifier.
1025 
1026     // C++ [temp.res]p2:
1027     //   A name used in a template declaration or definition and that is
1028     //   dependent on a template-parameter is assumed not to name a type
1029     //   unless the applicable name lookup finds a type name or the name is
1030     //   qualified by the keyword typename.
1031     //
1032     // FIXME: If the next token is '<', we might want to ask the parser to
1033     // perform some heroics to see if we actually have a
1034     // template-argument-list, which would indicate a missing 'template'
1035     // keyword here.
1036     return NameClassification::DependentNonType();
1037   }
1038 
1039   case LookupResult::Found:
1040   case LookupResult::FoundOverloaded:
1041   case LookupResult::FoundUnresolvedValue:
1042     break;
1043 
1044   case LookupResult::Ambiguous:
1045     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                       /*AllowDependent=*/false)) {
1048       // C++ [temp.local]p3:
1049       //   A lookup that finds an injected-class-name (10.2) can result in an
1050       //   ambiguity in certain cases (for example, if it is found in more than
1051       //   one base class). If all of the injected-class-names that are found
1052       //   refer to specializations of the same class template, and if the name
1053       //   is followed by a template-argument-list, the reference refers to the
1054       //   class template itself and not a specialization thereof, and is not
1055       //   ambiguous.
1056       //
1057       // This filtering can make an ambiguous result into an unambiguous one,
1058       // so try again after filtering out template names.
1059       FilterAcceptableTemplateNames(Result);
1060       if (!Result.isAmbiguous()) {
1061         IsFilteredTemplateName = true;
1062         break;
1063       }
1064     }
1065 
1066     // Diagnose the ambiguity and return an error.
1067     return NameClassification::Error();
1068   }
1069 
1070   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071       (IsFilteredTemplateName ||
1072        hasAnyAcceptableTemplateNames(
1073            Result, /*AllowFunctionTemplates=*/true,
1074            /*AllowDependent=*/false,
1075            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076                getLangOpts().CPlusPlus20))) {
1077     // C++ [temp.names]p3:
1078     //   After name lookup (3.4) finds that a name is a template-name or that
1079     //   an operator-function-id or a literal- operator-id refers to a set of
1080     //   overloaded functions any member of which is a function template if
1081     //   this is followed by a <, the < is always taken as the delimiter of a
1082     //   template-argument-list and never as the less-than operator.
1083     // C++2a [temp.names]p2:
1084     //   A name is also considered to refer to a template if it is an
1085     //   unqualified-id followed by a < and name lookup finds either one
1086     //   or more functions or finds nothing.
1087     if (!IsFilteredTemplateName)
1088       FilterAcceptableTemplateNames(Result);
1089 
1090     bool IsFunctionTemplate;
1091     bool IsVarTemplate;
1092     TemplateName Template;
1093     if (Result.end() - Result.begin() > 1) {
1094       IsFunctionTemplate = true;
1095       Template = Context.getOverloadedTemplateName(Result.begin(),
1096                                                    Result.end());
1097     } else if (!Result.empty()) {
1098       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099           *Result.begin(), /*AllowFunctionTemplates=*/true,
1100           /*AllowDependent=*/false));
1101       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102       IsVarTemplate = isa<VarTemplateDecl>(TD);
1103 
1104       if (SS.isNotEmpty())
1105         Template =
1106             Context.getQualifiedTemplateName(SS.getScopeRep(),
1107                                              /*TemplateKeyword=*/false, TD);
1108       else
1109         Template = TemplateName(TD);
1110     } else {
1111       // All results were non-template functions. This is a function template
1112       // name.
1113       IsFunctionTemplate = true;
1114       Template = Context.getAssumedTemplateName(NameInfo.getName());
1115     }
1116 
1117     if (IsFunctionTemplate) {
1118       // Function templates always go through overload resolution, at which
1119       // point we'll perform the various checks (e.g., accessibility) we need
1120       // to based on which function we selected.
1121       Result.suppressDiagnostics();
1122 
1123       return NameClassification::FunctionTemplate(Template);
1124     }
1125 
1126     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127                          : NameClassification::TypeTemplate(Template);
1128   }
1129 
1130   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132     DiagnoseUseOfDecl(Type, NameLoc);
1133     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134     QualType T = Context.getTypeDeclType(Type);
1135     if (SS.isNotEmpty())
1136       return buildNestedType(*this, SS, T, NameLoc);
1137     return ParsedType::make(T);
1138   }
1139 
1140   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141   if (!Class) {
1142     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143     if (ObjCCompatibleAliasDecl *Alias =
1144             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145       Class = Alias->getClassInterface();
1146   }
1147 
1148   if (Class) {
1149     DiagnoseUseOfDecl(Class, NameLoc);
1150 
1151     if (NextToken.is(tok::period)) {
1152       // Interface. <something> is parsed as a property reference expression.
1153       // Just return "unknown" as a fall-through for now.
1154       Result.suppressDiagnostics();
1155       return NameClassification::Unknown();
1156     }
1157 
1158     QualType T = Context.getObjCInterfaceType(Class);
1159     return ParsedType::make(T);
1160   }
1161 
1162   if (isa<ConceptDecl>(FirstDecl))
1163     return NameClassification::Concept(
1164         TemplateName(cast<TemplateDecl>(FirstDecl)));
1165 
1166   // We can have a type template here if we're classifying a template argument.
1167   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168       !isa<VarTemplateDecl>(FirstDecl))
1169     return NameClassification::TypeTemplate(
1170         TemplateName(cast<TemplateDecl>(FirstDecl)));
1171 
1172   // Check for a tag type hidden by a non-type decl in a few cases where it
1173   // seems likely a type is wanted instead of the non-type that was found.
1174   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175   if ((NextToken.is(tok::identifier) ||
1176        (NextIsOp &&
1177         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180     DiagnoseUseOfDecl(Type, NameLoc);
1181     QualType T = Context.getTypeDeclType(Type);
1182     if (SS.isNotEmpty())
1183       return buildNestedType(*this, SS, T, NameLoc);
1184     return ParsedType::make(T);
1185   }
1186 
1187   // If we already know which single declaration is referenced, just annotate
1188   // that declaration directly. Defer resolving even non-overloaded class
1189   // member accesses, as we need to defer certain access checks until we know
1190   // the context.
1191   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1193     return NameClassification::NonType(Result.getRepresentativeDecl());
1194 
1195   // Otherwise, this is an overload set that we will need to resolve later.
1196   Result.suppressDiagnostics();
1197   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1198       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1199       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1200       Result.begin(), Result.end()));
1201 }
1202 
1203 ExprResult
1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1205                                              SourceLocation NameLoc) {
1206   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1207   CXXScopeSpec SS;
1208   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1209   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1210 }
1211 
1212 ExprResult
1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1214                                             IdentifierInfo *Name,
1215                                             SourceLocation NameLoc,
1216                                             bool IsAddressOfOperand) {
1217   DeclarationNameInfo NameInfo(Name, NameLoc);
1218   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1219                                     NameInfo, IsAddressOfOperand,
1220                                     /*TemplateArgs=*/nullptr);
1221 }
1222 
1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1224                                               NamedDecl *Found,
1225                                               SourceLocation NameLoc,
1226                                               const Token &NextToken) {
1227   if (getCurMethodDecl() && SS.isEmpty())
1228     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1229       return BuildIvarRefExpr(S, NameLoc, Ivar);
1230 
1231   // Reconstruct the lookup result.
1232   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1233   Result.addDecl(Found);
1234   Result.resolveKind();
1235 
1236   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237   return BuildDeclarationNameExpr(SS, Result, ADL);
1238 }
1239 
1240 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1241   // For an implicit class member access, transform the result into a member
1242   // access expression if necessary.
1243   auto *ULE = cast<UnresolvedLookupExpr>(E);
1244   if ((*ULE->decls_begin())->isCXXClassMember()) {
1245     CXXScopeSpec SS;
1246     SS.Adopt(ULE->getQualifierLoc());
1247 
1248     // Reconstruct the lookup result.
1249     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1250                         LookupOrdinaryName);
1251     Result.setNamingClass(ULE->getNamingClass());
1252     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1253       Result.addDecl(*I, I.getAccess());
1254     Result.resolveKind();
1255     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1256                                            nullptr, S);
1257   }
1258 
1259   // Otherwise, this is already in the form we needed, and no further checks
1260   // are necessary.
1261   return ULE;
1262 }
1263 
1264 Sema::TemplateNameKindForDiagnostics
1265 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1266   auto *TD = Name.getAsTemplateDecl();
1267   if (!TD)
1268     return TemplateNameKindForDiagnostics::DependentTemplate;
1269   if (isa<ClassTemplateDecl>(TD))
1270     return TemplateNameKindForDiagnostics::ClassTemplate;
1271   if (isa<FunctionTemplateDecl>(TD))
1272     return TemplateNameKindForDiagnostics::FunctionTemplate;
1273   if (isa<VarTemplateDecl>(TD))
1274     return TemplateNameKindForDiagnostics::VarTemplate;
1275   if (isa<TypeAliasTemplateDecl>(TD))
1276     return TemplateNameKindForDiagnostics::AliasTemplate;
1277   if (isa<TemplateTemplateParmDecl>(TD))
1278     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1279   if (isa<ConceptDecl>(TD))
1280     return TemplateNameKindForDiagnostics::Concept;
1281   return TemplateNameKindForDiagnostics::DependentTemplate;
1282 }
1283 
1284 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1285   assert(DC->getLexicalParent() == CurContext &&
1286       "The next DeclContext should be lexically contained in the current one.");
1287   CurContext = DC;
1288   S->setEntity(DC);
1289 }
1290 
1291 void Sema::PopDeclContext() {
1292   assert(CurContext && "DeclContext imbalance!");
1293 
1294   CurContext = CurContext->getLexicalParent();
1295   assert(CurContext && "Popped translation unit!");
1296 }
1297 
1298 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1299                                                                     Decl *D) {
1300   // Unlike PushDeclContext, the context to which we return is not necessarily
1301   // the containing DC of TD, because the new context will be some pre-existing
1302   // TagDecl definition instead of a fresh one.
1303   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1304   CurContext = cast<TagDecl>(D)->getDefinition();
1305   assert(CurContext && "skipping definition of undefined tag");
1306   // Start lookups from the parent of the current context; we don't want to look
1307   // into the pre-existing complete definition.
1308   S->setEntity(CurContext->getLookupParent());
1309   return Result;
1310 }
1311 
1312 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1313   CurContext = static_cast<decltype(CurContext)>(Context);
1314 }
1315 
1316 /// EnterDeclaratorContext - Used when we must lookup names in the context
1317 /// of a declarator's nested name specifier.
1318 ///
1319 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1320   // C++0x [basic.lookup.unqual]p13:
1321   //   A name used in the definition of a static data member of class
1322   //   X (after the qualified-id of the static member) is looked up as
1323   //   if the name was used in a member function of X.
1324   // C++0x [basic.lookup.unqual]p14:
1325   //   If a variable member of a namespace is defined outside of the
1326   //   scope of its namespace then any name used in the definition of
1327   //   the variable member (after the declarator-id) is looked up as
1328   //   if the definition of the variable member occurred in its
1329   //   namespace.
1330   // Both of these imply that we should push a scope whose context
1331   // is the semantic context of the declaration.  We can't use
1332   // PushDeclContext here because that context is not necessarily
1333   // lexically contained in the current context.  Fortunately,
1334   // the containing scope should have the appropriate information.
1335 
1336   assert(!S->getEntity() && "scope already has entity");
1337 
1338 #ifndef NDEBUG
1339   Scope *Ancestor = S->getParent();
1340   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1342 #endif
1343 
1344   CurContext = DC;
1345   S->setEntity(DC);
1346 
1347   if (S->getParent()->isTemplateParamScope()) {
1348     // Also set the corresponding entities for all immediately-enclosing
1349     // template parameter scopes.
1350     EnterTemplatedContext(S->getParent(), DC);
1351   }
1352 }
1353 
1354 void Sema::ExitDeclaratorContext(Scope *S) {
1355   assert(S->getEntity() == CurContext && "Context imbalance!");
1356 
1357   // Switch back to the lexical context.  The safety of this is
1358   // enforced by an assert in EnterDeclaratorContext.
1359   Scope *Ancestor = S->getParent();
1360   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361   CurContext = Ancestor->getEntity();
1362 
1363   // We don't need to do anything with the scope, which is going to
1364   // disappear.
1365 }
1366 
1367 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1368   assert(S->isTemplateParamScope() &&
1369          "expected to be initializing a template parameter scope");
1370 
1371   // C++20 [temp.local]p7:
1372   //   In the definition of a member of a class template that appears outside
1373   //   of the class template definition, the name of a member of the class
1374   //   template hides the name of a template-parameter of any enclosing class
1375   //   templates (but not a template-parameter of the member if the member is a
1376   //   class or function template).
1377   // C++20 [temp.local]p9:
1378   //   In the definition of a class template or in the definition of a member
1379   //   of such a template that appears outside of the template definition, for
1380   //   each non-dependent base class (13.8.2.1), if the name of the base class
1381   //   or the name of a member of the base class is the same as the name of a
1382   //   template-parameter, the base class name or member name hides the
1383   //   template-parameter name (6.4.10).
1384   //
1385   // This means that a template parameter scope should be searched immediately
1386   // after searching the DeclContext for which it is a template parameter
1387   // scope. For example, for
1388   //   template<typename T> template<typename U> template<typename V>
1389   //     void N::A<T>::B<U>::f(...)
1390   // we search V then B<U> (and base classes) then U then A<T> (and base
1391   // classes) then T then N then ::.
1392   unsigned ScopeDepth = getTemplateDepth(S);
1393   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1394     DeclContext *SearchDCAfterScope = DC;
1395     for (; DC; DC = DC->getLookupParent()) {
1396       if (const TemplateParameterList *TPL =
1397               cast<Decl>(DC)->getDescribedTemplateParams()) {
1398         unsigned DCDepth = TPL->getDepth() + 1;
1399         if (DCDepth > ScopeDepth)
1400           continue;
1401         if (ScopeDepth == DCDepth)
1402           SearchDCAfterScope = DC = DC->getLookupParent();
1403         break;
1404       }
1405     }
1406     S->setLookupEntity(SearchDCAfterScope);
1407   }
1408 }
1409 
1410 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1411   // We assume that the caller has already called
1412   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1413   FunctionDecl *FD = D->getAsFunction();
1414   if (!FD)
1415     return;
1416 
1417   // Same implementation as PushDeclContext, but enters the context
1418   // from the lexical parent, rather than the top-level class.
1419   assert(CurContext == FD->getLexicalParent() &&
1420     "The next DeclContext should be lexically contained in the current one.");
1421   CurContext = FD;
1422   S->setEntity(CurContext);
1423 
1424   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1425     ParmVarDecl *Param = FD->getParamDecl(P);
1426     // If the parameter has an identifier, then add it to the scope
1427     if (Param->getIdentifier()) {
1428       S->AddDecl(Param);
1429       IdResolver.AddDecl(Param);
1430     }
1431   }
1432 }
1433 
1434 void Sema::ActOnExitFunctionContext() {
1435   // Same implementation as PopDeclContext, but returns to the lexical parent,
1436   // rather than the top-level class.
1437   assert(CurContext && "DeclContext imbalance!");
1438   CurContext = CurContext->getLexicalParent();
1439   assert(CurContext && "Popped translation unit!");
1440 }
1441 
1442 /// Determine whether we allow overloading of the function
1443 /// PrevDecl with another declaration.
1444 ///
1445 /// This routine determines whether overloading is possible, not
1446 /// whether some new function is actually an overload. It will return
1447 /// true in C++ (where we can always provide overloads) or, as an
1448 /// extension, in C when the previous function is already an
1449 /// overloaded function declaration or has the "overloadable"
1450 /// attribute.
1451 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1452                                        ASTContext &Context,
1453                                        const FunctionDecl *New) {
1454   if (Context.getLangOpts().CPlusPlus)
1455     return true;
1456 
1457   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1458     return true;
1459 
1460   return Previous.getResultKind() == LookupResult::Found &&
1461          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1462           New->hasAttr<OverloadableAttr>());
1463 }
1464 
1465 /// Add this decl to the scope shadowed decl chains.
1466 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1467   // Move up the scope chain until we find the nearest enclosing
1468   // non-transparent context. The declaration will be introduced into this
1469   // scope.
1470   while (S->getEntity() && S->getEntity()->isTransparentContext())
1471     S = S->getParent();
1472 
1473   // Add scoped declarations into their context, so that they can be
1474   // found later. Declarations without a context won't be inserted
1475   // into any context.
1476   if (AddToContext)
1477     CurContext->addDecl(D);
1478 
1479   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1480   // are function-local declarations.
1481   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1482     return;
1483 
1484   // Template instantiations should also not be pushed into scope.
1485   if (isa<FunctionDecl>(D) &&
1486       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1487     return;
1488 
1489   // If this replaces anything in the current scope,
1490   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1491                                IEnd = IdResolver.end();
1492   for (; I != IEnd; ++I) {
1493     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1494       S->RemoveDecl(*I);
1495       IdResolver.RemoveDecl(*I);
1496 
1497       // Should only need to replace one decl.
1498       break;
1499     }
1500   }
1501 
1502   S->AddDecl(D);
1503 
1504   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1505     // Implicitly-generated labels may end up getting generated in an order that
1506     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1507     // the label at the appropriate place in the identifier chain.
1508     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1509       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1510       if (IDC == CurContext) {
1511         if (!S->isDeclScope(*I))
1512           continue;
1513       } else if (IDC->Encloses(CurContext))
1514         break;
1515     }
1516 
1517     IdResolver.InsertDeclAfter(I, D);
1518   } else {
1519     IdResolver.AddDecl(D);
1520   }
1521 }
1522 
1523 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1524                          bool AllowInlineNamespace) {
1525   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1526 }
1527 
1528 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1529   DeclContext *TargetDC = DC->getPrimaryContext();
1530   do {
1531     if (DeclContext *ScopeDC = S->getEntity())
1532       if (ScopeDC->getPrimaryContext() == TargetDC)
1533         return S;
1534   } while ((S = S->getParent()));
1535 
1536   return nullptr;
1537 }
1538 
1539 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1540                                             DeclContext*,
1541                                             ASTContext&);
1542 
1543 /// Filters out lookup results that don't fall within the given scope
1544 /// as determined by isDeclInScope.
1545 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1546                                 bool ConsiderLinkage,
1547                                 bool AllowInlineNamespace) {
1548   LookupResult::Filter F = R.makeFilter();
1549   while (F.hasNext()) {
1550     NamedDecl *D = F.next();
1551 
1552     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1553       continue;
1554 
1555     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1556       continue;
1557 
1558     F.erase();
1559   }
1560 
1561   F.done();
1562 }
1563 
1564 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1565 /// have compatible owning modules.
1566 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1567   // FIXME: The Modules TS is not clear about how friend declarations are
1568   // to be treated. It's not meaningful to have different owning modules for
1569   // linkage in redeclarations of the same entity, so for now allow the
1570   // redeclaration and change the owning modules to match.
1571   if (New->getFriendObjectKind() &&
1572       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1573     New->setLocalOwningModule(Old->getOwningModule());
1574     makeMergedDefinitionVisible(New);
1575     return false;
1576   }
1577 
1578   Module *NewM = New->getOwningModule();
1579   Module *OldM = Old->getOwningModule();
1580 
1581   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1582     NewM = NewM->Parent;
1583   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1584     OldM = OldM->Parent;
1585 
1586   if (NewM == OldM)
1587     return false;
1588 
1589   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1590   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1591   if (NewIsModuleInterface || OldIsModuleInterface) {
1592     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1593     //   if a declaration of D [...] appears in the purview of a module, all
1594     //   other such declarations shall appear in the purview of the same module
1595     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1596       << New
1597       << NewIsModuleInterface
1598       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1599       << OldIsModuleInterface
1600       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1601     Diag(Old->getLocation(), diag::note_previous_declaration);
1602     New->setInvalidDecl();
1603     return true;
1604   }
1605 
1606   return false;
1607 }
1608 
1609 static bool isUsingDecl(NamedDecl *D) {
1610   return isa<UsingShadowDecl>(D) ||
1611          isa<UnresolvedUsingTypenameDecl>(D) ||
1612          isa<UnresolvedUsingValueDecl>(D);
1613 }
1614 
1615 /// Removes using shadow declarations from the lookup results.
1616 static void RemoveUsingDecls(LookupResult &R) {
1617   LookupResult::Filter F = R.makeFilter();
1618   while (F.hasNext())
1619     if (isUsingDecl(F.next()))
1620       F.erase();
1621 
1622   F.done();
1623 }
1624 
1625 /// Check for this common pattern:
1626 /// @code
1627 /// class S {
1628 ///   S(const S&); // DO NOT IMPLEMENT
1629 ///   void operator=(const S&); // DO NOT IMPLEMENT
1630 /// };
1631 /// @endcode
1632 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1633   // FIXME: Should check for private access too but access is set after we get
1634   // the decl here.
1635   if (D->doesThisDeclarationHaveABody())
1636     return false;
1637 
1638   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1639     return CD->isCopyConstructor();
1640   return D->isCopyAssignmentOperator();
1641 }
1642 
1643 // We need this to handle
1644 //
1645 // typedef struct {
1646 //   void *foo() { return 0; }
1647 // } A;
1648 //
1649 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1650 // for example. If 'A', foo will have external linkage. If we have '*A',
1651 // foo will have no linkage. Since we can't know until we get to the end
1652 // of the typedef, this function finds out if D might have non-external linkage.
1653 // Callers should verify at the end of the TU if it D has external linkage or
1654 // not.
1655 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1656   const DeclContext *DC = D->getDeclContext();
1657   while (!DC->isTranslationUnit()) {
1658     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1659       if (!RD->hasNameForLinkage())
1660         return true;
1661     }
1662     DC = DC->getParent();
1663   }
1664 
1665   return !D->isExternallyVisible();
1666 }
1667 
1668 // FIXME: This needs to be refactored; some other isInMainFile users want
1669 // these semantics.
1670 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1671   if (S.TUKind != TU_Complete)
1672     return false;
1673   return S.SourceMgr.isInMainFile(Loc);
1674 }
1675 
1676 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1677   assert(D);
1678 
1679   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1680     return false;
1681 
1682   // Ignore all entities declared within templates, and out-of-line definitions
1683   // of members of class templates.
1684   if (D->getDeclContext()->isDependentContext() ||
1685       D->getLexicalDeclContext()->isDependentContext())
1686     return false;
1687 
1688   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1689     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1690       return false;
1691     // A non-out-of-line declaration of a member specialization was implicitly
1692     // instantiated; it's the out-of-line declaration that we're interested in.
1693     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1694         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1695       return false;
1696 
1697     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1698       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1699         return false;
1700     } else {
1701       // 'static inline' functions are defined in headers; don't warn.
1702       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1703         return false;
1704     }
1705 
1706     if (FD->doesThisDeclarationHaveABody() &&
1707         Context.DeclMustBeEmitted(FD))
1708       return false;
1709   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1710     // Constants and utility variables are defined in headers with internal
1711     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1712     // like "inline".)
1713     if (!isMainFileLoc(*this, VD->getLocation()))
1714       return false;
1715 
1716     if (Context.DeclMustBeEmitted(VD))
1717       return false;
1718 
1719     if (VD->isStaticDataMember() &&
1720         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1721       return false;
1722     if (VD->isStaticDataMember() &&
1723         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1724         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1725       return false;
1726 
1727     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1728       return false;
1729   } else {
1730     return false;
1731   }
1732 
1733   // Only warn for unused decls internal to the translation unit.
1734   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1735   // for inline functions defined in the main source file, for instance.
1736   return mightHaveNonExternalLinkage(D);
1737 }
1738 
1739 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1740   if (!D)
1741     return;
1742 
1743   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1744     const FunctionDecl *First = FD->getFirstDecl();
1745     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1746       return; // First should already be in the vector.
1747   }
1748 
1749   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1750     const VarDecl *First = VD->getFirstDecl();
1751     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1752       return; // First should already be in the vector.
1753   }
1754 
1755   if (ShouldWarnIfUnusedFileScopedDecl(D))
1756     UnusedFileScopedDecls.push_back(D);
1757 }
1758 
1759 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1760   if (D->isInvalidDecl())
1761     return false;
1762 
1763   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1764     // For a decomposition declaration, warn if none of the bindings are
1765     // referenced, instead of if the variable itself is referenced (which
1766     // it is, by the bindings' expressions).
1767     for (auto *BD : DD->bindings())
1768       if (BD->isReferenced())
1769         return false;
1770   } else if (!D->getDeclName()) {
1771     return false;
1772   } else if (D->isReferenced() || D->isUsed()) {
1773     return false;
1774   }
1775 
1776   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1777     return false;
1778 
1779   if (isa<LabelDecl>(D))
1780     return true;
1781 
1782   // Except for labels, we only care about unused decls that are local to
1783   // functions.
1784   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1785   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1786     // For dependent types, the diagnostic is deferred.
1787     WithinFunction =
1788         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1789   if (!WithinFunction)
1790     return false;
1791 
1792   if (isa<TypedefNameDecl>(D))
1793     return true;
1794 
1795   // White-list anything that isn't a local variable.
1796   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1797     return false;
1798 
1799   // Types of valid local variables should be complete, so this should succeed.
1800   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1801 
1802     // White-list anything with an __attribute__((unused)) type.
1803     const auto *Ty = VD->getType().getTypePtr();
1804 
1805     // Only look at the outermost level of typedef.
1806     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1807       if (TT->getDecl()->hasAttr<UnusedAttr>())
1808         return false;
1809     }
1810 
1811     // If we failed to complete the type for some reason, or if the type is
1812     // dependent, don't diagnose the variable.
1813     if (Ty->isIncompleteType() || Ty->isDependentType())
1814       return false;
1815 
1816     // Look at the element type to ensure that the warning behaviour is
1817     // consistent for both scalars and arrays.
1818     Ty = Ty->getBaseElementTypeUnsafe();
1819 
1820     if (const TagType *TT = Ty->getAs<TagType>()) {
1821       const TagDecl *Tag = TT->getDecl();
1822       if (Tag->hasAttr<UnusedAttr>())
1823         return false;
1824 
1825       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1826         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1827           return false;
1828 
1829         if (const Expr *Init = VD->getInit()) {
1830           if (const ExprWithCleanups *Cleanups =
1831                   dyn_cast<ExprWithCleanups>(Init))
1832             Init = Cleanups->getSubExpr();
1833           const CXXConstructExpr *Construct =
1834             dyn_cast<CXXConstructExpr>(Init);
1835           if (Construct && !Construct->isElidable()) {
1836             CXXConstructorDecl *CD = Construct->getConstructor();
1837             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1838                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1839               return false;
1840           }
1841 
1842           // Suppress the warning if we don't know how this is constructed, and
1843           // it could possibly be non-trivial constructor.
1844           if (Init->isTypeDependent())
1845             for (const CXXConstructorDecl *Ctor : RD->ctors())
1846               if (!Ctor->isTrivial())
1847                 return false;
1848         }
1849       }
1850     }
1851 
1852     // TODO: __attribute__((unused)) templates?
1853   }
1854 
1855   return true;
1856 }
1857 
1858 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1859                                      FixItHint &Hint) {
1860   if (isa<LabelDecl>(D)) {
1861     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1862         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1863         true);
1864     if (AfterColon.isInvalid())
1865       return;
1866     Hint = FixItHint::CreateRemoval(
1867         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1868   }
1869 }
1870 
1871 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1872   if (D->getTypeForDecl()->isDependentType())
1873     return;
1874 
1875   for (auto *TmpD : D->decls()) {
1876     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1877       DiagnoseUnusedDecl(T);
1878     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1879       DiagnoseUnusedNestedTypedefs(R);
1880   }
1881 }
1882 
1883 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1884 /// unless they are marked attr(unused).
1885 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1886   if (!ShouldDiagnoseUnusedDecl(D))
1887     return;
1888 
1889   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1890     // typedefs can be referenced later on, so the diagnostics are emitted
1891     // at end-of-translation-unit.
1892     UnusedLocalTypedefNameCandidates.insert(TD);
1893     return;
1894   }
1895 
1896   FixItHint Hint;
1897   GenerateFixForUnusedDecl(D, Context, Hint);
1898 
1899   unsigned DiagID;
1900   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1901     DiagID = diag::warn_unused_exception_param;
1902   else if (isa<LabelDecl>(D))
1903     DiagID = diag::warn_unused_label;
1904   else
1905     DiagID = diag::warn_unused_variable;
1906 
1907   Diag(D->getLocation(), DiagID) << D << Hint;
1908 }
1909 
1910 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1911   // Verify that we have no forward references left.  If so, there was a goto
1912   // or address of a label taken, but no definition of it.  Label fwd
1913   // definitions are indicated with a null substmt which is also not a resolved
1914   // MS inline assembly label name.
1915   bool Diagnose = false;
1916   if (L->isMSAsmLabel())
1917     Diagnose = !L->isResolvedMSAsmLabel();
1918   else
1919     Diagnose = L->getStmt() == nullptr;
1920   if (Diagnose)
1921     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1922 }
1923 
1924 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1925   S->mergeNRVOIntoParent();
1926 
1927   if (S->decl_empty()) return;
1928   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1929          "Scope shouldn't contain decls!");
1930 
1931   for (auto *TmpD : S->decls()) {
1932     assert(TmpD && "This decl didn't get pushed??");
1933 
1934     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1935     NamedDecl *D = cast<NamedDecl>(TmpD);
1936 
1937     // Diagnose unused variables in this scope.
1938     if (!S->hasUnrecoverableErrorOccurred()) {
1939       DiagnoseUnusedDecl(D);
1940       if (const auto *RD = dyn_cast<RecordDecl>(D))
1941         DiagnoseUnusedNestedTypedefs(RD);
1942     }
1943 
1944     if (!D->getDeclName()) continue;
1945 
1946     // If this was a forward reference to a label, verify it was defined.
1947     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1948       CheckPoppedLabel(LD, *this);
1949 
1950     // Remove this name from our lexical scope, and warn on it if we haven't
1951     // already.
1952     IdResolver.RemoveDecl(D);
1953     auto ShadowI = ShadowingDecls.find(D);
1954     if (ShadowI != ShadowingDecls.end()) {
1955       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1956         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1957             << D << FD << FD->getParent();
1958         Diag(FD->getLocation(), diag::note_previous_declaration);
1959       }
1960       ShadowingDecls.erase(ShadowI);
1961     }
1962   }
1963 }
1964 
1965 /// Look for an Objective-C class in the translation unit.
1966 ///
1967 /// \param Id The name of the Objective-C class we're looking for. If
1968 /// typo-correction fixes this name, the Id will be updated
1969 /// to the fixed name.
1970 ///
1971 /// \param IdLoc The location of the name in the translation unit.
1972 ///
1973 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1974 /// if there is no class with the given name.
1975 ///
1976 /// \returns The declaration of the named Objective-C class, or NULL if the
1977 /// class could not be found.
1978 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1979                                               SourceLocation IdLoc,
1980                                               bool DoTypoCorrection) {
1981   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1982   // creation from this context.
1983   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1984 
1985   if (!IDecl && DoTypoCorrection) {
1986     // Perform typo correction at the given location, but only if we
1987     // find an Objective-C class name.
1988     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1989     if (TypoCorrection C =
1990             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1991                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1992       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1993       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1994       Id = IDecl->getIdentifier();
1995     }
1996   }
1997   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1998   // This routine must always return a class definition, if any.
1999   if (Def && Def->getDefinition())
2000       Def = Def->getDefinition();
2001   return Def;
2002 }
2003 
2004 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2005 /// from S, where a non-field would be declared. This routine copes
2006 /// with the difference between C and C++ scoping rules in structs and
2007 /// unions. For example, the following code is well-formed in C but
2008 /// ill-formed in C++:
2009 /// @code
2010 /// struct S6 {
2011 ///   enum { BAR } e;
2012 /// };
2013 ///
2014 /// void test_S6() {
2015 ///   struct S6 a;
2016 ///   a.e = BAR;
2017 /// }
2018 /// @endcode
2019 /// For the declaration of BAR, this routine will return a different
2020 /// scope. The scope S will be the scope of the unnamed enumeration
2021 /// within S6. In C++, this routine will return the scope associated
2022 /// with S6, because the enumeration's scope is a transparent
2023 /// context but structures can contain non-field names. In C, this
2024 /// routine will return the translation unit scope, since the
2025 /// enumeration's scope is a transparent context and structures cannot
2026 /// contain non-field names.
2027 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2028   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2029          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2030          (S->isClassScope() && !getLangOpts().CPlusPlus))
2031     S = S->getParent();
2032   return S;
2033 }
2034 
2035 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2036                                ASTContext::GetBuiltinTypeError Error) {
2037   switch (Error) {
2038   case ASTContext::GE_None:
2039     return "";
2040   case ASTContext::GE_Missing_type:
2041     return BuiltinInfo.getHeaderName(ID);
2042   case ASTContext::GE_Missing_stdio:
2043     return "stdio.h";
2044   case ASTContext::GE_Missing_setjmp:
2045     return "setjmp.h";
2046   case ASTContext::GE_Missing_ucontext:
2047     return "ucontext.h";
2048   }
2049   llvm_unreachable("unhandled error kind");
2050 }
2051 
2052 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2053                                   unsigned ID, SourceLocation Loc) {
2054   DeclContext *Parent = Context.getTranslationUnitDecl();
2055 
2056   if (getLangOpts().CPlusPlus) {
2057     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2058         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2059     CLinkageDecl->setImplicit();
2060     Parent->addDecl(CLinkageDecl);
2061     Parent = CLinkageDecl;
2062   }
2063 
2064   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2065                                            /*TInfo=*/nullptr, SC_Extern, false,
2066                                            Type->isFunctionProtoType());
2067   New->setImplicit();
2068   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2069 
2070   // Create Decl objects for each parameter, adding them to the
2071   // FunctionDecl.
2072   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2073     SmallVector<ParmVarDecl *, 16> Params;
2074     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2075       ParmVarDecl *parm = ParmVarDecl::Create(
2076           Context, New, SourceLocation(), SourceLocation(), nullptr,
2077           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2078       parm->setScopeInfo(0, i);
2079       Params.push_back(parm);
2080     }
2081     New->setParams(Params);
2082   }
2083 
2084   AddKnownFunctionAttributes(New);
2085   return New;
2086 }
2087 
2088 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2089 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2090 /// if we're creating this built-in in anticipation of redeclaring the
2091 /// built-in.
2092 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2093                                      Scope *S, bool ForRedeclaration,
2094                                      SourceLocation Loc) {
2095   LookupNecessaryTypesForBuiltin(S, ID);
2096 
2097   ASTContext::GetBuiltinTypeError Error;
2098   QualType R = Context.GetBuiltinType(ID, Error);
2099   if (Error) {
2100     if (!ForRedeclaration)
2101       return nullptr;
2102 
2103     // If we have a builtin without an associated type we should not emit a
2104     // warning when we were not able to find a type for it.
2105     if (Error == ASTContext::GE_Missing_type ||
2106         Context.BuiltinInfo.allowTypeMismatch(ID))
2107       return nullptr;
2108 
2109     // If we could not find a type for setjmp it is because the jmp_buf type was
2110     // not defined prior to the setjmp declaration.
2111     if (Error == ASTContext::GE_Missing_setjmp) {
2112       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2113           << Context.BuiltinInfo.getName(ID);
2114       return nullptr;
2115     }
2116 
2117     // Generally, we emit a warning that the declaration requires the
2118     // appropriate header.
2119     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2120         << getHeaderName(Context.BuiltinInfo, ID, Error)
2121         << Context.BuiltinInfo.getName(ID);
2122     return nullptr;
2123   }
2124 
2125   if (!ForRedeclaration &&
2126       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2127        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2128     Diag(Loc, diag::ext_implicit_lib_function_decl)
2129         << Context.BuiltinInfo.getName(ID) << R;
2130     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2131       Diag(Loc, diag::note_include_header_or_declare)
2132           << Header << Context.BuiltinInfo.getName(ID);
2133   }
2134 
2135   if (R.isNull())
2136     return nullptr;
2137 
2138   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2139   RegisterLocallyScopedExternCDecl(New, S);
2140 
2141   // TUScope is the translation-unit scope to insert this function into.
2142   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2143   // relate Scopes to DeclContexts, and probably eliminate CurContext
2144   // entirely, but we're not there yet.
2145   DeclContext *SavedContext = CurContext;
2146   CurContext = New->getDeclContext();
2147   PushOnScopeChains(New, TUScope);
2148   CurContext = SavedContext;
2149   return New;
2150 }
2151 
2152 /// Typedef declarations don't have linkage, but they still denote the same
2153 /// entity if their types are the same.
2154 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2155 /// isSameEntity.
2156 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2157                                                      TypedefNameDecl *Decl,
2158                                                      LookupResult &Previous) {
2159   // This is only interesting when modules are enabled.
2160   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2161     return;
2162 
2163   // Empty sets are uninteresting.
2164   if (Previous.empty())
2165     return;
2166 
2167   LookupResult::Filter Filter = Previous.makeFilter();
2168   while (Filter.hasNext()) {
2169     NamedDecl *Old = Filter.next();
2170 
2171     // Non-hidden declarations are never ignored.
2172     if (S.isVisible(Old))
2173       continue;
2174 
2175     // Declarations of the same entity are not ignored, even if they have
2176     // different linkages.
2177     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2179                                 Decl->getUnderlyingType()))
2180         continue;
2181 
2182       // If both declarations give a tag declaration a typedef name for linkage
2183       // purposes, then they declare the same entity.
2184       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2185           Decl->getAnonDeclWithTypedefName())
2186         continue;
2187     }
2188 
2189     Filter.erase();
2190   }
2191 
2192   Filter.done();
2193 }
2194 
2195 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2196   QualType OldType;
2197   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2198     OldType = OldTypedef->getUnderlyingType();
2199   else
2200     OldType = Context.getTypeDeclType(Old);
2201   QualType NewType = New->getUnderlyingType();
2202 
2203   if (NewType->isVariablyModifiedType()) {
2204     // Must not redefine a typedef with a variably-modified type.
2205     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2206     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2207       << Kind << NewType;
2208     if (Old->getLocation().isValid())
2209       notePreviousDefinition(Old, New->getLocation());
2210     New->setInvalidDecl();
2211     return true;
2212   }
2213 
2214   if (OldType != NewType &&
2215       !OldType->isDependentType() &&
2216       !NewType->isDependentType() &&
2217       !Context.hasSameType(OldType, NewType)) {
2218     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2219     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2220       << Kind << NewType << OldType;
2221     if (Old->getLocation().isValid())
2222       notePreviousDefinition(Old, New->getLocation());
2223     New->setInvalidDecl();
2224     return true;
2225   }
2226   return false;
2227 }
2228 
2229 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2230 /// same name and scope as a previous declaration 'Old'.  Figure out
2231 /// how to resolve this situation, merging decls or emitting
2232 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2233 ///
2234 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2235                                 LookupResult &OldDecls) {
2236   // If the new decl is known invalid already, don't bother doing any
2237   // merging checks.
2238   if (New->isInvalidDecl()) return;
2239 
2240   // Allow multiple definitions for ObjC built-in typedefs.
2241   // FIXME: Verify the underlying types are equivalent!
2242   if (getLangOpts().ObjC) {
2243     const IdentifierInfo *TypeID = New->getIdentifier();
2244     switch (TypeID->getLength()) {
2245     default: break;
2246     case 2:
2247       {
2248         if (!TypeID->isStr("id"))
2249           break;
2250         QualType T = New->getUnderlyingType();
2251         if (!T->isPointerType())
2252           break;
2253         if (!T->isVoidPointerType()) {
2254           QualType PT = T->castAs<PointerType>()->getPointeeType();
2255           if (!PT->isStructureType())
2256             break;
2257         }
2258         Context.setObjCIdRedefinitionType(T);
2259         // Install the built-in type for 'id', ignoring the current definition.
2260         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2261         return;
2262       }
2263     case 5:
2264       if (!TypeID->isStr("Class"))
2265         break;
2266       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2267       // Install the built-in type for 'Class', ignoring the current definition.
2268       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2269       return;
2270     case 3:
2271       if (!TypeID->isStr("SEL"))
2272         break;
2273       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2274       // Install the built-in type for 'SEL', ignoring the current definition.
2275       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2276       return;
2277     }
2278     // Fall through - the typedef name was not a builtin type.
2279   }
2280 
2281   // Verify the old decl was also a type.
2282   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2283   if (!Old) {
2284     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2285       << New->getDeclName();
2286 
2287     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2288     if (OldD->getLocation().isValid())
2289       notePreviousDefinition(OldD, New->getLocation());
2290 
2291     return New->setInvalidDecl();
2292   }
2293 
2294   // If the old declaration is invalid, just give up here.
2295   if (Old->isInvalidDecl())
2296     return New->setInvalidDecl();
2297 
2298   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2299     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2300     auto *NewTag = New->getAnonDeclWithTypedefName();
2301     NamedDecl *Hidden = nullptr;
2302     if (OldTag && NewTag &&
2303         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2304         !hasVisibleDefinition(OldTag, &Hidden)) {
2305       // There is a definition of this tag, but it is not visible. Use it
2306       // instead of our tag.
2307       New->setTypeForDecl(OldTD->getTypeForDecl());
2308       if (OldTD->isModed())
2309         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2310                                     OldTD->getUnderlyingType());
2311       else
2312         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2313 
2314       // Make the old tag definition visible.
2315       makeMergedDefinitionVisible(Hidden);
2316 
2317       // If this was an unscoped enumeration, yank all of its enumerators
2318       // out of the scope.
2319       if (isa<EnumDecl>(NewTag)) {
2320         Scope *EnumScope = getNonFieldDeclScope(S);
2321         for (auto *D : NewTag->decls()) {
2322           auto *ED = cast<EnumConstantDecl>(D);
2323           assert(EnumScope->isDeclScope(ED));
2324           EnumScope->RemoveDecl(ED);
2325           IdResolver.RemoveDecl(ED);
2326           ED->getLexicalDeclContext()->removeDecl(ED);
2327         }
2328       }
2329     }
2330   }
2331 
2332   // If the typedef types are not identical, reject them in all languages and
2333   // with any extensions enabled.
2334   if (isIncompatibleTypedef(Old, New))
2335     return;
2336 
2337   // The types match.  Link up the redeclaration chain and merge attributes if
2338   // the old declaration was a typedef.
2339   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2340     New->setPreviousDecl(Typedef);
2341     mergeDeclAttributes(New, Old);
2342   }
2343 
2344   if (getLangOpts().MicrosoftExt)
2345     return;
2346 
2347   if (getLangOpts().CPlusPlus) {
2348     // C++ [dcl.typedef]p2:
2349     //   In a given non-class scope, a typedef specifier can be used to
2350     //   redefine the name of any type declared in that scope to refer
2351     //   to the type to which it already refers.
2352     if (!isa<CXXRecordDecl>(CurContext))
2353       return;
2354 
2355     // C++0x [dcl.typedef]p4:
2356     //   In a given class scope, a typedef specifier can be used to redefine
2357     //   any class-name declared in that scope that is not also a typedef-name
2358     //   to refer to the type to which it already refers.
2359     //
2360     // This wording came in via DR424, which was a correction to the
2361     // wording in DR56, which accidentally banned code like:
2362     //
2363     //   struct S {
2364     //     typedef struct A { } A;
2365     //   };
2366     //
2367     // in the C++03 standard. We implement the C++0x semantics, which
2368     // allow the above but disallow
2369     //
2370     //   struct S {
2371     //     typedef int I;
2372     //     typedef int I;
2373     //   };
2374     //
2375     // since that was the intent of DR56.
2376     if (!isa<TypedefNameDecl>(Old))
2377       return;
2378 
2379     Diag(New->getLocation(), diag::err_redefinition)
2380       << New->getDeclName();
2381     notePreviousDefinition(Old, New->getLocation());
2382     return New->setInvalidDecl();
2383   }
2384 
2385   // Modules always permit redefinition of typedefs, as does C11.
2386   if (getLangOpts().Modules || getLangOpts().C11)
2387     return;
2388 
2389   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2390   // is normally mapped to an error, but can be controlled with
2391   // -Wtypedef-redefinition.  If either the original or the redefinition is
2392   // in a system header, don't emit this for compatibility with GCC.
2393   if (getDiagnostics().getSuppressSystemWarnings() &&
2394       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2395       (Old->isImplicit() ||
2396        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2397        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2398     return;
2399 
2400   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2401     << New->getDeclName();
2402   notePreviousDefinition(Old, New->getLocation());
2403 }
2404 
2405 /// DeclhasAttr - returns true if decl Declaration already has the target
2406 /// attribute.
2407 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2408   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2409   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2410   for (const auto *i : D->attrs())
2411     if (i->getKind() == A->getKind()) {
2412       if (Ann) {
2413         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2414           return true;
2415         continue;
2416       }
2417       // FIXME: Don't hardcode this check
2418       if (OA && isa<OwnershipAttr>(i))
2419         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2420       return true;
2421     }
2422 
2423   return false;
2424 }
2425 
2426 static bool isAttributeTargetADefinition(Decl *D) {
2427   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2428     return VD->isThisDeclarationADefinition();
2429   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2430     return TD->isCompleteDefinition() || TD->isBeingDefined();
2431   return true;
2432 }
2433 
2434 /// Merge alignment attributes from \p Old to \p New, taking into account the
2435 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2436 ///
2437 /// \return \c true if any attributes were added to \p New.
2438 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2439   // Look for alignas attributes on Old, and pick out whichever attribute
2440   // specifies the strictest alignment requirement.
2441   AlignedAttr *OldAlignasAttr = nullptr;
2442   AlignedAttr *OldStrictestAlignAttr = nullptr;
2443   unsigned OldAlign = 0;
2444   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2445     // FIXME: We have no way of representing inherited dependent alignments
2446     // in a case like:
2447     //   template<int A, int B> struct alignas(A) X;
2448     //   template<int A, int B> struct alignas(B) X {};
2449     // For now, we just ignore any alignas attributes which are not on the
2450     // definition in such a case.
2451     if (I->isAlignmentDependent())
2452       return false;
2453 
2454     if (I->isAlignas())
2455       OldAlignasAttr = I;
2456 
2457     unsigned Align = I->getAlignment(S.Context);
2458     if (Align > OldAlign) {
2459       OldAlign = Align;
2460       OldStrictestAlignAttr = I;
2461     }
2462   }
2463 
2464   // Look for alignas attributes on New.
2465   AlignedAttr *NewAlignasAttr = nullptr;
2466   unsigned NewAlign = 0;
2467   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2468     if (I->isAlignmentDependent())
2469       return false;
2470 
2471     if (I->isAlignas())
2472       NewAlignasAttr = I;
2473 
2474     unsigned Align = I->getAlignment(S.Context);
2475     if (Align > NewAlign)
2476       NewAlign = Align;
2477   }
2478 
2479   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2480     // Both declarations have 'alignas' attributes. We require them to match.
2481     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2482     // fall short. (If two declarations both have alignas, they must both match
2483     // every definition, and so must match each other if there is a definition.)
2484 
2485     // If either declaration only contains 'alignas(0)' specifiers, then it
2486     // specifies the natural alignment for the type.
2487     if (OldAlign == 0 || NewAlign == 0) {
2488       QualType Ty;
2489       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2490         Ty = VD->getType();
2491       else
2492         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2493 
2494       if (OldAlign == 0)
2495         OldAlign = S.Context.getTypeAlign(Ty);
2496       if (NewAlign == 0)
2497         NewAlign = S.Context.getTypeAlign(Ty);
2498     }
2499 
2500     if (OldAlign != NewAlign) {
2501       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2502         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2503         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2504       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2505     }
2506   }
2507 
2508   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2509     // C++11 [dcl.align]p6:
2510     //   if any declaration of an entity has an alignment-specifier,
2511     //   every defining declaration of that entity shall specify an
2512     //   equivalent alignment.
2513     // C11 6.7.5/7:
2514     //   If the definition of an object does not have an alignment
2515     //   specifier, any other declaration of that object shall also
2516     //   have no alignment specifier.
2517     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2518       << OldAlignasAttr;
2519     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2520       << OldAlignasAttr;
2521   }
2522 
2523   bool AnyAdded = false;
2524 
2525   // Ensure we have an attribute representing the strictest alignment.
2526   if (OldAlign > NewAlign) {
2527     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2528     Clone->setInherited(true);
2529     New->addAttr(Clone);
2530     AnyAdded = true;
2531   }
2532 
2533   // Ensure we have an alignas attribute if the old declaration had one.
2534   if (OldAlignasAttr && !NewAlignasAttr &&
2535       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2536     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2537     Clone->setInherited(true);
2538     New->addAttr(Clone);
2539     AnyAdded = true;
2540   }
2541 
2542   return AnyAdded;
2543 }
2544 
2545 #define WANT_DECL_MERGE_LOGIC
2546 #include "clang/Sema/AttrParsedAttrImpl.inc"
2547 #undef WANT_DECL_MERGE_LOGIC
2548 
2549 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2550                                const InheritableAttr *Attr,
2551                                Sema::AvailabilityMergeKind AMK) {
2552   // Diagnose any mutual exclusions between the attribute that we want to add
2553   // and attributes that already exist on the declaration.
2554   if (!DiagnoseMutualExclusions(S, D, Attr))
2555     return false;
2556 
2557   // This function copies an attribute Attr from a previous declaration to the
2558   // new declaration D if the new declaration doesn't itself have that attribute
2559   // yet or if that attribute allows duplicates.
2560   // If you're adding a new attribute that requires logic different from
2561   // "use explicit attribute on decl if present, else use attribute from
2562   // previous decl", for example if the attribute needs to be consistent
2563   // between redeclarations, you need to call a custom merge function here.
2564   InheritableAttr *NewAttr = nullptr;
2565   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2566     NewAttr = S.mergeAvailabilityAttr(
2567         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2568         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2569         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2570         AA->getPriority());
2571   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2572     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2573   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2574     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2575   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2576     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2577   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2578     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2579   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2580     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2581                                 FA->getFirstArg());
2582   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2583     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2584   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2585     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2586   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2587     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2588                                        IA->getInheritanceModel());
2589   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2590     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2591                                       &S.Context.Idents.get(AA->getSpelling()));
2592   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2593            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2594             isa<CUDAGlobalAttr>(Attr))) {
2595     // CUDA target attributes are part of function signature for
2596     // overloading purposes and must not be merged.
2597     return false;
2598   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2599     NewAttr = S.mergeMinSizeAttr(D, *MA);
2600   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2601     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2602   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2603     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2604   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2605     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2606   else if (isa<AlignedAttr>(Attr))
2607     // AlignedAttrs are handled separately, because we need to handle all
2608     // such attributes on a declaration at the same time.
2609     NewAttr = nullptr;
2610   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2611            (AMK == Sema::AMK_Override ||
2612             AMK == Sema::AMK_ProtocolImplementation))
2613     NewAttr = nullptr;
2614   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2615     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2616   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2617     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2618   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2619     NewAttr = S.mergeImportNameAttr(D, *INA);
2620   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2621     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2622   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2623     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2624   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2625     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2626 
2627   if (NewAttr) {
2628     NewAttr->setInherited(true);
2629     D->addAttr(NewAttr);
2630     if (isa<MSInheritanceAttr>(NewAttr))
2631       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2632     return true;
2633   }
2634 
2635   return false;
2636 }
2637 
2638 static const NamedDecl *getDefinition(const Decl *D) {
2639   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2640     return TD->getDefinition();
2641   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2642     const VarDecl *Def = VD->getDefinition();
2643     if (Def)
2644       return Def;
2645     return VD->getActingDefinition();
2646   }
2647   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2648     const FunctionDecl *Def = nullptr;
2649     if (FD->isDefined(Def, true))
2650       return Def;
2651   }
2652   return nullptr;
2653 }
2654 
2655 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2656   for (const auto *Attribute : D->attrs())
2657     if (Attribute->getKind() == Kind)
2658       return true;
2659   return false;
2660 }
2661 
2662 /// checkNewAttributesAfterDef - If we already have a definition, check that
2663 /// there are no new attributes in this declaration.
2664 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2665   if (!New->hasAttrs())
2666     return;
2667 
2668   const NamedDecl *Def = getDefinition(Old);
2669   if (!Def || Def == New)
2670     return;
2671 
2672   AttrVec &NewAttributes = New->getAttrs();
2673   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2674     const Attr *NewAttribute = NewAttributes[I];
2675 
2676     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2677       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2678         Sema::SkipBodyInfo SkipBody;
2679         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2680 
2681         // If we're skipping this definition, drop the "alias" attribute.
2682         if (SkipBody.ShouldSkip) {
2683           NewAttributes.erase(NewAttributes.begin() + I);
2684           --E;
2685           continue;
2686         }
2687       } else {
2688         VarDecl *VD = cast<VarDecl>(New);
2689         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2690                                 VarDecl::TentativeDefinition
2691                             ? diag::err_alias_after_tentative
2692                             : diag::err_redefinition;
2693         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2694         if (Diag == diag::err_redefinition)
2695           S.notePreviousDefinition(Def, VD->getLocation());
2696         else
2697           S.Diag(Def->getLocation(), diag::note_previous_definition);
2698         VD->setInvalidDecl();
2699       }
2700       ++I;
2701       continue;
2702     }
2703 
2704     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2705       // Tentative definitions are only interesting for the alias check above.
2706       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2707         ++I;
2708         continue;
2709       }
2710     }
2711 
2712     if (hasAttribute(Def, NewAttribute->getKind())) {
2713       ++I;
2714       continue; // regular attr merging will take care of validating this.
2715     }
2716 
2717     if (isa<C11NoReturnAttr>(NewAttribute)) {
2718       // C's _Noreturn is allowed to be added to a function after it is defined.
2719       ++I;
2720       continue;
2721     } else if (isa<UuidAttr>(NewAttribute)) {
2722       // msvc will allow a subsequent definition to add an uuid to a class
2723       ++I;
2724       continue;
2725     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2726       if (AA->isAlignas()) {
2727         // C++11 [dcl.align]p6:
2728         //   if any declaration of an entity has an alignment-specifier,
2729         //   every defining declaration of that entity shall specify an
2730         //   equivalent alignment.
2731         // C11 6.7.5/7:
2732         //   If the definition of an object does not have an alignment
2733         //   specifier, any other declaration of that object shall also
2734         //   have no alignment specifier.
2735         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2736           << AA;
2737         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2738           << AA;
2739         NewAttributes.erase(NewAttributes.begin() + I);
2740         --E;
2741         continue;
2742       }
2743     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2744       // If there is a C definition followed by a redeclaration with this
2745       // attribute then there are two different definitions. In C++, prefer the
2746       // standard diagnostics.
2747       if (!S.getLangOpts().CPlusPlus) {
2748         S.Diag(NewAttribute->getLocation(),
2749                diag::err_loader_uninitialized_redeclaration);
2750         S.Diag(Def->getLocation(), diag::note_previous_definition);
2751         NewAttributes.erase(NewAttributes.begin() + I);
2752         --E;
2753         continue;
2754       }
2755     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2756                cast<VarDecl>(New)->isInline() &&
2757                !cast<VarDecl>(New)->isInlineSpecified()) {
2758       // Don't warn about applying selectany to implicitly inline variables.
2759       // Older compilers and language modes would require the use of selectany
2760       // to make such variables inline, and it would have no effect if we
2761       // honored it.
2762       ++I;
2763       continue;
2764     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2765       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2766       // declarations after defintions.
2767       ++I;
2768       continue;
2769     }
2770 
2771     S.Diag(NewAttribute->getLocation(),
2772            diag::warn_attribute_precede_definition);
2773     S.Diag(Def->getLocation(), diag::note_previous_definition);
2774     NewAttributes.erase(NewAttributes.begin() + I);
2775     --E;
2776   }
2777 }
2778 
2779 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2780                                      const ConstInitAttr *CIAttr,
2781                                      bool AttrBeforeInit) {
2782   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2783 
2784   // Figure out a good way to write this specifier on the old declaration.
2785   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2786   // enough of the attribute list spelling information to extract that without
2787   // heroics.
2788   std::string SuitableSpelling;
2789   if (S.getLangOpts().CPlusPlus20)
2790     SuitableSpelling = std::string(
2791         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2792   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2793     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2794         InsertLoc, {tok::l_square, tok::l_square,
2795                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2796                     S.PP.getIdentifierInfo("require_constant_initialization"),
2797                     tok::r_square, tok::r_square}));
2798   if (SuitableSpelling.empty())
2799     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2800         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2801                     S.PP.getIdentifierInfo("require_constant_initialization"),
2802                     tok::r_paren, tok::r_paren}));
2803   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2804     SuitableSpelling = "constinit";
2805   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2806     SuitableSpelling = "[[clang::require_constant_initialization]]";
2807   if (SuitableSpelling.empty())
2808     SuitableSpelling = "__attribute__((require_constant_initialization))";
2809   SuitableSpelling += " ";
2810 
2811   if (AttrBeforeInit) {
2812     // extern constinit int a;
2813     // int a = 0; // error (missing 'constinit'), accepted as extension
2814     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2815     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2816         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2817     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2818   } else {
2819     // int a = 0;
2820     // constinit extern int a; // error (missing 'constinit')
2821     S.Diag(CIAttr->getLocation(),
2822            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2823                                  : diag::warn_require_const_init_added_too_late)
2824         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2825     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2826         << CIAttr->isConstinit()
2827         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2828   }
2829 }
2830 
2831 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2832 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2833                                AvailabilityMergeKind AMK) {
2834   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2835     UsedAttr *NewAttr = OldAttr->clone(Context);
2836     NewAttr->setInherited(true);
2837     New->addAttr(NewAttr);
2838   }
2839   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2840     RetainAttr *NewAttr = OldAttr->clone(Context);
2841     NewAttr->setInherited(true);
2842     New->addAttr(NewAttr);
2843   }
2844 
2845   if (!Old->hasAttrs() && !New->hasAttrs())
2846     return;
2847 
2848   // [dcl.constinit]p1:
2849   //   If the [constinit] specifier is applied to any declaration of a
2850   //   variable, it shall be applied to the initializing declaration.
2851   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2852   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2853   if (bool(OldConstInit) != bool(NewConstInit)) {
2854     const auto *OldVD = cast<VarDecl>(Old);
2855     auto *NewVD = cast<VarDecl>(New);
2856 
2857     // Find the initializing declaration. Note that we might not have linked
2858     // the new declaration into the redeclaration chain yet.
2859     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2860     if (!InitDecl &&
2861         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2862       InitDecl = NewVD;
2863 
2864     if (InitDecl == NewVD) {
2865       // This is the initializing declaration. If it would inherit 'constinit',
2866       // that's ill-formed. (Note that we do not apply this to the attribute
2867       // form).
2868       if (OldConstInit && OldConstInit->isConstinit())
2869         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2870                                  /*AttrBeforeInit=*/true);
2871     } else if (NewConstInit) {
2872       // This is the first time we've been told that this declaration should
2873       // have a constant initializer. If we already saw the initializing
2874       // declaration, this is too late.
2875       if (InitDecl && InitDecl != NewVD) {
2876         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2877                                  /*AttrBeforeInit=*/false);
2878         NewVD->dropAttr<ConstInitAttr>();
2879       }
2880     }
2881   }
2882 
2883   // Attributes declared post-definition are currently ignored.
2884   checkNewAttributesAfterDef(*this, New, Old);
2885 
2886   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2887     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2888       if (!OldA->isEquivalent(NewA)) {
2889         // This redeclaration changes __asm__ label.
2890         Diag(New->getLocation(), diag::err_different_asm_label);
2891         Diag(OldA->getLocation(), diag::note_previous_declaration);
2892       }
2893     } else if (Old->isUsed()) {
2894       // This redeclaration adds an __asm__ label to a declaration that has
2895       // already been ODR-used.
2896       Diag(New->getLocation(), diag::err_late_asm_label_name)
2897         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2898     }
2899   }
2900 
2901   // Re-declaration cannot add abi_tag's.
2902   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2903     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2904       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2905         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2906                       NewTag) == OldAbiTagAttr->tags_end()) {
2907           Diag(NewAbiTagAttr->getLocation(),
2908                diag::err_new_abi_tag_on_redeclaration)
2909               << NewTag;
2910           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2911         }
2912       }
2913     } else {
2914       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2915       Diag(Old->getLocation(), diag::note_previous_declaration);
2916     }
2917   }
2918 
2919   // This redeclaration adds a section attribute.
2920   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2921     if (auto *VD = dyn_cast<VarDecl>(New)) {
2922       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2923         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2924         Diag(Old->getLocation(), diag::note_previous_declaration);
2925       }
2926     }
2927   }
2928 
2929   // Redeclaration adds code-seg attribute.
2930   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2931   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2932       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2933     Diag(New->getLocation(), diag::warn_mismatched_section)
2934          << 0 /*codeseg*/;
2935     Diag(Old->getLocation(), diag::note_previous_declaration);
2936   }
2937 
2938   if (!Old->hasAttrs())
2939     return;
2940 
2941   bool foundAny = New->hasAttrs();
2942 
2943   // Ensure that any moving of objects within the allocated map is done before
2944   // we process them.
2945   if (!foundAny) New->setAttrs(AttrVec());
2946 
2947   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2948     // Ignore deprecated/unavailable/availability attributes if requested.
2949     AvailabilityMergeKind LocalAMK = AMK_None;
2950     if (isa<DeprecatedAttr>(I) ||
2951         isa<UnavailableAttr>(I) ||
2952         isa<AvailabilityAttr>(I)) {
2953       switch (AMK) {
2954       case AMK_None:
2955         continue;
2956 
2957       case AMK_Redeclaration:
2958       case AMK_Override:
2959       case AMK_ProtocolImplementation:
2960         LocalAMK = AMK;
2961         break;
2962       }
2963     }
2964 
2965     // Already handled.
2966     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
2967       continue;
2968 
2969     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2970       foundAny = true;
2971   }
2972 
2973   if (mergeAlignedAttrs(*this, New, Old))
2974     foundAny = true;
2975 
2976   if (!foundAny) New->dropAttrs();
2977 }
2978 
2979 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2980 /// to the new one.
2981 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2982                                      const ParmVarDecl *oldDecl,
2983                                      Sema &S) {
2984   // C++11 [dcl.attr.depend]p2:
2985   //   The first declaration of a function shall specify the
2986   //   carries_dependency attribute for its declarator-id if any declaration
2987   //   of the function specifies the carries_dependency attribute.
2988   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2989   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2990     S.Diag(CDA->getLocation(),
2991            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2992     // Find the first declaration of the parameter.
2993     // FIXME: Should we build redeclaration chains for function parameters?
2994     const FunctionDecl *FirstFD =
2995       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2996     const ParmVarDecl *FirstVD =
2997       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2998     S.Diag(FirstVD->getLocation(),
2999            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3000   }
3001 
3002   if (!oldDecl->hasAttrs())
3003     return;
3004 
3005   bool foundAny = newDecl->hasAttrs();
3006 
3007   // Ensure that any moving of objects within the allocated map is
3008   // done before we process them.
3009   if (!foundAny) newDecl->setAttrs(AttrVec());
3010 
3011   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3012     if (!DeclHasAttr(newDecl, I)) {
3013       InheritableAttr *newAttr =
3014         cast<InheritableParamAttr>(I->clone(S.Context));
3015       newAttr->setInherited(true);
3016       newDecl->addAttr(newAttr);
3017       foundAny = true;
3018     }
3019   }
3020 
3021   if (!foundAny) newDecl->dropAttrs();
3022 }
3023 
3024 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3025                                 const ParmVarDecl *OldParam,
3026                                 Sema &S) {
3027   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3028     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3029       if (*Oldnullability != *Newnullability) {
3030         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3031           << DiagNullabilityKind(
3032                *Newnullability,
3033                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3034                 != 0))
3035           << DiagNullabilityKind(
3036                *Oldnullability,
3037                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3038                 != 0));
3039         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3040       }
3041     } else {
3042       QualType NewT = NewParam->getType();
3043       NewT = S.Context.getAttributedType(
3044                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3045                          NewT, NewT);
3046       NewParam->setType(NewT);
3047     }
3048   }
3049 }
3050 
3051 namespace {
3052 
3053 /// Used in MergeFunctionDecl to keep track of function parameters in
3054 /// C.
3055 struct GNUCompatibleParamWarning {
3056   ParmVarDecl *OldParm;
3057   ParmVarDecl *NewParm;
3058   QualType PromotedType;
3059 };
3060 
3061 } // end anonymous namespace
3062 
3063 // Determine whether the previous declaration was a definition, implicit
3064 // declaration, or a declaration.
3065 template <typename T>
3066 static std::pair<diag::kind, SourceLocation>
3067 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3068   diag::kind PrevDiag;
3069   SourceLocation OldLocation = Old->getLocation();
3070   if (Old->isThisDeclarationADefinition())
3071     PrevDiag = diag::note_previous_definition;
3072   else if (Old->isImplicit()) {
3073     PrevDiag = diag::note_previous_implicit_declaration;
3074     if (OldLocation.isInvalid())
3075       OldLocation = New->getLocation();
3076   } else
3077     PrevDiag = diag::note_previous_declaration;
3078   return std::make_pair(PrevDiag, OldLocation);
3079 }
3080 
3081 /// canRedefineFunction - checks if a function can be redefined. Currently,
3082 /// only extern inline functions can be redefined, and even then only in
3083 /// GNU89 mode.
3084 static bool canRedefineFunction(const FunctionDecl *FD,
3085                                 const LangOptions& LangOpts) {
3086   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3087           !LangOpts.CPlusPlus &&
3088           FD->isInlineSpecified() &&
3089           FD->getStorageClass() == SC_Extern);
3090 }
3091 
3092 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3093   const AttributedType *AT = T->getAs<AttributedType>();
3094   while (AT && !AT->isCallingConv())
3095     AT = AT->getModifiedType()->getAs<AttributedType>();
3096   return AT;
3097 }
3098 
3099 template <typename T>
3100 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3101   const DeclContext *DC = Old->getDeclContext();
3102   if (DC->isRecord())
3103     return false;
3104 
3105   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3106   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3107     return true;
3108   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3109     return true;
3110   return false;
3111 }
3112 
3113 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3114 static bool isExternC(VarTemplateDecl *) { return false; }
3115 
3116 /// Check whether a redeclaration of an entity introduced by a
3117 /// using-declaration is valid, given that we know it's not an overload
3118 /// (nor a hidden tag declaration).
3119 template<typename ExpectedDecl>
3120 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3121                                    ExpectedDecl *New) {
3122   // C++11 [basic.scope.declarative]p4:
3123   //   Given a set of declarations in a single declarative region, each of
3124   //   which specifies the same unqualified name,
3125   //   -- they shall all refer to the same entity, or all refer to functions
3126   //      and function templates; or
3127   //   -- exactly one declaration shall declare a class name or enumeration
3128   //      name that is not a typedef name and the other declarations shall all
3129   //      refer to the same variable or enumerator, or all refer to functions
3130   //      and function templates; in this case the class name or enumeration
3131   //      name is hidden (3.3.10).
3132 
3133   // C++11 [namespace.udecl]p14:
3134   //   If a function declaration in namespace scope or block scope has the
3135   //   same name and the same parameter-type-list as a function introduced
3136   //   by a using-declaration, and the declarations do not declare the same
3137   //   function, the program is ill-formed.
3138 
3139   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3140   if (Old &&
3141       !Old->getDeclContext()->getRedeclContext()->Equals(
3142           New->getDeclContext()->getRedeclContext()) &&
3143       !(isExternC(Old) && isExternC(New)))
3144     Old = nullptr;
3145 
3146   if (!Old) {
3147     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3148     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3149     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3150     return true;
3151   }
3152   return false;
3153 }
3154 
3155 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3156                                             const FunctionDecl *B) {
3157   assert(A->getNumParams() == B->getNumParams());
3158 
3159   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3160     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3161     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3162     if (AttrA == AttrB)
3163       return true;
3164     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3165            AttrA->isDynamic() == AttrB->isDynamic();
3166   };
3167 
3168   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3169 }
3170 
3171 /// If necessary, adjust the semantic declaration context for a qualified
3172 /// declaration to name the correct inline namespace within the qualifier.
3173 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3174                                                DeclaratorDecl *OldD) {
3175   // The only case where we need to update the DeclContext is when
3176   // redeclaration lookup for a qualified name finds a declaration
3177   // in an inline namespace within the context named by the qualifier:
3178   //
3179   //   inline namespace N { int f(); }
3180   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3181   //
3182   // For unqualified declarations, the semantic context *can* change
3183   // along the redeclaration chain (for local extern declarations,
3184   // extern "C" declarations, and friend declarations in particular).
3185   if (!NewD->getQualifier())
3186     return;
3187 
3188   // NewD is probably already in the right context.
3189   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3190   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3191   if (NamedDC->Equals(SemaDC))
3192     return;
3193 
3194   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3195           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3196          "unexpected context for redeclaration");
3197 
3198   auto *LexDC = NewD->getLexicalDeclContext();
3199   auto FixSemaDC = [=](NamedDecl *D) {
3200     if (!D)
3201       return;
3202     D->setDeclContext(SemaDC);
3203     D->setLexicalDeclContext(LexDC);
3204   };
3205 
3206   FixSemaDC(NewD);
3207   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3208     FixSemaDC(FD->getDescribedFunctionTemplate());
3209   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3210     FixSemaDC(VD->getDescribedVarTemplate());
3211 }
3212 
3213 /// MergeFunctionDecl - We just parsed a function 'New' from
3214 /// declarator D which has the same name and scope as a previous
3215 /// declaration 'Old'.  Figure out how to resolve this situation,
3216 /// merging decls or emitting diagnostics as appropriate.
3217 ///
3218 /// In C++, New and Old must be declarations that are not
3219 /// overloaded. Use IsOverload to determine whether New and Old are
3220 /// overloaded, and to select the Old declaration that New should be
3221 /// merged with.
3222 ///
3223 /// Returns true if there was an error, false otherwise.
3224 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3225                              Scope *S, bool MergeTypeWithOld) {
3226   // Verify the old decl was also a function.
3227   FunctionDecl *Old = OldD->getAsFunction();
3228   if (!Old) {
3229     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3230       if (New->getFriendObjectKind()) {
3231         Diag(New->getLocation(), diag::err_using_decl_friend);
3232         Diag(Shadow->getTargetDecl()->getLocation(),
3233              diag::note_using_decl_target);
3234         Diag(Shadow->getUsingDecl()->getLocation(),
3235              diag::note_using_decl) << 0;
3236         return true;
3237       }
3238 
3239       // Check whether the two declarations might declare the same function.
3240       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3241         return true;
3242       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3243     } else {
3244       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3245         << New->getDeclName();
3246       notePreviousDefinition(OldD, New->getLocation());
3247       return true;
3248     }
3249   }
3250 
3251   // If the old declaration was found in an inline namespace and the new
3252   // declaration was qualified, update the DeclContext to match.
3253   adjustDeclContextForDeclaratorDecl(New, Old);
3254 
3255   // If the old declaration is invalid, just give up here.
3256   if (Old->isInvalidDecl())
3257     return true;
3258 
3259   // Disallow redeclaration of some builtins.
3260   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3261     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3262     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3263         << Old << Old->getType();
3264     return true;
3265   }
3266 
3267   diag::kind PrevDiag;
3268   SourceLocation OldLocation;
3269   std::tie(PrevDiag, OldLocation) =
3270       getNoteDiagForInvalidRedeclaration(Old, New);
3271 
3272   // Don't complain about this if we're in GNU89 mode and the old function
3273   // is an extern inline function.
3274   // Don't complain about specializations. They are not supposed to have
3275   // storage classes.
3276   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3277       New->getStorageClass() == SC_Static &&
3278       Old->hasExternalFormalLinkage() &&
3279       !New->getTemplateSpecializationInfo() &&
3280       !canRedefineFunction(Old, getLangOpts())) {
3281     if (getLangOpts().MicrosoftExt) {
3282       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3283       Diag(OldLocation, PrevDiag);
3284     } else {
3285       Diag(New->getLocation(), diag::err_static_non_static) << New;
3286       Diag(OldLocation, PrevDiag);
3287       return true;
3288     }
3289   }
3290 
3291   if (New->hasAttr<InternalLinkageAttr>() &&
3292       !Old->hasAttr<InternalLinkageAttr>()) {
3293     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3294         << New->getDeclName();
3295     notePreviousDefinition(Old, New->getLocation());
3296     New->dropAttr<InternalLinkageAttr>();
3297   }
3298 
3299   if (CheckRedeclarationModuleOwnership(New, Old))
3300     return true;
3301 
3302   if (!getLangOpts().CPlusPlus) {
3303     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3304     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3305       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3306         << New << OldOvl;
3307 
3308       // Try our best to find a decl that actually has the overloadable
3309       // attribute for the note. In most cases (e.g. programs with only one
3310       // broken declaration/definition), this won't matter.
3311       //
3312       // FIXME: We could do this if we juggled some extra state in
3313       // OverloadableAttr, rather than just removing it.
3314       const Decl *DiagOld = Old;
3315       if (OldOvl) {
3316         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3317           const auto *A = D->getAttr<OverloadableAttr>();
3318           return A && !A->isImplicit();
3319         });
3320         // If we've implicitly added *all* of the overloadable attrs to this
3321         // chain, emitting a "previous redecl" note is pointless.
3322         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3323       }
3324 
3325       if (DiagOld)
3326         Diag(DiagOld->getLocation(),
3327              diag::note_attribute_overloadable_prev_overload)
3328           << OldOvl;
3329 
3330       if (OldOvl)
3331         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3332       else
3333         New->dropAttr<OverloadableAttr>();
3334     }
3335   }
3336 
3337   // If a function is first declared with a calling convention, but is later
3338   // declared or defined without one, all following decls assume the calling
3339   // convention of the first.
3340   //
3341   // It's OK if a function is first declared without a calling convention,
3342   // but is later declared or defined with the default calling convention.
3343   //
3344   // To test if either decl has an explicit calling convention, we look for
3345   // AttributedType sugar nodes on the type as written.  If they are missing or
3346   // were canonicalized away, we assume the calling convention was implicit.
3347   //
3348   // Note also that we DO NOT return at this point, because we still have
3349   // other tests to run.
3350   QualType OldQType = Context.getCanonicalType(Old->getType());
3351   QualType NewQType = Context.getCanonicalType(New->getType());
3352   const FunctionType *OldType = cast<FunctionType>(OldQType);
3353   const FunctionType *NewType = cast<FunctionType>(NewQType);
3354   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3355   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3356   bool RequiresAdjustment = false;
3357 
3358   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3359     FunctionDecl *First = Old->getFirstDecl();
3360     const FunctionType *FT =
3361         First->getType().getCanonicalType()->castAs<FunctionType>();
3362     FunctionType::ExtInfo FI = FT->getExtInfo();
3363     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3364     if (!NewCCExplicit) {
3365       // Inherit the CC from the previous declaration if it was specified
3366       // there but not here.
3367       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3368       RequiresAdjustment = true;
3369     } else if (Old->getBuiltinID()) {
3370       // Builtin attribute isn't propagated to the new one yet at this point,
3371       // so we check if the old one is a builtin.
3372 
3373       // Calling Conventions on a Builtin aren't really useful and setting a
3374       // default calling convention and cdecl'ing some builtin redeclarations is
3375       // common, so warn and ignore the calling convention on the redeclaration.
3376       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3377           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3378           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3379       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3380       RequiresAdjustment = true;
3381     } else {
3382       // Calling conventions aren't compatible, so complain.
3383       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3384       Diag(New->getLocation(), diag::err_cconv_change)
3385         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3386         << !FirstCCExplicit
3387         << (!FirstCCExplicit ? "" :
3388             FunctionType::getNameForCallConv(FI.getCC()));
3389 
3390       // Put the note on the first decl, since it is the one that matters.
3391       Diag(First->getLocation(), diag::note_previous_declaration);
3392       return true;
3393     }
3394   }
3395 
3396   // FIXME: diagnose the other way around?
3397   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3398     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3399     RequiresAdjustment = true;
3400   }
3401 
3402   // Merge regparm attribute.
3403   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3404       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3405     if (NewTypeInfo.getHasRegParm()) {
3406       Diag(New->getLocation(), diag::err_regparm_mismatch)
3407         << NewType->getRegParmType()
3408         << OldType->getRegParmType();
3409       Diag(OldLocation, diag::note_previous_declaration);
3410       return true;
3411     }
3412 
3413     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3414     RequiresAdjustment = true;
3415   }
3416 
3417   // Merge ns_returns_retained attribute.
3418   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3419     if (NewTypeInfo.getProducesResult()) {
3420       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3421           << "'ns_returns_retained'";
3422       Diag(OldLocation, diag::note_previous_declaration);
3423       return true;
3424     }
3425 
3426     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3427     RequiresAdjustment = true;
3428   }
3429 
3430   if (OldTypeInfo.getNoCallerSavedRegs() !=
3431       NewTypeInfo.getNoCallerSavedRegs()) {
3432     if (NewTypeInfo.getNoCallerSavedRegs()) {
3433       AnyX86NoCallerSavedRegistersAttr *Attr =
3434         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3435       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3436       Diag(OldLocation, diag::note_previous_declaration);
3437       return true;
3438     }
3439 
3440     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3441     RequiresAdjustment = true;
3442   }
3443 
3444   if (RequiresAdjustment) {
3445     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3446     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3447     New->setType(QualType(AdjustedType, 0));
3448     NewQType = Context.getCanonicalType(New->getType());
3449   }
3450 
3451   // If this redeclaration makes the function inline, we may need to add it to
3452   // UndefinedButUsed.
3453   if (!Old->isInlined() && New->isInlined() &&
3454       !New->hasAttr<GNUInlineAttr>() &&
3455       !getLangOpts().GNUInline &&
3456       Old->isUsed(false) &&
3457       !Old->isDefined() && !New->isThisDeclarationADefinition())
3458     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3459                                            SourceLocation()));
3460 
3461   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3462   // about it.
3463   if (New->hasAttr<GNUInlineAttr>() &&
3464       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3465     UndefinedButUsed.erase(Old->getCanonicalDecl());
3466   }
3467 
3468   // If pass_object_size params don't match up perfectly, this isn't a valid
3469   // redeclaration.
3470   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3471       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3472     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3473         << New->getDeclName();
3474     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3475     return true;
3476   }
3477 
3478   if (getLangOpts().CPlusPlus) {
3479     // C++1z [over.load]p2
3480     //   Certain function declarations cannot be overloaded:
3481     //     -- Function declarations that differ only in the return type,
3482     //        the exception specification, or both cannot be overloaded.
3483 
3484     // Check the exception specifications match. This may recompute the type of
3485     // both Old and New if it resolved exception specifications, so grab the
3486     // types again after this. Because this updates the type, we do this before
3487     // any of the other checks below, which may update the "de facto" NewQType
3488     // but do not necessarily update the type of New.
3489     if (CheckEquivalentExceptionSpec(Old, New))
3490       return true;
3491     OldQType = Context.getCanonicalType(Old->getType());
3492     NewQType = Context.getCanonicalType(New->getType());
3493 
3494     // Go back to the type source info to compare the declared return types,
3495     // per C++1y [dcl.type.auto]p13:
3496     //   Redeclarations or specializations of a function or function template
3497     //   with a declared return type that uses a placeholder type shall also
3498     //   use that placeholder, not a deduced type.
3499     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3500     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3501     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3502         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3503                                        OldDeclaredReturnType)) {
3504       QualType ResQT;
3505       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3506           OldDeclaredReturnType->isObjCObjectPointerType())
3507         // FIXME: This does the wrong thing for a deduced return type.
3508         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3509       if (ResQT.isNull()) {
3510         if (New->isCXXClassMember() && New->isOutOfLine())
3511           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3512               << New << New->getReturnTypeSourceRange();
3513         else
3514           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3515               << New->getReturnTypeSourceRange();
3516         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3517                                     << Old->getReturnTypeSourceRange();
3518         return true;
3519       }
3520       else
3521         NewQType = ResQT;
3522     }
3523 
3524     QualType OldReturnType = OldType->getReturnType();
3525     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3526     if (OldReturnType != NewReturnType) {
3527       // If this function has a deduced return type and has already been
3528       // defined, copy the deduced value from the old declaration.
3529       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3530       if (OldAT && OldAT->isDeduced()) {
3531         New->setType(
3532             SubstAutoType(New->getType(),
3533                           OldAT->isDependentType() ? Context.DependentTy
3534                                                    : OldAT->getDeducedType()));
3535         NewQType = Context.getCanonicalType(
3536             SubstAutoType(NewQType,
3537                           OldAT->isDependentType() ? Context.DependentTy
3538                                                    : OldAT->getDeducedType()));
3539       }
3540     }
3541 
3542     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3543     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3544     if (OldMethod && NewMethod) {
3545       // Preserve triviality.
3546       NewMethod->setTrivial(OldMethod->isTrivial());
3547 
3548       // MSVC allows explicit template specialization at class scope:
3549       // 2 CXXMethodDecls referring to the same function will be injected.
3550       // We don't want a redeclaration error.
3551       bool IsClassScopeExplicitSpecialization =
3552                               OldMethod->isFunctionTemplateSpecialization() &&
3553                               NewMethod->isFunctionTemplateSpecialization();
3554       bool isFriend = NewMethod->getFriendObjectKind();
3555 
3556       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3557           !IsClassScopeExplicitSpecialization) {
3558         //    -- Member function declarations with the same name and the
3559         //       same parameter types cannot be overloaded if any of them
3560         //       is a static member function declaration.
3561         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3562           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3563           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3564           return true;
3565         }
3566 
3567         // C++ [class.mem]p1:
3568         //   [...] A member shall not be declared twice in the
3569         //   member-specification, except that a nested class or member
3570         //   class template can be declared and then later defined.
3571         if (!inTemplateInstantiation()) {
3572           unsigned NewDiag;
3573           if (isa<CXXConstructorDecl>(OldMethod))
3574             NewDiag = diag::err_constructor_redeclared;
3575           else if (isa<CXXDestructorDecl>(NewMethod))
3576             NewDiag = diag::err_destructor_redeclared;
3577           else if (isa<CXXConversionDecl>(NewMethod))
3578             NewDiag = diag::err_conv_function_redeclared;
3579           else
3580             NewDiag = diag::err_member_redeclared;
3581 
3582           Diag(New->getLocation(), NewDiag);
3583         } else {
3584           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3585             << New << New->getType();
3586         }
3587         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3588         return true;
3589 
3590       // Complain if this is an explicit declaration of a special
3591       // member that was initially declared implicitly.
3592       //
3593       // As an exception, it's okay to befriend such methods in order
3594       // to permit the implicit constructor/destructor/operator calls.
3595       } else if (OldMethod->isImplicit()) {
3596         if (isFriend) {
3597           NewMethod->setImplicit();
3598         } else {
3599           Diag(NewMethod->getLocation(),
3600                diag::err_definition_of_implicitly_declared_member)
3601             << New << getSpecialMember(OldMethod);
3602           return true;
3603         }
3604       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3605         Diag(NewMethod->getLocation(),
3606              diag::err_definition_of_explicitly_defaulted_member)
3607           << getSpecialMember(OldMethod);
3608         return true;
3609       }
3610     }
3611 
3612     // C++11 [dcl.attr.noreturn]p1:
3613     //   The first declaration of a function shall specify the noreturn
3614     //   attribute if any declaration of that function specifies the noreturn
3615     //   attribute.
3616     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3617     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3618       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3619       Diag(Old->getFirstDecl()->getLocation(),
3620            diag::note_noreturn_missing_first_decl);
3621     }
3622 
3623     // C++11 [dcl.attr.depend]p2:
3624     //   The first declaration of a function shall specify the
3625     //   carries_dependency attribute for its declarator-id if any declaration
3626     //   of the function specifies the carries_dependency attribute.
3627     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3628     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3629       Diag(CDA->getLocation(),
3630            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3631       Diag(Old->getFirstDecl()->getLocation(),
3632            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3633     }
3634 
3635     // (C++98 8.3.5p3):
3636     //   All declarations for a function shall agree exactly in both the
3637     //   return type and the parameter-type-list.
3638     // We also want to respect all the extended bits except noreturn.
3639 
3640     // noreturn should now match unless the old type info didn't have it.
3641     QualType OldQTypeForComparison = OldQType;
3642     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3643       auto *OldType = OldQType->castAs<FunctionProtoType>();
3644       const FunctionType *OldTypeForComparison
3645         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3646       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3647       assert(OldQTypeForComparison.isCanonical());
3648     }
3649 
3650     if (haveIncompatibleLanguageLinkages(Old, New)) {
3651       // As a special case, retain the language linkage from previous
3652       // declarations of a friend function as an extension.
3653       //
3654       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3655       // and is useful because there's otherwise no way to specify language
3656       // linkage within class scope.
3657       //
3658       // Check cautiously as the friend object kind isn't yet complete.
3659       if (New->getFriendObjectKind() != Decl::FOK_None) {
3660         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3661         Diag(OldLocation, PrevDiag);
3662       } else {
3663         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3664         Diag(OldLocation, PrevDiag);
3665         return true;
3666       }
3667     }
3668 
3669     // If the function types are compatible, merge the declarations. Ignore the
3670     // exception specifier because it was already checked above in
3671     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3672     // about incompatible types under -fms-compatibility.
3673     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3674                                                          NewQType))
3675       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3676 
3677     // If the types are imprecise (due to dependent constructs in friends or
3678     // local extern declarations), it's OK if they differ. We'll check again
3679     // during instantiation.
3680     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3681       return false;
3682 
3683     // Fall through for conflicting redeclarations and redefinitions.
3684   }
3685 
3686   // C: Function types need to be compatible, not identical. This handles
3687   // duplicate function decls like "void f(int); void f(enum X);" properly.
3688   if (!getLangOpts().CPlusPlus &&
3689       Context.typesAreCompatible(OldQType, NewQType)) {
3690     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3691     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3692     const FunctionProtoType *OldProto = nullptr;
3693     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3694         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3695       // The old declaration provided a function prototype, but the
3696       // new declaration does not. Merge in the prototype.
3697       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3698       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3699       NewQType =
3700           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3701                                   OldProto->getExtProtoInfo());
3702       New->setType(NewQType);
3703       New->setHasInheritedPrototype();
3704 
3705       // Synthesize parameters with the same types.
3706       SmallVector<ParmVarDecl*, 16> Params;
3707       for (const auto &ParamType : OldProto->param_types()) {
3708         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3709                                                  SourceLocation(), nullptr,
3710                                                  ParamType, /*TInfo=*/nullptr,
3711                                                  SC_None, nullptr);
3712         Param->setScopeInfo(0, Params.size());
3713         Param->setImplicit();
3714         Params.push_back(Param);
3715       }
3716 
3717       New->setParams(Params);
3718     }
3719 
3720     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3721   }
3722 
3723   // Check if the function types are compatible when pointer size address
3724   // spaces are ignored.
3725   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3726     return false;
3727 
3728   // GNU C permits a K&R definition to follow a prototype declaration
3729   // if the declared types of the parameters in the K&R definition
3730   // match the types in the prototype declaration, even when the
3731   // promoted types of the parameters from the K&R definition differ
3732   // from the types in the prototype. GCC then keeps the types from
3733   // the prototype.
3734   //
3735   // If a variadic prototype is followed by a non-variadic K&R definition,
3736   // the K&R definition becomes variadic.  This is sort of an edge case, but
3737   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3738   // C99 6.9.1p8.
3739   if (!getLangOpts().CPlusPlus &&
3740       Old->hasPrototype() && !New->hasPrototype() &&
3741       New->getType()->getAs<FunctionProtoType>() &&
3742       Old->getNumParams() == New->getNumParams()) {
3743     SmallVector<QualType, 16> ArgTypes;
3744     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3745     const FunctionProtoType *OldProto
3746       = Old->getType()->getAs<FunctionProtoType>();
3747     const FunctionProtoType *NewProto
3748       = New->getType()->getAs<FunctionProtoType>();
3749 
3750     // Determine whether this is the GNU C extension.
3751     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3752                                                NewProto->getReturnType());
3753     bool LooseCompatible = !MergedReturn.isNull();
3754     for (unsigned Idx = 0, End = Old->getNumParams();
3755          LooseCompatible && Idx != End; ++Idx) {
3756       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3757       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3758       if (Context.typesAreCompatible(OldParm->getType(),
3759                                      NewProto->getParamType(Idx))) {
3760         ArgTypes.push_back(NewParm->getType());
3761       } else if (Context.typesAreCompatible(OldParm->getType(),
3762                                             NewParm->getType(),
3763                                             /*CompareUnqualified=*/true)) {
3764         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3765                                            NewProto->getParamType(Idx) };
3766         Warnings.push_back(Warn);
3767         ArgTypes.push_back(NewParm->getType());
3768       } else
3769         LooseCompatible = false;
3770     }
3771 
3772     if (LooseCompatible) {
3773       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3774         Diag(Warnings[Warn].NewParm->getLocation(),
3775              diag::ext_param_promoted_not_compatible_with_prototype)
3776           << Warnings[Warn].PromotedType
3777           << Warnings[Warn].OldParm->getType();
3778         if (Warnings[Warn].OldParm->getLocation().isValid())
3779           Diag(Warnings[Warn].OldParm->getLocation(),
3780                diag::note_previous_declaration);
3781       }
3782 
3783       if (MergeTypeWithOld)
3784         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3785                                              OldProto->getExtProtoInfo()));
3786       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3787     }
3788 
3789     // Fall through to diagnose conflicting types.
3790   }
3791 
3792   // A function that has already been declared has been redeclared or
3793   // defined with a different type; show an appropriate diagnostic.
3794 
3795   // If the previous declaration was an implicitly-generated builtin
3796   // declaration, then at the very least we should use a specialized note.
3797   unsigned BuiltinID;
3798   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3799     // If it's actually a library-defined builtin function like 'malloc'
3800     // or 'printf', just warn about the incompatible redeclaration.
3801     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3802       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3803       Diag(OldLocation, diag::note_previous_builtin_declaration)
3804         << Old << Old->getType();
3805       return false;
3806     }
3807 
3808     PrevDiag = diag::note_previous_builtin_declaration;
3809   }
3810 
3811   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3812   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3813   return true;
3814 }
3815 
3816 /// Completes the merge of two function declarations that are
3817 /// known to be compatible.
3818 ///
3819 /// This routine handles the merging of attributes and other
3820 /// properties of function declarations from the old declaration to
3821 /// the new declaration, once we know that New is in fact a
3822 /// redeclaration of Old.
3823 ///
3824 /// \returns false
3825 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3826                                         Scope *S, bool MergeTypeWithOld) {
3827   // Merge the attributes
3828   mergeDeclAttributes(New, Old);
3829 
3830   // Merge "pure" flag.
3831   if (Old->isPure())
3832     New->setPure();
3833 
3834   // Merge "used" flag.
3835   if (Old->getMostRecentDecl()->isUsed(false))
3836     New->setIsUsed();
3837 
3838   // Merge attributes from the parameters.  These can mismatch with K&R
3839   // declarations.
3840   if (New->getNumParams() == Old->getNumParams())
3841       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3842         ParmVarDecl *NewParam = New->getParamDecl(i);
3843         ParmVarDecl *OldParam = Old->getParamDecl(i);
3844         mergeParamDeclAttributes(NewParam, OldParam, *this);
3845         mergeParamDeclTypes(NewParam, OldParam, *this);
3846       }
3847 
3848   if (getLangOpts().CPlusPlus)
3849     return MergeCXXFunctionDecl(New, Old, S);
3850 
3851   // Merge the function types so the we get the composite types for the return
3852   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3853   // was visible.
3854   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3855   if (!Merged.isNull() && MergeTypeWithOld)
3856     New->setType(Merged);
3857 
3858   return false;
3859 }
3860 
3861 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3862                                 ObjCMethodDecl *oldMethod) {
3863   // Merge the attributes, including deprecated/unavailable
3864   AvailabilityMergeKind MergeKind =
3865     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3866       ? AMK_ProtocolImplementation
3867       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3868                                                        : AMK_Override;
3869 
3870   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3871 
3872   // Merge attributes from the parameters.
3873   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3874                                        oe = oldMethod->param_end();
3875   for (ObjCMethodDecl::param_iterator
3876          ni = newMethod->param_begin(), ne = newMethod->param_end();
3877        ni != ne && oi != oe; ++ni, ++oi)
3878     mergeParamDeclAttributes(*ni, *oi, *this);
3879 
3880   CheckObjCMethodOverride(newMethod, oldMethod);
3881 }
3882 
3883 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3884   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3885 
3886   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3887          ? diag::err_redefinition_different_type
3888          : diag::err_redeclaration_different_type)
3889     << New->getDeclName() << New->getType() << Old->getType();
3890 
3891   diag::kind PrevDiag;
3892   SourceLocation OldLocation;
3893   std::tie(PrevDiag, OldLocation)
3894     = getNoteDiagForInvalidRedeclaration(Old, New);
3895   S.Diag(OldLocation, PrevDiag);
3896   New->setInvalidDecl();
3897 }
3898 
3899 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3900 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3901 /// emitting diagnostics as appropriate.
3902 ///
3903 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3904 /// to here in AddInitializerToDecl. We can't check them before the initializer
3905 /// is attached.
3906 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3907                              bool MergeTypeWithOld) {
3908   if (New->isInvalidDecl() || Old->isInvalidDecl())
3909     return;
3910 
3911   QualType MergedT;
3912   if (getLangOpts().CPlusPlus) {
3913     if (New->getType()->isUndeducedType()) {
3914       // We don't know what the new type is until the initializer is attached.
3915       return;
3916     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3917       // These could still be something that needs exception specs checked.
3918       return MergeVarDeclExceptionSpecs(New, Old);
3919     }
3920     // C++ [basic.link]p10:
3921     //   [...] the types specified by all declarations referring to a given
3922     //   object or function shall be identical, except that declarations for an
3923     //   array object can specify array types that differ by the presence or
3924     //   absence of a major array bound (8.3.4).
3925     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3926       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3927       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3928 
3929       // We are merging a variable declaration New into Old. If it has an array
3930       // bound, and that bound differs from Old's bound, we should diagnose the
3931       // mismatch.
3932       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3933         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3934              PrevVD = PrevVD->getPreviousDecl()) {
3935           QualType PrevVDTy = PrevVD->getType();
3936           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3937             continue;
3938 
3939           if (!Context.hasSameType(New->getType(), PrevVDTy))
3940             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3941         }
3942       }
3943 
3944       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3945         if (Context.hasSameType(OldArray->getElementType(),
3946                                 NewArray->getElementType()))
3947           MergedT = New->getType();
3948       }
3949       // FIXME: Check visibility. New is hidden but has a complete type. If New
3950       // has no array bound, it should not inherit one from Old, if Old is not
3951       // visible.
3952       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3953         if (Context.hasSameType(OldArray->getElementType(),
3954                                 NewArray->getElementType()))
3955           MergedT = Old->getType();
3956       }
3957     }
3958     else if (New->getType()->isObjCObjectPointerType() &&
3959                Old->getType()->isObjCObjectPointerType()) {
3960       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3961                                               Old->getType());
3962     }
3963   } else {
3964     // C 6.2.7p2:
3965     //   All declarations that refer to the same object or function shall have
3966     //   compatible type.
3967     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3968   }
3969   if (MergedT.isNull()) {
3970     // It's OK if we couldn't merge types if either type is dependent, for a
3971     // block-scope variable. In other cases (static data members of class
3972     // templates, variable templates, ...), we require the types to be
3973     // equivalent.
3974     // FIXME: The C++ standard doesn't say anything about this.
3975     if ((New->getType()->isDependentType() ||
3976          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3977       // If the old type was dependent, we can't merge with it, so the new type
3978       // becomes dependent for now. We'll reproduce the original type when we
3979       // instantiate the TypeSourceInfo for the variable.
3980       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3981         New->setType(Context.DependentTy);
3982       return;
3983     }
3984     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3985   }
3986 
3987   // Don't actually update the type on the new declaration if the old
3988   // declaration was an extern declaration in a different scope.
3989   if (MergeTypeWithOld)
3990     New->setType(MergedT);
3991 }
3992 
3993 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3994                                   LookupResult &Previous) {
3995   // C11 6.2.7p4:
3996   //   For an identifier with internal or external linkage declared
3997   //   in a scope in which a prior declaration of that identifier is
3998   //   visible, if the prior declaration specifies internal or
3999   //   external linkage, the type of the identifier at the later
4000   //   declaration becomes the composite type.
4001   //
4002   // If the variable isn't visible, we do not merge with its type.
4003   if (Previous.isShadowed())
4004     return false;
4005 
4006   if (S.getLangOpts().CPlusPlus) {
4007     // C++11 [dcl.array]p3:
4008     //   If there is a preceding declaration of the entity in the same
4009     //   scope in which the bound was specified, an omitted array bound
4010     //   is taken to be the same as in that earlier declaration.
4011     return NewVD->isPreviousDeclInSameBlockScope() ||
4012            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4013             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4014   } else {
4015     // If the old declaration was function-local, don't merge with its
4016     // type unless we're in the same function.
4017     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4018            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4019   }
4020 }
4021 
4022 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4023 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4024 /// situation, merging decls or emitting diagnostics as appropriate.
4025 ///
4026 /// Tentative definition rules (C99 6.9.2p2) are checked by
4027 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4028 /// definitions here, since the initializer hasn't been attached.
4029 ///
4030 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4031   // If the new decl is already invalid, don't do any other checking.
4032   if (New->isInvalidDecl())
4033     return;
4034 
4035   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4036     return;
4037 
4038   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4039 
4040   // Verify the old decl was also a variable or variable template.
4041   VarDecl *Old = nullptr;
4042   VarTemplateDecl *OldTemplate = nullptr;
4043   if (Previous.isSingleResult()) {
4044     if (NewTemplate) {
4045       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4046       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4047 
4048       if (auto *Shadow =
4049               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4050         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4051           return New->setInvalidDecl();
4052     } else {
4053       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4054 
4055       if (auto *Shadow =
4056               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4057         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4058           return New->setInvalidDecl();
4059     }
4060   }
4061   if (!Old) {
4062     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4063         << New->getDeclName();
4064     notePreviousDefinition(Previous.getRepresentativeDecl(),
4065                            New->getLocation());
4066     return New->setInvalidDecl();
4067   }
4068 
4069   // If the old declaration was found in an inline namespace and the new
4070   // declaration was qualified, update the DeclContext to match.
4071   adjustDeclContextForDeclaratorDecl(New, Old);
4072 
4073   // Ensure the template parameters are compatible.
4074   if (NewTemplate &&
4075       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4076                                       OldTemplate->getTemplateParameters(),
4077                                       /*Complain=*/true, TPL_TemplateMatch))
4078     return New->setInvalidDecl();
4079 
4080   // C++ [class.mem]p1:
4081   //   A member shall not be declared twice in the member-specification [...]
4082   //
4083   // Here, we need only consider static data members.
4084   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4085     Diag(New->getLocation(), diag::err_duplicate_member)
4086       << New->getIdentifier();
4087     Diag(Old->getLocation(), diag::note_previous_declaration);
4088     New->setInvalidDecl();
4089   }
4090 
4091   mergeDeclAttributes(New, Old);
4092   // Warn if an already-declared variable is made a weak_import in a subsequent
4093   // declaration
4094   if (New->hasAttr<WeakImportAttr>() &&
4095       Old->getStorageClass() == SC_None &&
4096       !Old->hasAttr<WeakImportAttr>()) {
4097     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4098     notePreviousDefinition(Old, New->getLocation());
4099     // Remove weak_import attribute on new declaration.
4100     New->dropAttr<WeakImportAttr>();
4101   }
4102 
4103   if (New->hasAttr<InternalLinkageAttr>() &&
4104       !Old->hasAttr<InternalLinkageAttr>()) {
4105     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4106         << New->getDeclName();
4107     notePreviousDefinition(Old, New->getLocation());
4108     New->dropAttr<InternalLinkageAttr>();
4109   }
4110 
4111   // Merge the types.
4112   VarDecl *MostRecent = Old->getMostRecentDecl();
4113   if (MostRecent != Old) {
4114     MergeVarDeclTypes(New, MostRecent,
4115                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4116     if (New->isInvalidDecl())
4117       return;
4118   }
4119 
4120   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4121   if (New->isInvalidDecl())
4122     return;
4123 
4124   diag::kind PrevDiag;
4125   SourceLocation OldLocation;
4126   std::tie(PrevDiag, OldLocation) =
4127       getNoteDiagForInvalidRedeclaration(Old, New);
4128 
4129   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4130   if (New->getStorageClass() == SC_Static &&
4131       !New->isStaticDataMember() &&
4132       Old->hasExternalFormalLinkage()) {
4133     if (getLangOpts().MicrosoftExt) {
4134       Diag(New->getLocation(), diag::ext_static_non_static)
4135           << New->getDeclName();
4136       Diag(OldLocation, PrevDiag);
4137     } else {
4138       Diag(New->getLocation(), diag::err_static_non_static)
4139           << New->getDeclName();
4140       Diag(OldLocation, PrevDiag);
4141       return New->setInvalidDecl();
4142     }
4143   }
4144   // C99 6.2.2p4:
4145   //   For an identifier declared with the storage-class specifier
4146   //   extern in a scope in which a prior declaration of that
4147   //   identifier is visible,23) if the prior declaration specifies
4148   //   internal or external linkage, the linkage of the identifier at
4149   //   the later declaration is the same as the linkage specified at
4150   //   the prior declaration. If no prior declaration is visible, or
4151   //   if the prior declaration specifies no linkage, then the
4152   //   identifier has external linkage.
4153   if (New->hasExternalStorage() && Old->hasLinkage())
4154     /* Okay */;
4155   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4156            !New->isStaticDataMember() &&
4157            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4158     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4159     Diag(OldLocation, PrevDiag);
4160     return New->setInvalidDecl();
4161   }
4162 
4163   // Check if extern is followed by non-extern and vice-versa.
4164   if (New->hasExternalStorage() &&
4165       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4166     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4167     Diag(OldLocation, PrevDiag);
4168     return New->setInvalidDecl();
4169   }
4170   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4171       !New->hasExternalStorage()) {
4172     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4173     Diag(OldLocation, PrevDiag);
4174     return New->setInvalidDecl();
4175   }
4176 
4177   if (CheckRedeclarationModuleOwnership(New, Old))
4178     return;
4179 
4180   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4181 
4182   // FIXME: The test for external storage here seems wrong? We still
4183   // need to check for mismatches.
4184   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4185       // Don't complain about out-of-line definitions of static members.
4186       !(Old->getLexicalDeclContext()->isRecord() &&
4187         !New->getLexicalDeclContext()->isRecord())) {
4188     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4189     Diag(OldLocation, PrevDiag);
4190     return New->setInvalidDecl();
4191   }
4192 
4193   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4194     if (VarDecl *Def = Old->getDefinition()) {
4195       // C++1z [dcl.fcn.spec]p4:
4196       //   If the definition of a variable appears in a translation unit before
4197       //   its first declaration as inline, the program is ill-formed.
4198       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4199       Diag(Def->getLocation(), diag::note_previous_definition);
4200     }
4201   }
4202 
4203   // If this redeclaration makes the variable inline, we may need to add it to
4204   // UndefinedButUsed.
4205   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4206       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4207     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4208                                            SourceLocation()));
4209 
4210   if (New->getTLSKind() != Old->getTLSKind()) {
4211     if (!Old->getTLSKind()) {
4212       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4213       Diag(OldLocation, PrevDiag);
4214     } else if (!New->getTLSKind()) {
4215       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4216       Diag(OldLocation, PrevDiag);
4217     } else {
4218       // Do not allow redeclaration to change the variable between requiring
4219       // static and dynamic initialization.
4220       // FIXME: GCC allows this, but uses the TLS keyword on the first
4221       // declaration to determine the kind. Do we need to be compatible here?
4222       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4223         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4224       Diag(OldLocation, PrevDiag);
4225     }
4226   }
4227 
4228   // C++ doesn't have tentative definitions, so go right ahead and check here.
4229   if (getLangOpts().CPlusPlus &&
4230       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4231     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4232         Old->getCanonicalDecl()->isConstexpr()) {
4233       // This definition won't be a definition any more once it's been merged.
4234       Diag(New->getLocation(),
4235            diag::warn_deprecated_redundant_constexpr_static_def);
4236     } else if (VarDecl *Def = Old->getDefinition()) {
4237       if (checkVarDeclRedefinition(Def, New))
4238         return;
4239     }
4240   }
4241 
4242   if (haveIncompatibleLanguageLinkages(Old, New)) {
4243     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4244     Diag(OldLocation, PrevDiag);
4245     New->setInvalidDecl();
4246     return;
4247   }
4248 
4249   // Merge "used" flag.
4250   if (Old->getMostRecentDecl()->isUsed(false))
4251     New->setIsUsed();
4252 
4253   // Keep a chain of previous declarations.
4254   New->setPreviousDecl(Old);
4255   if (NewTemplate)
4256     NewTemplate->setPreviousDecl(OldTemplate);
4257 
4258   // Inherit access appropriately.
4259   New->setAccess(Old->getAccess());
4260   if (NewTemplate)
4261     NewTemplate->setAccess(New->getAccess());
4262 
4263   if (Old->isInline())
4264     New->setImplicitlyInline();
4265 }
4266 
4267 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4268   SourceManager &SrcMgr = getSourceManager();
4269   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4270   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4271   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4272   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4273   auto &HSI = PP.getHeaderSearchInfo();
4274   StringRef HdrFilename =
4275       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4276 
4277   auto noteFromModuleOrInclude = [&](Module *Mod,
4278                                      SourceLocation IncLoc) -> bool {
4279     // Redefinition errors with modules are common with non modular mapped
4280     // headers, example: a non-modular header H in module A that also gets
4281     // included directly in a TU. Pointing twice to the same header/definition
4282     // is confusing, try to get better diagnostics when modules is on.
4283     if (IncLoc.isValid()) {
4284       if (Mod) {
4285         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4286             << HdrFilename.str() << Mod->getFullModuleName();
4287         if (!Mod->DefinitionLoc.isInvalid())
4288           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4289               << Mod->getFullModuleName();
4290       } else {
4291         Diag(IncLoc, diag::note_redefinition_include_same_file)
4292             << HdrFilename.str();
4293       }
4294       return true;
4295     }
4296 
4297     return false;
4298   };
4299 
4300   // Is it the same file and same offset? Provide more information on why
4301   // this leads to a redefinition error.
4302   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4303     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4304     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4305     bool EmittedDiag =
4306         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4307     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4308 
4309     // If the header has no guards, emit a note suggesting one.
4310     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4311       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4312 
4313     if (EmittedDiag)
4314       return;
4315   }
4316 
4317   // Redefinition coming from different files or couldn't do better above.
4318   if (Old->getLocation().isValid())
4319     Diag(Old->getLocation(), diag::note_previous_definition);
4320 }
4321 
4322 /// We've just determined that \p Old and \p New both appear to be definitions
4323 /// of the same variable. Either diagnose or fix the problem.
4324 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4325   if (!hasVisibleDefinition(Old) &&
4326       (New->getFormalLinkage() == InternalLinkage ||
4327        New->isInline() ||
4328        New->getDescribedVarTemplate() ||
4329        New->getNumTemplateParameterLists() ||
4330        New->getDeclContext()->isDependentContext())) {
4331     // The previous definition is hidden, and multiple definitions are
4332     // permitted (in separate TUs). Demote this to a declaration.
4333     New->demoteThisDefinitionToDeclaration();
4334 
4335     // Make the canonical definition visible.
4336     if (auto *OldTD = Old->getDescribedVarTemplate())
4337       makeMergedDefinitionVisible(OldTD);
4338     makeMergedDefinitionVisible(Old);
4339     return false;
4340   } else {
4341     Diag(New->getLocation(), diag::err_redefinition) << New;
4342     notePreviousDefinition(Old, New->getLocation());
4343     New->setInvalidDecl();
4344     return true;
4345   }
4346 }
4347 
4348 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4349 /// no declarator (e.g. "struct foo;") is parsed.
4350 Decl *
4351 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4352                                  RecordDecl *&AnonRecord) {
4353   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4354                                     AnonRecord);
4355 }
4356 
4357 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4358 // disambiguate entities defined in different scopes.
4359 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4360 // compatibility.
4361 // We will pick our mangling number depending on which version of MSVC is being
4362 // targeted.
4363 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4364   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4365              ? S->getMSCurManglingNumber()
4366              : S->getMSLastManglingNumber();
4367 }
4368 
4369 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4370   if (!Context.getLangOpts().CPlusPlus)
4371     return;
4372 
4373   if (isa<CXXRecordDecl>(Tag->getParent())) {
4374     // If this tag is the direct child of a class, number it if
4375     // it is anonymous.
4376     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4377       return;
4378     MangleNumberingContext &MCtx =
4379         Context.getManglingNumberContext(Tag->getParent());
4380     Context.setManglingNumber(
4381         Tag, MCtx.getManglingNumber(
4382                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4383     return;
4384   }
4385 
4386   // If this tag isn't a direct child of a class, number it if it is local.
4387   MangleNumberingContext *MCtx;
4388   Decl *ManglingContextDecl;
4389   std::tie(MCtx, ManglingContextDecl) =
4390       getCurrentMangleNumberContext(Tag->getDeclContext());
4391   if (MCtx) {
4392     Context.setManglingNumber(
4393         Tag, MCtx->getManglingNumber(
4394                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4395   }
4396 }
4397 
4398 namespace {
4399 struct NonCLikeKind {
4400   enum {
4401     None,
4402     BaseClass,
4403     DefaultMemberInit,
4404     Lambda,
4405     Friend,
4406     OtherMember,
4407     Invalid,
4408   } Kind = None;
4409   SourceRange Range;
4410 
4411   explicit operator bool() { return Kind != None; }
4412 };
4413 }
4414 
4415 /// Determine whether a class is C-like, according to the rules of C++
4416 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4417 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4418   if (RD->isInvalidDecl())
4419     return {NonCLikeKind::Invalid, {}};
4420 
4421   // C++ [dcl.typedef]p9: [P1766R1]
4422   //   An unnamed class with a typedef name for linkage purposes shall not
4423   //
4424   //    -- have any base classes
4425   if (RD->getNumBases())
4426     return {NonCLikeKind::BaseClass,
4427             SourceRange(RD->bases_begin()->getBeginLoc(),
4428                         RD->bases_end()[-1].getEndLoc())};
4429   bool Invalid = false;
4430   for (Decl *D : RD->decls()) {
4431     // Don't complain about things we already diagnosed.
4432     if (D->isInvalidDecl()) {
4433       Invalid = true;
4434       continue;
4435     }
4436 
4437     //  -- have any [...] default member initializers
4438     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4439       if (FD->hasInClassInitializer()) {
4440         auto *Init = FD->getInClassInitializer();
4441         return {NonCLikeKind::DefaultMemberInit,
4442                 Init ? Init->getSourceRange() : D->getSourceRange()};
4443       }
4444       continue;
4445     }
4446 
4447     // FIXME: We don't allow friend declarations. This violates the wording of
4448     // P1766, but not the intent.
4449     if (isa<FriendDecl>(D))
4450       return {NonCLikeKind::Friend, D->getSourceRange()};
4451 
4452     //  -- declare any members other than non-static data members, member
4453     //     enumerations, or member classes,
4454     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4455         isa<EnumDecl>(D))
4456       continue;
4457     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4458     if (!MemberRD) {
4459       if (D->isImplicit())
4460         continue;
4461       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4462     }
4463 
4464     //  -- contain a lambda-expression,
4465     if (MemberRD->isLambda())
4466       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4467 
4468     //  and all member classes shall also satisfy these requirements
4469     //  (recursively).
4470     if (MemberRD->isThisDeclarationADefinition()) {
4471       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4472         return Kind;
4473     }
4474   }
4475 
4476   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4477 }
4478 
4479 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4480                                         TypedefNameDecl *NewTD) {
4481   if (TagFromDeclSpec->isInvalidDecl())
4482     return;
4483 
4484   // Do nothing if the tag already has a name for linkage purposes.
4485   if (TagFromDeclSpec->hasNameForLinkage())
4486     return;
4487 
4488   // A well-formed anonymous tag must always be a TUK_Definition.
4489   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4490 
4491   // The type must match the tag exactly;  no qualifiers allowed.
4492   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4493                            Context.getTagDeclType(TagFromDeclSpec))) {
4494     if (getLangOpts().CPlusPlus)
4495       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4496     return;
4497   }
4498 
4499   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4500   //   An unnamed class with a typedef name for linkage purposes shall [be
4501   //   C-like].
4502   //
4503   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4504   // shouldn't happen, but there are constructs that the language rule doesn't
4505   // disallow for which we can't reasonably avoid computing linkage early.
4506   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4507   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4508                              : NonCLikeKind();
4509   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4510   if (NonCLike || ChangesLinkage) {
4511     if (NonCLike.Kind == NonCLikeKind::Invalid)
4512       return;
4513 
4514     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4515     if (ChangesLinkage) {
4516       // If the linkage changes, we can't accept this as an extension.
4517       if (NonCLike.Kind == NonCLikeKind::None)
4518         DiagID = diag::err_typedef_changes_linkage;
4519       else
4520         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4521     }
4522 
4523     SourceLocation FixitLoc =
4524         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4525     llvm::SmallString<40> TextToInsert;
4526     TextToInsert += ' ';
4527     TextToInsert += NewTD->getIdentifier()->getName();
4528 
4529     Diag(FixitLoc, DiagID)
4530       << isa<TypeAliasDecl>(NewTD)
4531       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4532     if (NonCLike.Kind != NonCLikeKind::None) {
4533       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4534         << NonCLike.Kind - 1 << NonCLike.Range;
4535     }
4536     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4537       << NewTD << isa<TypeAliasDecl>(NewTD);
4538 
4539     if (ChangesLinkage)
4540       return;
4541   }
4542 
4543   // Otherwise, set this as the anon-decl typedef for the tag.
4544   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4545 }
4546 
4547 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4548   switch (T) {
4549   case DeclSpec::TST_class:
4550     return 0;
4551   case DeclSpec::TST_struct:
4552     return 1;
4553   case DeclSpec::TST_interface:
4554     return 2;
4555   case DeclSpec::TST_union:
4556     return 3;
4557   case DeclSpec::TST_enum:
4558     return 4;
4559   default:
4560     llvm_unreachable("unexpected type specifier");
4561   }
4562 }
4563 
4564 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4565 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4566 /// parameters to cope with template friend declarations.
4567 Decl *
4568 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4569                                  MultiTemplateParamsArg TemplateParams,
4570                                  bool IsExplicitInstantiation,
4571                                  RecordDecl *&AnonRecord) {
4572   Decl *TagD = nullptr;
4573   TagDecl *Tag = nullptr;
4574   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4575       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4576       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4577       DS.getTypeSpecType() == DeclSpec::TST_union ||
4578       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4579     TagD = DS.getRepAsDecl();
4580 
4581     if (!TagD) // We probably had an error
4582       return nullptr;
4583 
4584     // Note that the above type specs guarantee that the
4585     // type rep is a Decl, whereas in many of the others
4586     // it's a Type.
4587     if (isa<TagDecl>(TagD))
4588       Tag = cast<TagDecl>(TagD);
4589     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4590       Tag = CTD->getTemplatedDecl();
4591   }
4592 
4593   if (Tag) {
4594     handleTagNumbering(Tag, S);
4595     Tag->setFreeStanding();
4596     if (Tag->isInvalidDecl())
4597       return Tag;
4598   }
4599 
4600   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4601     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4602     // or incomplete types shall not be restrict-qualified."
4603     if (TypeQuals & DeclSpec::TQ_restrict)
4604       Diag(DS.getRestrictSpecLoc(),
4605            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4606            << DS.getSourceRange();
4607   }
4608 
4609   if (DS.isInlineSpecified())
4610     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4611         << getLangOpts().CPlusPlus17;
4612 
4613   if (DS.hasConstexprSpecifier()) {
4614     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4615     // and definitions of functions and variables.
4616     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4617     // the declaration of a function or function template
4618     if (Tag)
4619       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4620           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4621           << static_cast<int>(DS.getConstexprSpecifier());
4622     else
4623       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4624           << static_cast<int>(DS.getConstexprSpecifier());
4625     // Don't emit warnings after this error.
4626     return TagD;
4627   }
4628 
4629   DiagnoseFunctionSpecifiers(DS);
4630 
4631   if (DS.isFriendSpecified()) {
4632     // If we're dealing with a decl but not a TagDecl, assume that
4633     // whatever routines created it handled the friendship aspect.
4634     if (TagD && !Tag)
4635       return nullptr;
4636     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4637   }
4638 
4639   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4640   bool IsExplicitSpecialization =
4641     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4642   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4643       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4644       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4645     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4646     // nested-name-specifier unless it is an explicit instantiation
4647     // or an explicit specialization.
4648     //
4649     // FIXME: We allow class template partial specializations here too, per the
4650     // obvious intent of DR1819.
4651     //
4652     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4653     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4654         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4655     return nullptr;
4656   }
4657 
4658   // Track whether this decl-specifier declares anything.
4659   bool DeclaresAnything = true;
4660 
4661   // Handle anonymous struct definitions.
4662   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4663     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4664         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4665       if (getLangOpts().CPlusPlus ||
4666           Record->getDeclContext()->isRecord()) {
4667         // If CurContext is a DeclContext that can contain statements,
4668         // RecursiveASTVisitor won't visit the decls that
4669         // BuildAnonymousStructOrUnion() will put into CurContext.
4670         // Also store them here so that they can be part of the
4671         // DeclStmt that gets created in this case.
4672         // FIXME: Also return the IndirectFieldDecls created by
4673         // BuildAnonymousStructOr union, for the same reason?
4674         if (CurContext->isFunctionOrMethod())
4675           AnonRecord = Record;
4676         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4677                                            Context.getPrintingPolicy());
4678       }
4679 
4680       DeclaresAnything = false;
4681     }
4682   }
4683 
4684   // C11 6.7.2.1p2:
4685   //   A struct-declaration that does not declare an anonymous structure or
4686   //   anonymous union shall contain a struct-declarator-list.
4687   //
4688   // This rule also existed in C89 and C99; the grammar for struct-declaration
4689   // did not permit a struct-declaration without a struct-declarator-list.
4690   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4691       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4692     // Check for Microsoft C extension: anonymous struct/union member.
4693     // Handle 2 kinds of anonymous struct/union:
4694     //   struct STRUCT;
4695     //   union UNION;
4696     // and
4697     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4698     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4699     if ((Tag && Tag->getDeclName()) ||
4700         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4701       RecordDecl *Record = nullptr;
4702       if (Tag)
4703         Record = dyn_cast<RecordDecl>(Tag);
4704       else if (const RecordType *RT =
4705                    DS.getRepAsType().get()->getAsStructureType())
4706         Record = RT->getDecl();
4707       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4708         Record = UT->getDecl();
4709 
4710       if (Record && getLangOpts().MicrosoftExt) {
4711         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4712             << Record->isUnion() << DS.getSourceRange();
4713         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4714       }
4715 
4716       DeclaresAnything = false;
4717     }
4718   }
4719 
4720   // Skip all the checks below if we have a type error.
4721   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4722       (TagD && TagD->isInvalidDecl()))
4723     return TagD;
4724 
4725   if (getLangOpts().CPlusPlus &&
4726       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4727     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4728       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4729           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4730         DeclaresAnything = false;
4731 
4732   if (!DS.isMissingDeclaratorOk()) {
4733     // Customize diagnostic for a typedef missing a name.
4734     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4735       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4736           << DS.getSourceRange();
4737     else
4738       DeclaresAnything = false;
4739   }
4740 
4741   if (DS.isModulePrivateSpecified() &&
4742       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4743     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4744       << Tag->getTagKind()
4745       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4746 
4747   ActOnDocumentableDecl(TagD);
4748 
4749   // C 6.7/2:
4750   //   A declaration [...] shall declare at least a declarator [...], a tag,
4751   //   or the members of an enumeration.
4752   // C++ [dcl.dcl]p3:
4753   //   [If there are no declarators], and except for the declaration of an
4754   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4755   //   names into the program, or shall redeclare a name introduced by a
4756   //   previous declaration.
4757   if (!DeclaresAnything) {
4758     // In C, we allow this as a (popular) extension / bug. Don't bother
4759     // producing further diagnostics for redundant qualifiers after this.
4760     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4761                                ? diag::err_no_declarators
4762                                : diag::ext_no_declarators)
4763         << DS.getSourceRange();
4764     return TagD;
4765   }
4766 
4767   // C++ [dcl.stc]p1:
4768   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4769   //   init-declarator-list of the declaration shall not be empty.
4770   // C++ [dcl.fct.spec]p1:
4771   //   If a cv-qualifier appears in a decl-specifier-seq, the
4772   //   init-declarator-list of the declaration shall not be empty.
4773   //
4774   // Spurious qualifiers here appear to be valid in C.
4775   unsigned DiagID = diag::warn_standalone_specifier;
4776   if (getLangOpts().CPlusPlus)
4777     DiagID = diag::ext_standalone_specifier;
4778 
4779   // Note that a linkage-specification sets a storage class, but
4780   // 'extern "C" struct foo;' is actually valid and not theoretically
4781   // useless.
4782   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4783     if (SCS == DeclSpec::SCS_mutable)
4784       // Since mutable is not a viable storage class specifier in C, there is
4785       // no reason to treat it as an extension. Instead, diagnose as an error.
4786       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4787     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4788       Diag(DS.getStorageClassSpecLoc(), DiagID)
4789         << DeclSpec::getSpecifierName(SCS);
4790   }
4791 
4792   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4793     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4794       << DeclSpec::getSpecifierName(TSCS);
4795   if (DS.getTypeQualifiers()) {
4796     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4797       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4798     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4799       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4800     // Restrict is covered above.
4801     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4802       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4803     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4804       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4805   }
4806 
4807   // Warn about ignored type attributes, for example:
4808   // __attribute__((aligned)) struct A;
4809   // Attributes should be placed after tag to apply to type declaration.
4810   if (!DS.getAttributes().empty()) {
4811     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4812     if (TypeSpecType == DeclSpec::TST_class ||
4813         TypeSpecType == DeclSpec::TST_struct ||
4814         TypeSpecType == DeclSpec::TST_interface ||
4815         TypeSpecType == DeclSpec::TST_union ||
4816         TypeSpecType == DeclSpec::TST_enum) {
4817       for (const ParsedAttr &AL : DS.getAttributes())
4818         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4819             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4820     }
4821   }
4822 
4823   return TagD;
4824 }
4825 
4826 /// We are trying to inject an anonymous member into the given scope;
4827 /// check if there's an existing declaration that can't be overloaded.
4828 ///
4829 /// \return true if this is a forbidden redeclaration
4830 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4831                                          Scope *S,
4832                                          DeclContext *Owner,
4833                                          DeclarationName Name,
4834                                          SourceLocation NameLoc,
4835                                          bool IsUnion) {
4836   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4837                  Sema::ForVisibleRedeclaration);
4838   if (!SemaRef.LookupName(R, S)) return false;
4839 
4840   // Pick a representative declaration.
4841   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4842   assert(PrevDecl && "Expected a non-null Decl");
4843 
4844   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4845     return false;
4846 
4847   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4848     << IsUnion << Name;
4849   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4850 
4851   return true;
4852 }
4853 
4854 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4855 /// anonymous struct or union AnonRecord into the owning context Owner
4856 /// and scope S. This routine will be invoked just after we realize
4857 /// that an unnamed union or struct is actually an anonymous union or
4858 /// struct, e.g.,
4859 ///
4860 /// @code
4861 /// union {
4862 ///   int i;
4863 ///   float f;
4864 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4865 ///    // f into the surrounding scope.x
4866 /// @endcode
4867 ///
4868 /// This routine is recursive, injecting the names of nested anonymous
4869 /// structs/unions into the owning context and scope as well.
4870 static bool
4871 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4872                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4873                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4874   bool Invalid = false;
4875 
4876   // Look every FieldDecl and IndirectFieldDecl with a name.
4877   for (auto *D : AnonRecord->decls()) {
4878     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4879         cast<NamedDecl>(D)->getDeclName()) {
4880       ValueDecl *VD = cast<ValueDecl>(D);
4881       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4882                                        VD->getLocation(),
4883                                        AnonRecord->isUnion())) {
4884         // C++ [class.union]p2:
4885         //   The names of the members of an anonymous union shall be
4886         //   distinct from the names of any other entity in the
4887         //   scope in which the anonymous union is declared.
4888         Invalid = true;
4889       } else {
4890         // C++ [class.union]p2:
4891         //   For the purpose of name lookup, after the anonymous union
4892         //   definition, the members of the anonymous union are
4893         //   considered to have been defined in the scope in which the
4894         //   anonymous union is declared.
4895         unsigned OldChainingSize = Chaining.size();
4896         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4897           Chaining.append(IF->chain_begin(), IF->chain_end());
4898         else
4899           Chaining.push_back(VD);
4900 
4901         assert(Chaining.size() >= 2);
4902         NamedDecl **NamedChain =
4903           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4904         for (unsigned i = 0; i < Chaining.size(); i++)
4905           NamedChain[i] = Chaining[i];
4906 
4907         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4908             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4909             VD->getType(), {NamedChain, Chaining.size()});
4910 
4911         for (const auto *Attr : VD->attrs())
4912           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4913 
4914         IndirectField->setAccess(AS);
4915         IndirectField->setImplicit();
4916         SemaRef.PushOnScopeChains(IndirectField, S);
4917 
4918         // That includes picking up the appropriate access specifier.
4919         if (AS != AS_none) IndirectField->setAccess(AS);
4920 
4921         Chaining.resize(OldChainingSize);
4922       }
4923     }
4924   }
4925 
4926   return Invalid;
4927 }
4928 
4929 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4930 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4931 /// illegal input values are mapped to SC_None.
4932 static StorageClass
4933 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4934   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4935   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4936          "Parser allowed 'typedef' as storage class VarDecl.");
4937   switch (StorageClassSpec) {
4938   case DeclSpec::SCS_unspecified:    return SC_None;
4939   case DeclSpec::SCS_extern:
4940     if (DS.isExternInLinkageSpec())
4941       return SC_None;
4942     return SC_Extern;
4943   case DeclSpec::SCS_static:         return SC_Static;
4944   case DeclSpec::SCS_auto:           return SC_Auto;
4945   case DeclSpec::SCS_register:       return SC_Register;
4946   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4947     // Illegal SCSs map to None: error reporting is up to the caller.
4948   case DeclSpec::SCS_mutable:        // Fall through.
4949   case DeclSpec::SCS_typedef:        return SC_None;
4950   }
4951   llvm_unreachable("unknown storage class specifier");
4952 }
4953 
4954 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4955   assert(Record->hasInClassInitializer());
4956 
4957   for (const auto *I : Record->decls()) {
4958     const auto *FD = dyn_cast<FieldDecl>(I);
4959     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4960       FD = IFD->getAnonField();
4961     if (FD && FD->hasInClassInitializer())
4962       return FD->getLocation();
4963   }
4964 
4965   llvm_unreachable("couldn't find in-class initializer");
4966 }
4967 
4968 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4969                                       SourceLocation DefaultInitLoc) {
4970   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4971     return;
4972 
4973   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4974   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4975 }
4976 
4977 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4978                                       CXXRecordDecl *AnonUnion) {
4979   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4980     return;
4981 
4982   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4983 }
4984 
4985 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4986 /// anonymous structure or union. Anonymous unions are a C++ feature
4987 /// (C++ [class.union]) and a C11 feature; anonymous structures
4988 /// are a C11 feature and GNU C++ extension.
4989 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4990                                         AccessSpecifier AS,
4991                                         RecordDecl *Record,
4992                                         const PrintingPolicy &Policy) {
4993   DeclContext *Owner = Record->getDeclContext();
4994 
4995   // Diagnose whether this anonymous struct/union is an extension.
4996   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4997     Diag(Record->getLocation(), diag::ext_anonymous_union);
4998   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4999     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5000   else if (!Record->isUnion() && !getLangOpts().C11)
5001     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5002 
5003   // C and C++ require different kinds of checks for anonymous
5004   // structs/unions.
5005   bool Invalid = false;
5006   if (getLangOpts().CPlusPlus) {
5007     const char *PrevSpec = nullptr;
5008     if (Record->isUnion()) {
5009       // C++ [class.union]p6:
5010       // C++17 [class.union.anon]p2:
5011       //   Anonymous unions declared in a named namespace or in the
5012       //   global namespace shall be declared static.
5013       unsigned DiagID;
5014       DeclContext *OwnerScope = Owner->getRedeclContext();
5015       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5016           (OwnerScope->isTranslationUnit() ||
5017            (OwnerScope->isNamespace() &&
5018             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5019         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5020           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5021 
5022         // Recover by adding 'static'.
5023         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5024                                PrevSpec, DiagID, Policy);
5025       }
5026       // C++ [class.union]p6:
5027       //   A storage class is not allowed in a declaration of an
5028       //   anonymous union in a class scope.
5029       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5030                isa<RecordDecl>(Owner)) {
5031         Diag(DS.getStorageClassSpecLoc(),
5032              diag::err_anonymous_union_with_storage_spec)
5033           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5034 
5035         // Recover by removing the storage specifier.
5036         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5037                                SourceLocation(),
5038                                PrevSpec, DiagID, Context.getPrintingPolicy());
5039       }
5040     }
5041 
5042     // Ignore const/volatile/restrict qualifiers.
5043     if (DS.getTypeQualifiers()) {
5044       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5045         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5046           << Record->isUnion() << "const"
5047           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5048       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5049         Diag(DS.getVolatileSpecLoc(),
5050              diag::ext_anonymous_struct_union_qualified)
5051           << Record->isUnion() << "volatile"
5052           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5053       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5054         Diag(DS.getRestrictSpecLoc(),
5055              diag::ext_anonymous_struct_union_qualified)
5056           << Record->isUnion() << "restrict"
5057           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5058       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5059         Diag(DS.getAtomicSpecLoc(),
5060              diag::ext_anonymous_struct_union_qualified)
5061           << Record->isUnion() << "_Atomic"
5062           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5063       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5064         Diag(DS.getUnalignedSpecLoc(),
5065              diag::ext_anonymous_struct_union_qualified)
5066           << Record->isUnion() << "__unaligned"
5067           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5068 
5069       DS.ClearTypeQualifiers();
5070     }
5071 
5072     // C++ [class.union]p2:
5073     //   The member-specification of an anonymous union shall only
5074     //   define non-static data members. [Note: nested types and
5075     //   functions cannot be declared within an anonymous union. ]
5076     for (auto *Mem : Record->decls()) {
5077       // Ignore invalid declarations; we already diagnosed them.
5078       if (Mem->isInvalidDecl())
5079         continue;
5080 
5081       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5082         // C++ [class.union]p3:
5083         //   An anonymous union shall not have private or protected
5084         //   members (clause 11).
5085         assert(FD->getAccess() != AS_none);
5086         if (FD->getAccess() != AS_public) {
5087           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5088             << Record->isUnion() << (FD->getAccess() == AS_protected);
5089           Invalid = true;
5090         }
5091 
5092         // C++ [class.union]p1
5093         //   An object of a class with a non-trivial constructor, a non-trivial
5094         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5095         //   assignment operator cannot be a member of a union, nor can an
5096         //   array of such objects.
5097         if (CheckNontrivialField(FD))
5098           Invalid = true;
5099       } else if (Mem->isImplicit()) {
5100         // Any implicit members are fine.
5101       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5102         // This is a type that showed up in an
5103         // elaborated-type-specifier inside the anonymous struct or
5104         // union, but which actually declares a type outside of the
5105         // anonymous struct or union. It's okay.
5106       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5107         if (!MemRecord->isAnonymousStructOrUnion() &&
5108             MemRecord->getDeclName()) {
5109           // Visual C++ allows type definition in anonymous struct or union.
5110           if (getLangOpts().MicrosoftExt)
5111             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5112               << Record->isUnion();
5113           else {
5114             // This is a nested type declaration.
5115             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5116               << Record->isUnion();
5117             Invalid = true;
5118           }
5119         } else {
5120           // This is an anonymous type definition within another anonymous type.
5121           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5122           // not part of standard C++.
5123           Diag(MemRecord->getLocation(),
5124                diag::ext_anonymous_record_with_anonymous_type)
5125             << Record->isUnion();
5126         }
5127       } else if (isa<AccessSpecDecl>(Mem)) {
5128         // Any access specifier is fine.
5129       } else if (isa<StaticAssertDecl>(Mem)) {
5130         // In C++1z, static_assert declarations are also fine.
5131       } else {
5132         // We have something that isn't a non-static data
5133         // member. Complain about it.
5134         unsigned DK = diag::err_anonymous_record_bad_member;
5135         if (isa<TypeDecl>(Mem))
5136           DK = diag::err_anonymous_record_with_type;
5137         else if (isa<FunctionDecl>(Mem))
5138           DK = diag::err_anonymous_record_with_function;
5139         else if (isa<VarDecl>(Mem))
5140           DK = diag::err_anonymous_record_with_static;
5141 
5142         // Visual C++ allows type definition in anonymous struct or union.
5143         if (getLangOpts().MicrosoftExt &&
5144             DK == diag::err_anonymous_record_with_type)
5145           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5146             << Record->isUnion();
5147         else {
5148           Diag(Mem->getLocation(), DK) << Record->isUnion();
5149           Invalid = true;
5150         }
5151       }
5152     }
5153 
5154     // C++11 [class.union]p8 (DR1460):
5155     //   At most one variant member of a union may have a
5156     //   brace-or-equal-initializer.
5157     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5158         Owner->isRecord())
5159       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5160                                 cast<CXXRecordDecl>(Record));
5161   }
5162 
5163   if (!Record->isUnion() && !Owner->isRecord()) {
5164     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5165       << getLangOpts().CPlusPlus;
5166     Invalid = true;
5167   }
5168 
5169   // C++ [dcl.dcl]p3:
5170   //   [If there are no declarators], and except for the declaration of an
5171   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5172   //   names into the program
5173   // C++ [class.mem]p2:
5174   //   each such member-declaration shall either declare at least one member
5175   //   name of the class or declare at least one unnamed bit-field
5176   //
5177   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5178   if (getLangOpts().CPlusPlus && Record->field_empty())
5179     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5180 
5181   // Mock up a declarator.
5182   Declarator Dc(DS, DeclaratorContext::Member);
5183   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5184   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5185 
5186   // Create a declaration for this anonymous struct/union.
5187   NamedDecl *Anon = nullptr;
5188   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5189     Anon = FieldDecl::Create(
5190         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5191         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5192         /*BitWidth=*/nullptr, /*Mutable=*/false,
5193         /*InitStyle=*/ICIS_NoInit);
5194     Anon->setAccess(AS);
5195     ProcessDeclAttributes(S, Anon, Dc);
5196 
5197     if (getLangOpts().CPlusPlus)
5198       FieldCollector->Add(cast<FieldDecl>(Anon));
5199   } else {
5200     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5201     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5202     if (SCSpec == DeclSpec::SCS_mutable) {
5203       // mutable can only appear on non-static class members, so it's always
5204       // an error here
5205       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5206       Invalid = true;
5207       SC = SC_None;
5208     }
5209 
5210     assert(DS.getAttributes().empty() && "No attribute expected");
5211     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5212                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5213                            Context.getTypeDeclType(Record), TInfo, SC);
5214 
5215     // Default-initialize the implicit variable. This initialization will be
5216     // trivial in almost all cases, except if a union member has an in-class
5217     // initializer:
5218     //   union { int n = 0; };
5219     if (!Invalid)
5220       ActOnUninitializedDecl(Anon);
5221   }
5222   Anon->setImplicit();
5223 
5224   // Mark this as an anonymous struct/union type.
5225   Record->setAnonymousStructOrUnion(true);
5226 
5227   // Add the anonymous struct/union object to the current
5228   // context. We'll be referencing this object when we refer to one of
5229   // its members.
5230   Owner->addDecl(Anon);
5231 
5232   // Inject the members of the anonymous struct/union into the owning
5233   // context and into the identifier resolver chain for name lookup
5234   // purposes.
5235   SmallVector<NamedDecl*, 2> Chain;
5236   Chain.push_back(Anon);
5237 
5238   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5239     Invalid = true;
5240 
5241   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5242     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5243       MangleNumberingContext *MCtx;
5244       Decl *ManglingContextDecl;
5245       std::tie(MCtx, ManglingContextDecl) =
5246           getCurrentMangleNumberContext(NewVD->getDeclContext());
5247       if (MCtx) {
5248         Context.setManglingNumber(
5249             NewVD, MCtx->getManglingNumber(
5250                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5251         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5252       }
5253     }
5254   }
5255 
5256   if (Invalid)
5257     Anon->setInvalidDecl();
5258 
5259   return Anon;
5260 }
5261 
5262 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5263 /// Microsoft C anonymous structure.
5264 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5265 /// Example:
5266 ///
5267 /// struct A { int a; };
5268 /// struct B { struct A; int b; };
5269 ///
5270 /// void foo() {
5271 ///   B var;
5272 ///   var.a = 3;
5273 /// }
5274 ///
5275 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5276                                            RecordDecl *Record) {
5277   assert(Record && "expected a record!");
5278 
5279   // Mock up a declarator.
5280   Declarator Dc(DS, DeclaratorContext::TypeName);
5281   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5282   assert(TInfo && "couldn't build declarator info for anonymous struct");
5283 
5284   auto *ParentDecl = cast<RecordDecl>(CurContext);
5285   QualType RecTy = Context.getTypeDeclType(Record);
5286 
5287   // Create a declaration for this anonymous struct.
5288   NamedDecl *Anon =
5289       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5290                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5291                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5292                         /*InitStyle=*/ICIS_NoInit);
5293   Anon->setImplicit();
5294 
5295   // Add the anonymous struct object to the current context.
5296   CurContext->addDecl(Anon);
5297 
5298   // Inject the members of the anonymous struct into the current
5299   // context and into the identifier resolver chain for name lookup
5300   // purposes.
5301   SmallVector<NamedDecl*, 2> Chain;
5302   Chain.push_back(Anon);
5303 
5304   RecordDecl *RecordDef = Record->getDefinition();
5305   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5306                                diag::err_field_incomplete_or_sizeless) ||
5307       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5308                                           AS_none, Chain)) {
5309     Anon->setInvalidDecl();
5310     ParentDecl->setInvalidDecl();
5311   }
5312 
5313   return Anon;
5314 }
5315 
5316 /// GetNameForDeclarator - Determine the full declaration name for the
5317 /// given Declarator.
5318 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5319   return GetNameFromUnqualifiedId(D.getName());
5320 }
5321 
5322 /// Retrieves the declaration name from a parsed unqualified-id.
5323 DeclarationNameInfo
5324 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5325   DeclarationNameInfo NameInfo;
5326   NameInfo.setLoc(Name.StartLocation);
5327 
5328   switch (Name.getKind()) {
5329 
5330   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5331   case UnqualifiedIdKind::IK_Identifier:
5332     NameInfo.setName(Name.Identifier);
5333     return NameInfo;
5334 
5335   case UnqualifiedIdKind::IK_DeductionGuideName: {
5336     // C++ [temp.deduct.guide]p3:
5337     //   The simple-template-id shall name a class template specialization.
5338     //   The template-name shall be the same identifier as the template-name
5339     //   of the simple-template-id.
5340     // These together intend to imply that the template-name shall name a
5341     // class template.
5342     // FIXME: template<typename T> struct X {};
5343     //        template<typename T> using Y = X<T>;
5344     //        Y(int) -> Y<int>;
5345     //   satisfies these rules but does not name a class template.
5346     TemplateName TN = Name.TemplateName.get().get();
5347     auto *Template = TN.getAsTemplateDecl();
5348     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5349       Diag(Name.StartLocation,
5350            diag::err_deduction_guide_name_not_class_template)
5351         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5352       if (Template)
5353         Diag(Template->getLocation(), diag::note_template_decl_here);
5354       return DeclarationNameInfo();
5355     }
5356 
5357     NameInfo.setName(
5358         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5359     return NameInfo;
5360   }
5361 
5362   case UnqualifiedIdKind::IK_OperatorFunctionId:
5363     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5364                                            Name.OperatorFunctionId.Operator));
5365     NameInfo.setCXXOperatorNameRange(SourceRange(
5366         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5367     return NameInfo;
5368 
5369   case UnqualifiedIdKind::IK_LiteralOperatorId:
5370     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5371                                                            Name.Identifier));
5372     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5373     return NameInfo;
5374 
5375   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5376     TypeSourceInfo *TInfo;
5377     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5378     if (Ty.isNull())
5379       return DeclarationNameInfo();
5380     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5381                                                Context.getCanonicalType(Ty)));
5382     NameInfo.setNamedTypeInfo(TInfo);
5383     return NameInfo;
5384   }
5385 
5386   case UnqualifiedIdKind::IK_ConstructorName: {
5387     TypeSourceInfo *TInfo;
5388     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5389     if (Ty.isNull())
5390       return DeclarationNameInfo();
5391     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5392                                               Context.getCanonicalType(Ty)));
5393     NameInfo.setNamedTypeInfo(TInfo);
5394     return NameInfo;
5395   }
5396 
5397   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5398     // In well-formed code, we can only have a constructor
5399     // template-id that refers to the current context, so go there
5400     // to find the actual type being constructed.
5401     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5402     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5403       return DeclarationNameInfo();
5404 
5405     // Determine the type of the class being constructed.
5406     QualType CurClassType = Context.getTypeDeclType(CurClass);
5407 
5408     // FIXME: Check two things: that the template-id names the same type as
5409     // CurClassType, and that the template-id does not occur when the name
5410     // was qualified.
5411 
5412     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5413                                     Context.getCanonicalType(CurClassType)));
5414     // FIXME: should we retrieve TypeSourceInfo?
5415     NameInfo.setNamedTypeInfo(nullptr);
5416     return NameInfo;
5417   }
5418 
5419   case UnqualifiedIdKind::IK_DestructorName: {
5420     TypeSourceInfo *TInfo;
5421     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5422     if (Ty.isNull())
5423       return DeclarationNameInfo();
5424     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5425                                               Context.getCanonicalType(Ty)));
5426     NameInfo.setNamedTypeInfo(TInfo);
5427     return NameInfo;
5428   }
5429 
5430   case UnqualifiedIdKind::IK_TemplateId: {
5431     TemplateName TName = Name.TemplateId->Template.get();
5432     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5433     return Context.getNameForTemplate(TName, TNameLoc);
5434   }
5435 
5436   } // switch (Name.getKind())
5437 
5438   llvm_unreachable("Unknown name kind");
5439 }
5440 
5441 static QualType getCoreType(QualType Ty) {
5442   do {
5443     if (Ty->isPointerType() || Ty->isReferenceType())
5444       Ty = Ty->getPointeeType();
5445     else if (Ty->isArrayType())
5446       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5447     else
5448       return Ty.withoutLocalFastQualifiers();
5449   } while (true);
5450 }
5451 
5452 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5453 /// and Definition have "nearly" matching parameters. This heuristic is
5454 /// used to improve diagnostics in the case where an out-of-line function
5455 /// definition doesn't match any declaration within the class or namespace.
5456 /// Also sets Params to the list of indices to the parameters that differ
5457 /// between the declaration and the definition. If hasSimilarParameters
5458 /// returns true and Params is empty, then all of the parameters match.
5459 static bool hasSimilarParameters(ASTContext &Context,
5460                                      FunctionDecl *Declaration,
5461                                      FunctionDecl *Definition,
5462                                      SmallVectorImpl<unsigned> &Params) {
5463   Params.clear();
5464   if (Declaration->param_size() != Definition->param_size())
5465     return false;
5466   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5467     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5468     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5469 
5470     // The parameter types are identical
5471     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5472       continue;
5473 
5474     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5475     QualType DefParamBaseTy = getCoreType(DefParamTy);
5476     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5477     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5478 
5479     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5480         (DeclTyName && DeclTyName == DefTyName))
5481       Params.push_back(Idx);
5482     else  // The two parameters aren't even close
5483       return false;
5484   }
5485 
5486   return true;
5487 }
5488 
5489 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5490 /// declarator needs to be rebuilt in the current instantiation.
5491 /// Any bits of declarator which appear before the name are valid for
5492 /// consideration here.  That's specifically the type in the decl spec
5493 /// and the base type in any member-pointer chunks.
5494 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5495                                                     DeclarationName Name) {
5496   // The types we specifically need to rebuild are:
5497   //   - typenames, typeofs, and decltypes
5498   //   - types which will become injected class names
5499   // Of course, we also need to rebuild any type referencing such a
5500   // type.  It's safest to just say "dependent", but we call out a
5501   // few cases here.
5502 
5503   DeclSpec &DS = D.getMutableDeclSpec();
5504   switch (DS.getTypeSpecType()) {
5505   case DeclSpec::TST_typename:
5506   case DeclSpec::TST_typeofType:
5507   case DeclSpec::TST_underlyingType:
5508   case DeclSpec::TST_atomic: {
5509     // Grab the type from the parser.
5510     TypeSourceInfo *TSI = nullptr;
5511     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5512     if (T.isNull() || !T->isInstantiationDependentType()) break;
5513 
5514     // Make sure there's a type source info.  This isn't really much
5515     // of a waste; most dependent types should have type source info
5516     // attached already.
5517     if (!TSI)
5518       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5519 
5520     // Rebuild the type in the current instantiation.
5521     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5522     if (!TSI) return true;
5523 
5524     // Store the new type back in the decl spec.
5525     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5526     DS.UpdateTypeRep(LocType);
5527     break;
5528   }
5529 
5530   case DeclSpec::TST_decltype:
5531   case DeclSpec::TST_typeofExpr: {
5532     Expr *E = DS.getRepAsExpr();
5533     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5534     if (Result.isInvalid()) return true;
5535     DS.UpdateExprRep(Result.get());
5536     break;
5537   }
5538 
5539   default:
5540     // Nothing to do for these decl specs.
5541     break;
5542   }
5543 
5544   // It doesn't matter what order we do this in.
5545   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5546     DeclaratorChunk &Chunk = D.getTypeObject(I);
5547 
5548     // The only type information in the declarator which can come
5549     // before the declaration name is the base type of a member
5550     // pointer.
5551     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5552       continue;
5553 
5554     // Rebuild the scope specifier in-place.
5555     CXXScopeSpec &SS = Chunk.Mem.Scope();
5556     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5557       return true;
5558   }
5559 
5560   return false;
5561 }
5562 
5563 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5564   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5565   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5566 
5567   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5568       Dcl && Dcl->getDeclContext()->isFileContext())
5569     Dcl->setTopLevelDeclInObjCContainer();
5570 
5571   if (getLangOpts().OpenCL)
5572     setCurrentOpenCLExtensionForDecl(Dcl);
5573 
5574   return Dcl;
5575 }
5576 
5577 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5578 ///   If T is the name of a class, then each of the following shall have a
5579 ///   name different from T:
5580 ///     - every static data member of class T;
5581 ///     - every member function of class T
5582 ///     - every member of class T that is itself a type;
5583 /// \returns true if the declaration name violates these rules.
5584 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5585                                    DeclarationNameInfo NameInfo) {
5586   DeclarationName Name = NameInfo.getName();
5587 
5588   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5589   while (Record && Record->isAnonymousStructOrUnion())
5590     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5591   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5592     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5593     return true;
5594   }
5595 
5596   return false;
5597 }
5598 
5599 /// Diagnose a declaration whose declarator-id has the given
5600 /// nested-name-specifier.
5601 ///
5602 /// \param SS The nested-name-specifier of the declarator-id.
5603 ///
5604 /// \param DC The declaration context to which the nested-name-specifier
5605 /// resolves.
5606 ///
5607 /// \param Name The name of the entity being declared.
5608 ///
5609 /// \param Loc The location of the name of the entity being declared.
5610 ///
5611 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5612 /// we're declaring an explicit / partial specialization / instantiation.
5613 ///
5614 /// \returns true if we cannot safely recover from this error, false otherwise.
5615 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5616                                         DeclarationName Name,
5617                                         SourceLocation Loc, bool IsTemplateId) {
5618   DeclContext *Cur = CurContext;
5619   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5620     Cur = Cur->getParent();
5621 
5622   // If the user provided a superfluous scope specifier that refers back to the
5623   // class in which the entity is already declared, diagnose and ignore it.
5624   //
5625   // class X {
5626   //   void X::f();
5627   // };
5628   //
5629   // Note, it was once ill-formed to give redundant qualification in all
5630   // contexts, but that rule was removed by DR482.
5631   if (Cur->Equals(DC)) {
5632     if (Cur->isRecord()) {
5633       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5634                                       : diag::err_member_extra_qualification)
5635         << Name << FixItHint::CreateRemoval(SS.getRange());
5636       SS.clear();
5637     } else {
5638       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5639     }
5640     return false;
5641   }
5642 
5643   // Check whether the qualifying scope encloses the scope of the original
5644   // declaration. For a template-id, we perform the checks in
5645   // CheckTemplateSpecializationScope.
5646   if (!Cur->Encloses(DC) && !IsTemplateId) {
5647     if (Cur->isRecord())
5648       Diag(Loc, diag::err_member_qualification)
5649         << Name << SS.getRange();
5650     else if (isa<TranslationUnitDecl>(DC))
5651       Diag(Loc, diag::err_invalid_declarator_global_scope)
5652         << Name << SS.getRange();
5653     else if (isa<FunctionDecl>(Cur))
5654       Diag(Loc, diag::err_invalid_declarator_in_function)
5655         << Name << SS.getRange();
5656     else if (isa<BlockDecl>(Cur))
5657       Diag(Loc, diag::err_invalid_declarator_in_block)
5658         << Name << SS.getRange();
5659     else
5660       Diag(Loc, diag::err_invalid_declarator_scope)
5661       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5662 
5663     return true;
5664   }
5665 
5666   if (Cur->isRecord()) {
5667     // Cannot qualify members within a class.
5668     Diag(Loc, diag::err_member_qualification)
5669       << Name << SS.getRange();
5670     SS.clear();
5671 
5672     // C++ constructors and destructors with incorrect scopes can break
5673     // our AST invariants by having the wrong underlying types. If
5674     // that's the case, then drop this declaration entirely.
5675     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5676          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5677         !Context.hasSameType(Name.getCXXNameType(),
5678                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5679       return true;
5680 
5681     return false;
5682   }
5683 
5684   // C++11 [dcl.meaning]p1:
5685   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5686   //   not begin with a decltype-specifer"
5687   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5688   while (SpecLoc.getPrefix())
5689     SpecLoc = SpecLoc.getPrefix();
5690   if (dyn_cast_or_null<DecltypeType>(
5691         SpecLoc.getNestedNameSpecifier()->getAsType()))
5692     Diag(Loc, diag::err_decltype_in_declarator)
5693       << SpecLoc.getTypeLoc().getSourceRange();
5694 
5695   return false;
5696 }
5697 
5698 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5699                                   MultiTemplateParamsArg TemplateParamLists) {
5700   // TODO: consider using NameInfo for diagnostic.
5701   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5702   DeclarationName Name = NameInfo.getName();
5703 
5704   // All of these full declarators require an identifier.  If it doesn't have
5705   // one, the ParsedFreeStandingDeclSpec action should be used.
5706   if (D.isDecompositionDeclarator()) {
5707     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5708   } else if (!Name) {
5709     if (!D.isInvalidType())  // Reject this if we think it is valid.
5710       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5711           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5712     return nullptr;
5713   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5714     return nullptr;
5715 
5716   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5717   // we find one that is.
5718   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5719          (S->getFlags() & Scope::TemplateParamScope) != 0)
5720     S = S->getParent();
5721 
5722   DeclContext *DC = CurContext;
5723   if (D.getCXXScopeSpec().isInvalid())
5724     D.setInvalidType();
5725   else if (D.getCXXScopeSpec().isSet()) {
5726     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5727                                         UPPC_DeclarationQualifier))
5728       return nullptr;
5729 
5730     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5731     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5732     if (!DC || isa<EnumDecl>(DC)) {
5733       // If we could not compute the declaration context, it's because the
5734       // declaration context is dependent but does not refer to a class,
5735       // class template, or class template partial specialization. Complain
5736       // and return early, to avoid the coming semantic disaster.
5737       Diag(D.getIdentifierLoc(),
5738            diag::err_template_qualified_declarator_no_match)
5739         << D.getCXXScopeSpec().getScopeRep()
5740         << D.getCXXScopeSpec().getRange();
5741       return nullptr;
5742     }
5743     bool IsDependentContext = DC->isDependentContext();
5744 
5745     if (!IsDependentContext &&
5746         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5747       return nullptr;
5748 
5749     // If a class is incomplete, do not parse entities inside it.
5750     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5751       Diag(D.getIdentifierLoc(),
5752            diag::err_member_def_undefined_record)
5753         << Name << DC << D.getCXXScopeSpec().getRange();
5754       return nullptr;
5755     }
5756     if (!D.getDeclSpec().isFriendSpecified()) {
5757       if (diagnoseQualifiedDeclaration(
5758               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5759               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5760         if (DC->isRecord())
5761           return nullptr;
5762 
5763         D.setInvalidType();
5764       }
5765     }
5766 
5767     // Check whether we need to rebuild the type of the given
5768     // declaration in the current instantiation.
5769     if (EnteringContext && IsDependentContext &&
5770         TemplateParamLists.size() != 0) {
5771       ContextRAII SavedContext(*this, DC);
5772       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5773         D.setInvalidType();
5774     }
5775   }
5776 
5777   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5778   QualType R = TInfo->getType();
5779 
5780   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5781                                       UPPC_DeclarationType))
5782     D.setInvalidType();
5783 
5784   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5785                         forRedeclarationInCurContext());
5786 
5787   // See if this is a redefinition of a variable in the same scope.
5788   if (!D.getCXXScopeSpec().isSet()) {
5789     bool IsLinkageLookup = false;
5790     bool CreateBuiltins = false;
5791 
5792     // If the declaration we're planning to build will be a function
5793     // or object with linkage, then look for another declaration with
5794     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5795     //
5796     // If the declaration we're planning to build will be declared with
5797     // external linkage in the translation unit, create any builtin with
5798     // the same name.
5799     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5800       /* Do nothing*/;
5801     else if (CurContext->isFunctionOrMethod() &&
5802              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5803               R->isFunctionType())) {
5804       IsLinkageLookup = true;
5805       CreateBuiltins =
5806           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5807     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5808                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5809       CreateBuiltins = true;
5810 
5811     if (IsLinkageLookup) {
5812       Previous.clear(LookupRedeclarationWithLinkage);
5813       Previous.setRedeclarationKind(ForExternalRedeclaration);
5814     }
5815 
5816     LookupName(Previous, S, CreateBuiltins);
5817   } else { // Something like "int foo::x;"
5818     LookupQualifiedName(Previous, DC);
5819 
5820     // C++ [dcl.meaning]p1:
5821     //   When the declarator-id is qualified, the declaration shall refer to a
5822     //  previously declared member of the class or namespace to which the
5823     //  qualifier refers (or, in the case of a namespace, of an element of the
5824     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5825     //  thereof; [...]
5826     //
5827     // Note that we already checked the context above, and that we do not have
5828     // enough information to make sure that Previous contains the declaration
5829     // we want to match. For example, given:
5830     //
5831     //   class X {
5832     //     void f();
5833     //     void f(float);
5834     //   };
5835     //
5836     //   void X::f(int) { } // ill-formed
5837     //
5838     // In this case, Previous will point to the overload set
5839     // containing the two f's declared in X, but neither of them
5840     // matches.
5841 
5842     // C++ [dcl.meaning]p1:
5843     //   [...] the member shall not merely have been introduced by a
5844     //   using-declaration in the scope of the class or namespace nominated by
5845     //   the nested-name-specifier of the declarator-id.
5846     RemoveUsingDecls(Previous);
5847   }
5848 
5849   if (Previous.isSingleResult() &&
5850       Previous.getFoundDecl()->isTemplateParameter()) {
5851     // Maybe we will complain about the shadowed template parameter.
5852     if (!D.isInvalidType())
5853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5854                                       Previous.getFoundDecl());
5855 
5856     // Just pretend that we didn't see the previous declaration.
5857     Previous.clear();
5858   }
5859 
5860   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5861     // Forget that the previous declaration is the injected-class-name.
5862     Previous.clear();
5863 
5864   // In C++, the previous declaration we find might be a tag type
5865   // (class or enum). In this case, the new declaration will hide the
5866   // tag type. Note that this applies to functions, function templates, and
5867   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5868   if (Previous.isSingleTagDecl() &&
5869       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5870       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5871     Previous.clear();
5872 
5873   // Check that there are no default arguments other than in the parameters
5874   // of a function declaration (C++ only).
5875   if (getLangOpts().CPlusPlus)
5876     CheckExtraCXXDefaultArguments(D);
5877 
5878   NamedDecl *New;
5879 
5880   bool AddToScope = true;
5881   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5882     if (TemplateParamLists.size()) {
5883       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5884       return nullptr;
5885     }
5886 
5887     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5888   } else if (R->isFunctionType()) {
5889     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5890                                   TemplateParamLists,
5891                                   AddToScope);
5892   } else {
5893     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5894                                   AddToScope);
5895   }
5896 
5897   if (!New)
5898     return nullptr;
5899 
5900   // If this has an identifier and is not a function template specialization,
5901   // add it to the scope stack.
5902   if (New->getDeclName() && AddToScope)
5903     PushOnScopeChains(New, S);
5904 
5905   if (isInOpenMPDeclareTargetContext())
5906     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5907 
5908   return New;
5909 }
5910 
5911 /// Helper method to turn variable array types into constant array
5912 /// types in certain situations which would otherwise be errors (for
5913 /// GCC compatibility).
5914 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5915                                                     ASTContext &Context,
5916                                                     bool &SizeIsNegative,
5917                                                     llvm::APSInt &Oversized) {
5918   // This method tries to turn a variable array into a constant
5919   // array even when the size isn't an ICE.  This is necessary
5920   // for compatibility with code that depends on gcc's buggy
5921   // constant expression folding, like struct {char x[(int)(char*)2];}
5922   SizeIsNegative = false;
5923   Oversized = 0;
5924 
5925   if (T->isDependentType())
5926     return QualType();
5927 
5928   QualifierCollector Qs;
5929   const Type *Ty = Qs.strip(T);
5930 
5931   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5932     QualType Pointee = PTy->getPointeeType();
5933     QualType FixedType =
5934         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5935                                             Oversized);
5936     if (FixedType.isNull()) return FixedType;
5937     FixedType = Context.getPointerType(FixedType);
5938     return Qs.apply(Context, FixedType);
5939   }
5940   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5941     QualType Inner = PTy->getInnerType();
5942     QualType FixedType =
5943         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5944                                             Oversized);
5945     if (FixedType.isNull()) return FixedType;
5946     FixedType = Context.getParenType(FixedType);
5947     return Qs.apply(Context, FixedType);
5948   }
5949 
5950   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5951   if (!VLATy)
5952     return QualType();
5953 
5954   QualType ElemTy = VLATy->getElementType();
5955   if (ElemTy->isVariablyModifiedType()) {
5956     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5957                                                  SizeIsNegative, Oversized);
5958     if (ElemTy.isNull())
5959       return QualType();
5960   }
5961 
5962   Expr::EvalResult Result;
5963   if (!VLATy->getSizeExpr() ||
5964       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5965     return QualType();
5966 
5967   llvm::APSInt Res = Result.Val.getInt();
5968 
5969   // Check whether the array size is negative.
5970   if (Res.isSigned() && Res.isNegative()) {
5971     SizeIsNegative = true;
5972     return QualType();
5973   }
5974 
5975   // Check whether the array is too large to be addressed.
5976   unsigned ActiveSizeBits =
5977       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5978        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5979           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5980           : Res.getActiveBits();
5981   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5982     Oversized = Res;
5983     return QualType();
5984   }
5985 
5986   QualType FoldedArrayType = Context.getConstantArrayType(
5987       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5988   return Qs.apply(Context, FoldedArrayType);
5989 }
5990 
5991 static void
5992 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5993   SrcTL = SrcTL.getUnqualifiedLoc();
5994   DstTL = DstTL.getUnqualifiedLoc();
5995   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5996     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5997     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5998                                       DstPTL.getPointeeLoc());
5999     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6000     return;
6001   }
6002   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6003     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6004     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6005                                       DstPTL.getInnerLoc());
6006     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6007     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6008     return;
6009   }
6010   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6011   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6012   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6013   TypeLoc DstElemTL = DstATL.getElementLoc();
6014   if (VariableArrayTypeLoc SrcElemATL =
6015           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6016     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6017     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6018   } else {
6019     DstElemTL.initializeFullCopy(SrcElemTL);
6020   }
6021   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6022   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6023   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6024 }
6025 
6026 /// Helper method to turn variable array types into constant array
6027 /// types in certain situations which would otherwise be errors (for
6028 /// GCC compatibility).
6029 static TypeSourceInfo*
6030 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6031                                               ASTContext &Context,
6032                                               bool &SizeIsNegative,
6033                                               llvm::APSInt &Oversized) {
6034   QualType FixedTy
6035     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6036                                           SizeIsNegative, Oversized);
6037   if (FixedTy.isNull())
6038     return nullptr;
6039   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6040   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6041                                     FixedTInfo->getTypeLoc());
6042   return FixedTInfo;
6043 }
6044 
6045 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6046 /// true if we were successful.
6047 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6048                                            QualType &T, SourceLocation Loc,
6049                                            unsigned FailedFoldDiagID) {
6050   bool SizeIsNegative;
6051   llvm::APSInt Oversized;
6052   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6053       TInfo, Context, SizeIsNegative, Oversized);
6054   if (FixedTInfo) {
6055     Diag(Loc, diag::ext_vla_folded_to_constant);
6056     TInfo = FixedTInfo;
6057     T = FixedTInfo->getType();
6058     return true;
6059   }
6060 
6061   if (SizeIsNegative)
6062     Diag(Loc, diag::err_typecheck_negative_array_size);
6063   else if (Oversized.getBoolValue())
6064     Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6065   else if (FailedFoldDiagID)
6066     Diag(Loc, FailedFoldDiagID);
6067   return false;
6068 }
6069 
6070 /// Register the given locally-scoped extern "C" declaration so
6071 /// that it can be found later for redeclarations. We include any extern "C"
6072 /// declaration that is not visible in the translation unit here, not just
6073 /// function-scope declarations.
6074 void
6075 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6076   if (!getLangOpts().CPlusPlus &&
6077       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6078     // Don't need to track declarations in the TU in C.
6079     return;
6080 
6081   // Note that we have a locally-scoped external with this name.
6082   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6083 }
6084 
6085 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6086   // FIXME: We can have multiple results via __attribute__((overloadable)).
6087   auto Result = Context.getExternCContextDecl()->lookup(Name);
6088   return Result.empty() ? nullptr : *Result.begin();
6089 }
6090 
6091 /// Diagnose function specifiers on a declaration of an identifier that
6092 /// does not identify a function.
6093 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6094   // FIXME: We should probably indicate the identifier in question to avoid
6095   // confusion for constructs like "virtual int a(), b;"
6096   if (DS.isVirtualSpecified())
6097     Diag(DS.getVirtualSpecLoc(),
6098          diag::err_virtual_non_function);
6099 
6100   if (DS.hasExplicitSpecifier())
6101     Diag(DS.getExplicitSpecLoc(),
6102          diag::err_explicit_non_function);
6103 
6104   if (DS.isNoreturnSpecified())
6105     Diag(DS.getNoreturnSpecLoc(),
6106          diag::err_noreturn_non_function);
6107 }
6108 
6109 NamedDecl*
6110 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6111                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6112   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6113   if (D.getCXXScopeSpec().isSet()) {
6114     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6115       << D.getCXXScopeSpec().getRange();
6116     D.setInvalidType();
6117     // Pretend we didn't see the scope specifier.
6118     DC = CurContext;
6119     Previous.clear();
6120   }
6121 
6122   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6123 
6124   if (D.getDeclSpec().isInlineSpecified())
6125     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6126         << getLangOpts().CPlusPlus17;
6127   if (D.getDeclSpec().hasConstexprSpecifier())
6128     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6129         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6130 
6131   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6132     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6133       Diag(D.getName().StartLocation,
6134            diag::err_deduction_guide_invalid_specifier)
6135           << "typedef";
6136     else
6137       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6138           << D.getName().getSourceRange();
6139     return nullptr;
6140   }
6141 
6142   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6143   if (!NewTD) return nullptr;
6144 
6145   // Handle attributes prior to checking for duplicates in MergeVarDecl
6146   ProcessDeclAttributes(S, NewTD, D);
6147 
6148   CheckTypedefForVariablyModifiedType(S, NewTD);
6149 
6150   bool Redeclaration = D.isRedeclaration();
6151   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6152   D.setRedeclaration(Redeclaration);
6153   return ND;
6154 }
6155 
6156 void
6157 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6158   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6159   // then it shall have block scope.
6160   // Note that variably modified types must be fixed before merging the decl so
6161   // that redeclarations will match.
6162   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6163   QualType T = TInfo->getType();
6164   if (T->isVariablyModifiedType()) {
6165     setFunctionHasBranchProtectedScope();
6166 
6167     if (S->getFnParent() == nullptr) {
6168       bool SizeIsNegative;
6169       llvm::APSInt Oversized;
6170       TypeSourceInfo *FixedTInfo =
6171         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6172                                                       SizeIsNegative,
6173                                                       Oversized);
6174       if (FixedTInfo) {
6175         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6176         NewTD->setTypeSourceInfo(FixedTInfo);
6177       } else {
6178         if (SizeIsNegative)
6179           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6180         else if (T->isVariableArrayType())
6181           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6182         else if (Oversized.getBoolValue())
6183           Diag(NewTD->getLocation(), diag::err_array_too_large)
6184             << Oversized.toString(10);
6185         else
6186           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6187         NewTD->setInvalidDecl();
6188       }
6189     }
6190   }
6191 }
6192 
6193 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6194 /// declares a typedef-name, either using the 'typedef' type specifier or via
6195 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6196 NamedDecl*
6197 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6198                            LookupResult &Previous, bool &Redeclaration) {
6199 
6200   // Find the shadowed declaration before filtering for scope.
6201   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6202 
6203   // Merge the decl with the existing one if appropriate. If the decl is
6204   // in an outer scope, it isn't the same thing.
6205   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6206                        /*AllowInlineNamespace*/false);
6207   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6208   if (!Previous.empty()) {
6209     Redeclaration = true;
6210     MergeTypedefNameDecl(S, NewTD, Previous);
6211   } else {
6212     inferGslPointerAttribute(NewTD);
6213   }
6214 
6215   if (ShadowedDecl && !Redeclaration)
6216     CheckShadow(NewTD, ShadowedDecl, Previous);
6217 
6218   // If this is the C FILE type, notify the AST context.
6219   if (IdentifierInfo *II = NewTD->getIdentifier())
6220     if (!NewTD->isInvalidDecl() &&
6221         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6222       if (II->isStr("FILE"))
6223         Context.setFILEDecl(NewTD);
6224       else if (II->isStr("jmp_buf"))
6225         Context.setjmp_bufDecl(NewTD);
6226       else if (II->isStr("sigjmp_buf"))
6227         Context.setsigjmp_bufDecl(NewTD);
6228       else if (II->isStr("ucontext_t"))
6229         Context.setucontext_tDecl(NewTD);
6230     }
6231 
6232   return NewTD;
6233 }
6234 
6235 /// Determines whether the given declaration is an out-of-scope
6236 /// previous declaration.
6237 ///
6238 /// This routine should be invoked when name lookup has found a
6239 /// previous declaration (PrevDecl) that is not in the scope where a
6240 /// new declaration by the same name is being introduced. If the new
6241 /// declaration occurs in a local scope, previous declarations with
6242 /// linkage may still be considered previous declarations (C99
6243 /// 6.2.2p4-5, C++ [basic.link]p6).
6244 ///
6245 /// \param PrevDecl the previous declaration found by name
6246 /// lookup
6247 ///
6248 /// \param DC the context in which the new declaration is being
6249 /// declared.
6250 ///
6251 /// \returns true if PrevDecl is an out-of-scope previous declaration
6252 /// for a new delcaration with the same name.
6253 static bool
6254 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6255                                 ASTContext &Context) {
6256   if (!PrevDecl)
6257     return false;
6258 
6259   if (!PrevDecl->hasLinkage())
6260     return false;
6261 
6262   if (Context.getLangOpts().CPlusPlus) {
6263     // C++ [basic.link]p6:
6264     //   If there is a visible declaration of an entity with linkage
6265     //   having the same name and type, ignoring entities declared
6266     //   outside the innermost enclosing namespace scope, the block
6267     //   scope declaration declares that same entity and receives the
6268     //   linkage of the previous declaration.
6269     DeclContext *OuterContext = DC->getRedeclContext();
6270     if (!OuterContext->isFunctionOrMethod())
6271       // This rule only applies to block-scope declarations.
6272       return false;
6273 
6274     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6275     if (PrevOuterContext->isRecord())
6276       // We found a member function: ignore it.
6277       return false;
6278 
6279     // Find the innermost enclosing namespace for the new and
6280     // previous declarations.
6281     OuterContext = OuterContext->getEnclosingNamespaceContext();
6282     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6283 
6284     // The previous declaration is in a different namespace, so it
6285     // isn't the same function.
6286     if (!OuterContext->Equals(PrevOuterContext))
6287       return false;
6288   }
6289 
6290   return true;
6291 }
6292 
6293 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6294   CXXScopeSpec &SS = D.getCXXScopeSpec();
6295   if (!SS.isSet()) return;
6296   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6297 }
6298 
6299 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6300   QualType type = decl->getType();
6301   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6302   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6303     // Various kinds of declaration aren't allowed to be __autoreleasing.
6304     unsigned kind = -1U;
6305     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6306       if (var->hasAttr<BlocksAttr>())
6307         kind = 0; // __block
6308       else if (!var->hasLocalStorage())
6309         kind = 1; // global
6310     } else if (isa<ObjCIvarDecl>(decl)) {
6311       kind = 3; // ivar
6312     } else if (isa<FieldDecl>(decl)) {
6313       kind = 2; // field
6314     }
6315 
6316     if (kind != -1U) {
6317       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6318         << kind;
6319     }
6320   } else if (lifetime == Qualifiers::OCL_None) {
6321     // Try to infer lifetime.
6322     if (!type->isObjCLifetimeType())
6323       return false;
6324 
6325     lifetime = type->getObjCARCImplicitLifetime();
6326     type = Context.getLifetimeQualifiedType(type, lifetime);
6327     decl->setType(type);
6328   }
6329 
6330   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6331     // Thread-local variables cannot have lifetime.
6332     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6333         var->getTLSKind()) {
6334       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6335         << var->getType();
6336       return true;
6337     }
6338   }
6339 
6340   return false;
6341 }
6342 
6343 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6344   if (Decl->getType().hasAddressSpace())
6345     return;
6346   if (Decl->getType()->isDependentType())
6347     return;
6348   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6349     QualType Type = Var->getType();
6350     if (Type->isSamplerT() || Type->isVoidType())
6351       return;
6352     LangAS ImplAS = LangAS::opencl_private;
6353     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6354         Var->hasGlobalStorage())
6355       ImplAS = LangAS::opencl_global;
6356     // If the original type from a decayed type is an array type and that array
6357     // type has no address space yet, deduce it now.
6358     if (auto DT = dyn_cast<DecayedType>(Type)) {
6359       auto OrigTy = DT->getOriginalType();
6360       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6361         // Add the address space to the original array type and then propagate
6362         // that to the element type through `getAsArrayType`.
6363         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6364         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6365         // Re-generate the decayed type.
6366         Type = Context.getDecayedType(OrigTy);
6367       }
6368     }
6369     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6370     // Apply any qualifiers (including address space) from the array type to
6371     // the element type. This implements C99 6.7.3p8: "If the specification of
6372     // an array type includes any type qualifiers, the element type is so
6373     // qualified, not the array type."
6374     if (Type->isArrayType())
6375       Type = QualType(Context.getAsArrayType(Type), 0);
6376     Decl->setType(Type);
6377   }
6378 }
6379 
6380 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6381   // Ensure that an auto decl is deduced otherwise the checks below might cache
6382   // the wrong linkage.
6383   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6384 
6385   // 'weak' only applies to declarations with external linkage.
6386   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6387     if (!ND.isExternallyVisible()) {
6388       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6389       ND.dropAttr<WeakAttr>();
6390     }
6391   }
6392   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6393     if (ND.isExternallyVisible()) {
6394       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6395       ND.dropAttr<WeakRefAttr>();
6396       ND.dropAttr<AliasAttr>();
6397     }
6398   }
6399 
6400   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6401     if (VD->hasInit()) {
6402       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6403         assert(VD->isThisDeclarationADefinition() &&
6404                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6405         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6406         VD->dropAttr<AliasAttr>();
6407       }
6408     }
6409   }
6410 
6411   // 'selectany' only applies to externally visible variable declarations.
6412   // It does not apply to functions.
6413   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6414     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6415       S.Diag(Attr->getLocation(),
6416              diag::err_attribute_selectany_non_extern_data);
6417       ND.dropAttr<SelectAnyAttr>();
6418     }
6419   }
6420 
6421   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6422     auto *VD = dyn_cast<VarDecl>(&ND);
6423     bool IsAnonymousNS = false;
6424     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6425     if (VD) {
6426       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6427       while (NS && !IsAnonymousNS) {
6428         IsAnonymousNS = NS->isAnonymousNamespace();
6429         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6430       }
6431     }
6432     // dll attributes require external linkage. Static locals may have external
6433     // linkage but still cannot be explicitly imported or exported.
6434     // In Microsoft mode, a variable defined in anonymous namespace must have
6435     // external linkage in order to be exported.
6436     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6437     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6438         (!AnonNSInMicrosoftMode &&
6439          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6440       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6441         << &ND << Attr;
6442       ND.setInvalidDecl();
6443     }
6444   }
6445 
6446   // Check the attributes on the function type, if any.
6447   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6448     // Don't declare this variable in the second operand of the for-statement;
6449     // GCC miscompiles that by ending its lifetime before evaluating the
6450     // third operand. See gcc.gnu.org/PR86769.
6451     AttributedTypeLoc ATL;
6452     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6453          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6454          TL = ATL.getModifiedLoc()) {
6455       // The [[lifetimebound]] attribute can be applied to the implicit object
6456       // parameter of a non-static member function (other than a ctor or dtor)
6457       // by applying it to the function type.
6458       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6459         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6460         if (!MD || MD->isStatic()) {
6461           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6462               << !MD << A->getRange();
6463         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6464           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6465               << isa<CXXDestructorDecl>(MD) << A->getRange();
6466         }
6467       }
6468     }
6469   }
6470 }
6471 
6472 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6473                                            NamedDecl *NewDecl,
6474                                            bool IsSpecialization,
6475                                            bool IsDefinition) {
6476   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6477     return;
6478 
6479   bool IsTemplate = false;
6480   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6481     OldDecl = OldTD->getTemplatedDecl();
6482     IsTemplate = true;
6483     if (!IsSpecialization)
6484       IsDefinition = false;
6485   }
6486   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6487     NewDecl = NewTD->getTemplatedDecl();
6488     IsTemplate = true;
6489   }
6490 
6491   if (!OldDecl || !NewDecl)
6492     return;
6493 
6494   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6495   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6496   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6497   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6498 
6499   // dllimport and dllexport are inheritable attributes so we have to exclude
6500   // inherited attribute instances.
6501   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6502                     (NewExportAttr && !NewExportAttr->isInherited());
6503 
6504   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6505   // the only exception being explicit specializations.
6506   // Implicitly generated declarations are also excluded for now because there
6507   // is no other way to switch these to use dllimport or dllexport.
6508   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6509 
6510   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6511     // Allow with a warning for free functions and global variables.
6512     bool JustWarn = false;
6513     if (!OldDecl->isCXXClassMember()) {
6514       auto *VD = dyn_cast<VarDecl>(OldDecl);
6515       if (VD && !VD->getDescribedVarTemplate())
6516         JustWarn = true;
6517       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6518       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6519         JustWarn = true;
6520     }
6521 
6522     // We cannot change a declaration that's been used because IR has already
6523     // been emitted. Dllimported functions will still work though (modulo
6524     // address equality) as they can use the thunk.
6525     if (OldDecl->isUsed())
6526       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6527         JustWarn = false;
6528 
6529     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6530                                : diag::err_attribute_dll_redeclaration;
6531     S.Diag(NewDecl->getLocation(), DiagID)
6532         << NewDecl
6533         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6534     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6535     if (!JustWarn) {
6536       NewDecl->setInvalidDecl();
6537       return;
6538     }
6539   }
6540 
6541   // A redeclaration is not allowed to drop a dllimport attribute, the only
6542   // exceptions being inline function definitions (except for function
6543   // templates), local extern declarations, qualified friend declarations or
6544   // special MSVC extension: in the last case, the declaration is treated as if
6545   // it were marked dllexport.
6546   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6547   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6548   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6549     // Ignore static data because out-of-line definitions are diagnosed
6550     // separately.
6551     IsStaticDataMember = VD->isStaticDataMember();
6552     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6553                    VarDecl::DeclarationOnly;
6554   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6555     IsInline = FD->isInlined();
6556     IsQualifiedFriend = FD->getQualifier() &&
6557                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6558   }
6559 
6560   if (OldImportAttr && !HasNewAttr &&
6561       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6562       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6563     if (IsMicrosoftABI && IsDefinition) {
6564       S.Diag(NewDecl->getLocation(),
6565              diag::warn_redeclaration_without_import_attribute)
6566           << NewDecl;
6567       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6568       NewDecl->dropAttr<DLLImportAttr>();
6569       NewDecl->addAttr(
6570           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6571     } else {
6572       S.Diag(NewDecl->getLocation(),
6573              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6574           << NewDecl << OldImportAttr;
6575       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6576       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6577       OldDecl->dropAttr<DLLImportAttr>();
6578       NewDecl->dropAttr<DLLImportAttr>();
6579     }
6580   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6581     // In MinGW, seeing a function declared inline drops the dllimport
6582     // attribute.
6583     OldDecl->dropAttr<DLLImportAttr>();
6584     NewDecl->dropAttr<DLLImportAttr>();
6585     S.Diag(NewDecl->getLocation(),
6586            diag::warn_dllimport_dropped_from_inline_function)
6587         << NewDecl << OldImportAttr;
6588   }
6589 
6590   // A specialization of a class template member function is processed here
6591   // since it's a redeclaration. If the parent class is dllexport, the
6592   // specialization inherits that attribute. This doesn't happen automatically
6593   // since the parent class isn't instantiated until later.
6594   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6595     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6596         !NewImportAttr && !NewExportAttr) {
6597       if (const DLLExportAttr *ParentExportAttr =
6598               MD->getParent()->getAttr<DLLExportAttr>()) {
6599         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6600         NewAttr->setInherited(true);
6601         NewDecl->addAttr(NewAttr);
6602       }
6603     }
6604   }
6605 }
6606 
6607 /// Given that we are within the definition of the given function,
6608 /// will that definition behave like C99's 'inline', where the
6609 /// definition is discarded except for optimization purposes?
6610 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6611   // Try to avoid calling GetGVALinkageForFunction.
6612 
6613   // All cases of this require the 'inline' keyword.
6614   if (!FD->isInlined()) return false;
6615 
6616   // This is only possible in C++ with the gnu_inline attribute.
6617   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6618     return false;
6619 
6620   // Okay, go ahead and call the relatively-more-expensive function.
6621   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6622 }
6623 
6624 /// Determine whether a variable is extern "C" prior to attaching
6625 /// an initializer. We can't just call isExternC() here, because that
6626 /// will also compute and cache whether the declaration is externally
6627 /// visible, which might change when we attach the initializer.
6628 ///
6629 /// This can only be used if the declaration is known to not be a
6630 /// redeclaration of an internal linkage declaration.
6631 ///
6632 /// For instance:
6633 ///
6634 ///   auto x = []{};
6635 ///
6636 /// Attaching the initializer here makes this declaration not externally
6637 /// visible, because its type has internal linkage.
6638 ///
6639 /// FIXME: This is a hack.
6640 template<typename T>
6641 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6642   if (S.getLangOpts().CPlusPlus) {
6643     // In C++, the overloadable attribute negates the effects of extern "C".
6644     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6645       return false;
6646 
6647     // So do CUDA's host/device attributes.
6648     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6649                                  D->template hasAttr<CUDAHostAttr>()))
6650       return false;
6651   }
6652   return D->isExternC();
6653 }
6654 
6655 static bool shouldConsiderLinkage(const VarDecl *VD) {
6656   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6657   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6658       isa<OMPDeclareMapperDecl>(DC))
6659     return VD->hasExternalStorage();
6660   if (DC->isFileContext())
6661     return true;
6662   if (DC->isRecord())
6663     return false;
6664   if (isa<RequiresExprBodyDecl>(DC))
6665     return false;
6666   llvm_unreachable("Unexpected context");
6667 }
6668 
6669 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6670   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6671   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6672       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6673     return true;
6674   if (DC->isRecord())
6675     return false;
6676   llvm_unreachable("Unexpected context");
6677 }
6678 
6679 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6680                           ParsedAttr::Kind Kind) {
6681   // Check decl attributes on the DeclSpec.
6682   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6683     return true;
6684 
6685   // Walk the declarator structure, checking decl attributes that were in a type
6686   // position to the decl itself.
6687   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6688     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6689       return true;
6690   }
6691 
6692   // Finally, check attributes on the decl itself.
6693   return PD.getAttributes().hasAttribute(Kind);
6694 }
6695 
6696 /// Adjust the \c DeclContext for a function or variable that might be a
6697 /// function-local external declaration.
6698 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6699   if (!DC->isFunctionOrMethod())
6700     return false;
6701 
6702   // If this is a local extern function or variable declared within a function
6703   // template, don't add it into the enclosing namespace scope until it is
6704   // instantiated; it might have a dependent type right now.
6705   if (DC->isDependentContext())
6706     return true;
6707 
6708   // C++11 [basic.link]p7:
6709   //   When a block scope declaration of an entity with linkage is not found to
6710   //   refer to some other declaration, then that entity is a member of the
6711   //   innermost enclosing namespace.
6712   //
6713   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6714   // semantically-enclosing namespace, not a lexically-enclosing one.
6715   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6716     DC = DC->getParent();
6717   return true;
6718 }
6719 
6720 /// Returns true if given declaration has external C language linkage.
6721 static bool isDeclExternC(const Decl *D) {
6722   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6723     return FD->isExternC();
6724   if (const auto *VD = dyn_cast<VarDecl>(D))
6725     return VD->isExternC();
6726 
6727   llvm_unreachable("Unknown type of decl!");
6728 }
6729 
6730 /// Returns true if there hasn't been any invalid type diagnosed.
6731 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6732   DeclContext *DC = NewVD->getDeclContext();
6733   QualType R = NewVD->getType();
6734 
6735   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6736   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6737   // argument.
6738   if (R->isImageType() || R->isPipeType()) {
6739     Se.Diag(NewVD->getLocation(),
6740             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6741         << R;
6742     NewVD->setInvalidDecl();
6743     return false;
6744   }
6745 
6746   // OpenCL v1.2 s6.9.r:
6747   // The event type cannot be used to declare a program scope variable.
6748   // OpenCL v2.0 s6.9.q:
6749   // The clk_event_t and reserve_id_t types cannot be declared in program
6750   // scope.
6751   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6752     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6753       Se.Diag(NewVD->getLocation(),
6754               diag::err_invalid_type_for_program_scope_var)
6755           << R;
6756       NewVD->setInvalidDecl();
6757       return false;
6758     }
6759   }
6760 
6761   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6762   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6763                                                Se.getLangOpts())) {
6764     QualType NR = R.getCanonicalType();
6765     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6766            NR->isReferenceType()) {
6767       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6768           NR->isFunctionReferenceType()) {
6769         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6770             << NR->isReferenceType();
6771         NewVD->setInvalidDecl();
6772         return false;
6773       }
6774       NR = NR->getPointeeType();
6775     }
6776   }
6777 
6778   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6779                                                Se.getLangOpts())) {
6780     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6781     // half array type (unless the cl_khr_fp16 extension is enabled).
6782     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6783       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6784       NewVD->setInvalidDecl();
6785       return false;
6786     }
6787   }
6788 
6789   // OpenCL v1.2 s6.9.r:
6790   // The event type cannot be used with the __local, __constant and __global
6791   // address space qualifiers.
6792   if (R->isEventT()) {
6793     if (R.getAddressSpace() != LangAS::opencl_private) {
6794       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6795       NewVD->setInvalidDecl();
6796       return false;
6797     }
6798   }
6799 
6800   if (R->isSamplerT()) {
6801     // OpenCL v1.2 s6.9.b p4:
6802     // The sampler type cannot be used with the __local and __global address
6803     // space qualifiers.
6804     if (R.getAddressSpace() == LangAS::opencl_local ||
6805         R.getAddressSpace() == LangAS::opencl_global) {
6806       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6807       NewVD->setInvalidDecl();
6808     }
6809 
6810     // OpenCL v1.2 s6.12.14.1:
6811     // A global sampler must be declared with either the constant address
6812     // space qualifier or with the const qualifier.
6813     if (DC->isTranslationUnit() &&
6814         !(R.getAddressSpace() == LangAS::opencl_constant ||
6815           R.isConstQualified())) {
6816       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6817       NewVD->setInvalidDecl();
6818     }
6819     if (NewVD->isInvalidDecl())
6820       return false;
6821   }
6822 
6823   return true;
6824 }
6825 
6826 template <typename AttrTy>
6827 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6828   const TypedefNameDecl *TND = TT->getDecl();
6829   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6830     AttrTy *Clone = Attribute->clone(S.Context);
6831     Clone->setInherited(true);
6832     D->addAttr(Clone);
6833   }
6834 }
6835 
6836 NamedDecl *Sema::ActOnVariableDeclarator(
6837     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6838     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6839     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6840   QualType R = TInfo->getType();
6841   DeclarationName Name = GetNameForDeclarator(D).getName();
6842 
6843   IdentifierInfo *II = Name.getAsIdentifierInfo();
6844 
6845   if (D.isDecompositionDeclarator()) {
6846     // Take the name of the first declarator as our name for diagnostic
6847     // purposes.
6848     auto &Decomp = D.getDecompositionDeclarator();
6849     if (!Decomp.bindings().empty()) {
6850       II = Decomp.bindings()[0].Name;
6851       Name = II;
6852     }
6853   } else if (!II) {
6854     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6855     return nullptr;
6856   }
6857 
6858 
6859   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6860   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6861 
6862   // dllimport globals without explicit storage class are treated as extern. We
6863   // have to change the storage class this early to get the right DeclContext.
6864   if (SC == SC_None && !DC->isRecord() &&
6865       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6866       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6867     SC = SC_Extern;
6868 
6869   DeclContext *OriginalDC = DC;
6870   bool IsLocalExternDecl = SC == SC_Extern &&
6871                            adjustContextForLocalExternDecl(DC);
6872 
6873   if (SCSpec == DeclSpec::SCS_mutable) {
6874     // mutable can only appear on non-static class members, so it's always
6875     // an error here
6876     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6877     D.setInvalidType();
6878     SC = SC_None;
6879   }
6880 
6881   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6882       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6883                               D.getDeclSpec().getStorageClassSpecLoc())) {
6884     // In C++11, the 'register' storage class specifier is deprecated.
6885     // Suppress the warning in system macros, it's used in macros in some
6886     // popular C system headers, such as in glibc's htonl() macro.
6887     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6888          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6889                                    : diag::warn_deprecated_register)
6890       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6891   }
6892 
6893   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6894 
6895   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6896     // C99 6.9p2: The storage-class specifiers auto and register shall not
6897     // appear in the declaration specifiers in an external declaration.
6898     // Global Register+Asm is a GNU extension we support.
6899     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6900       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6901       D.setInvalidType();
6902     }
6903   }
6904 
6905   // If this variable has a VLA type and an initializer, try to
6906   // fold to a constant-sized type. This is otherwise invalid.
6907   if (D.hasInitializer() && R->isVariableArrayType())
6908     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6909                                     /*DiagID=*/0);
6910 
6911   bool IsMemberSpecialization = false;
6912   bool IsVariableTemplateSpecialization = false;
6913   bool IsPartialSpecialization = false;
6914   bool IsVariableTemplate = false;
6915   VarDecl *NewVD = nullptr;
6916   VarTemplateDecl *NewTemplate = nullptr;
6917   TemplateParameterList *TemplateParams = nullptr;
6918   if (!getLangOpts().CPlusPlus) {
6919     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6920                             II, R, TInfo, SC);
6921 
6922     if (R->getContainedDeducedType())
6923       ParsingInitForAutoVars.insert(NewVD);
6924 
6925     if (D.isInvalidType())
6926       NewVD->setInvalidDecl();
6927 
6928     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6929         NewVD->hasLocalStorage())
6930       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6931                             NTCUC_AutoVar, NTCUK_Destruct);
6932   } else {
6933     bool Invalid = false;
6934 
6935     if (DC->isRecord() && !CurContext->isRecord()) {
6936       // This is an out-of-line definition of a static data member.
6937       switch (SC) {
6938       case SC_None:
6939         break;
6940       case SC_Static:
6941         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6942              diag::err_static_out_of_line)
6943           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6944         break;
6945       case SC_Auto:
6946       case SC_Register:
6947       case SC_Extern:
6948         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6949         // to names of variables declared in a block or to function parameters.
6950         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6951         // of class members
6952 
6953         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6954              diag::err_storage_class_for_static_member)
6955           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6956         break;
6957       case SC_PrivateExtern:
6958         llvm_unreachable("C storage class in c++!");
6959       }
6960     }
6961 
6962     if (SC == SC_Static && CurContext->isRecord()) {
6963       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6964         // Walk up the enclosing DeclContexts to check for any that are
6965         // incompatible with static data members.
6966         const DeclContext *FunctionOrMethod = nullptr;
6967         const CXXRecordDecl *AnonStruct = nullptr;
6968         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6969           if (Ctxt->isFunctionOrMethod()) {
6970             FunctionOrMethod = Ctxt;
6971             break;
6972           }
6973           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6974           if (ParentDecl && !ParentDecl->getDeclName()) {
6975             AnonStruct = ParentDecl;
6976             break;
6977           }
6978         }
6979         if (FunctionOrMethod) {
6980           // C++ [class.static.data]p5: A local class shall not have static data
6981           // members.
6982           Diag(D.getIdentifierLoc(),
6983                diag::err_static_data_member_not_allowed_in_local_class)
6984             << Name << RD->getDeclName() << RD->getTagKind();
6985         } else if (AnonStruct) {
6986           // C++ [class.static.data]p4: Unnamed classes and classes contained
6987           // directly or indirectly within unnamed classes shall not contain
6988           // static data members.
6989           Diag(D.getIdentifierLoc(),
6990                diag::err_static_data_member_not_allowed_in_anon_struct)
6991             << Name << AnonStruct->getTagKind();
6992           Invalid = true;
6993         } else if (RD->isUnion()) {
6994           // C++98 [class.union]p1: If a union contains a static data member,
6995           // the program is ill-formed. C++11 drops this restriction.
6996           Diag(D.getIdentifierLoc(),
6997                getLangOpts().CPlusPlus11
6998                  ? diag::warn_cxx98_compat_static_data_member_in_union
6999                  : diag::ext_static_data_member_in_union) << Name;
7000         }
7001       }
7002     }
7003 
7004     // Match up the template parameter lists with the scope specifier, then
7005     // determine whether we have a template or a template specialization.
7006     bool InvalidScope = false;
7007     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7008         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7009         D.getCXXScopeSpec(),
7010         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7011             ? D.getName().TemplateId
7012             : nullptr,
7013         TemplateParamLists,
7014         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7015     Invalid |= InvalidScope;
7016 
7017     if (TemplateParams) {
7018       if (!TemplateParams->size() &&
7019           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7020         // There is an extraneous 'template<>' for this variable. Complain
7021         // about it, but allow the declaration of the variable.
7022         Diag(TemplateParams->getTemplateLoc(),
7023              diag::err_template_variable_noparams)
7024           << II
7025           << SourceRange(TemplateParams->getTemplateLoc(),
7026                          TemplateParams->getRAngleLoc());
7027         TemplateParams = nullptr;
7028       } else {
7029         // Check that we can declare a template here.
7030         if (CheckTemplateDeclScope(S, TemplateParams))
7031           return nullptr;
7032 
7033         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7034           // This is an explicit specialization or a partial specialization.
7035           IsVariableTemplateSpecialization = true;
7036           IsPartialSpecialization = TemplateParams->size() > 0;
7037         } else { // if (TemplateParams->size() > 0)
7038           // This is a template declaration.
7039           IsVariableTemplate = true;
7040 
7041           // Only C++1y supports variable templates (N3651).
7042           Diag(D.getIdentifierLoc(),
7043                getLangOpts().CPlusPlus14
7044                    ? diag::warn_cxx11_compat_variable_template
7045                    : diag::ext_variable_template);
7046         }
7047       }
7048     } else {
7049       // Check that we can declare a member specialization here.
7050       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7051           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7052         return nullptr;
7053       assert((Invalid ||
7054               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7055              "should have a 'template<>' for this decl");
7056     }
7057 
7058     if (IsVariableTemplateSpecialization) {
7059       SourceLocation TemplateKWLoc =
7060           TemplateParamLists.size() > 0
7061               ? TemplateParamLists[0]->getTemplateLoc()
7062               : SourceLocation();
7063       DeclResult Res = ActOnVarTemplateSpecialization(
7064           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7065           IsPartialSpecialization);
7066       if (Res.isInvalid())
7067         return nullptr;
7068       NewVD = cast<VarDecl>(Res.get());
7069       AddToScope = false;
7070     } else if (D.isDecompositionDeclarator()) {
7071       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7072                                         D.getIdentifierLoc(), R, TInfo, SC,
7073                                         Bindings);
7074     } else
7075       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7076                               D.getIdentifierLoc(), II, R, TInfo, SC);
7077 
7078     // If this is supposed to be a variable template, create it as such.
7079     if (IsVariableTemplate) {
7080       NewTemplate =
7081           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7082                                   TemplateParams, NewVD);
7083       NewVD->setDescribedVarTemplate(NewTemplate);
7084     }
7085 
7086     // If this decl has an auto type in need of deduction, make a note of the
7087     // Decl so we can diagnose uses of it in its own initializer.
7088     if (R->getContainedDeducedType())
7089       ParsingInitForAutoVars.insert(NewVD);
7090 
7091     if (D.isInvalidType() || Invalid) {
7092       NewVD->setInvalidDecl();
7093       if (NewTemplate)
7094         NewTemplate->setInvalidDecl();
7095     }
7096 
7097     SetNestedNameSpecifier(*this, NewVD, D);
7098 
7099     // If we have any template parameter lists that don't directly belong to
7100     // the variable (matching the scope specifier), store them.
7101     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7102     if (TemplateParamLists.size() > VDTemplateParamLists)
7103       NewVD->setTemplateParameterListsInfo(
7104           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7105   }
7106 
7107   if (D.getDeclSpec().isInlineSpecified()) {
7108     if (!getLangOpts().CPlusPlus) {
7109       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7110           << 0;
7111     } else if (CurContext->isFunctionOrMethod()) {
7112       // 'inline' is not allowed on block scope variable declaration.
7113       Diag(D.getDeclSpec().getInlineSpecLoc(),
7114            diag::err_inline_declaration_block_scope) << Name
7115         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7116     } else {
7117       Diag(D.getDeclSpec().getInlineSpecLoc(),
7118            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7119                                      : diag::ext_inline_variable);
7120       NewVD->setInlineSpecified();
7121     }
7122   }
7123 
7124   // Set the lexical context. If the declarator has a C++ scope specifier, the
7125   // lexical context will be different from the semantic context.
7126   NewVD->setLexicalDeclContext(CurContext);
7127   if (NewTemplate)
7128     NewTemplate->setLexicalDeclContext(CurContext);
7129 
7130   if (IsLocalExternDecl) {
7131     if (D.isDecompositionDeclarator())
7132       for (auto *B : Bindings)
7133         B->setLocalExternDecl();
7134     else
7135       NewVD->setLocalExternDecl();
7136   }
7137 
7138   bool EmitTLSUnsupportedError = false;
7139   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7140     // C++11 [dcl.stc]p4:
7141     //   When thread_local is applied to a variable of block scope the
7142     //   storage-class-specifier static is implied if it does not appear
7143     //   explicitly.
7144     // Core issue: 'static' is not implied if the variable is declared
7145     //   'extern'.
7146     if (NewVD->hasLocalStorage() &&
7147         (SCSpec != DeclSpec::SCS_unspecified ||
7148          TSCS != DeclSpec::TSCS_thread_local ||
7149          !DC->isFunctionOrMethod()))
7150       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7151            diag::err_thread_non_global)
7152         << DeclSpec::getSpecifierName(TSCS);
7153     else if (!Context.getTargetInfo().isTLSSupported()) {
7154       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7155           getLangOpts().SYCLIsDevice) {
7156         // Postpone error emission until we've collected attributes required to
7157         // figure out whether it's a host or device variable and whether the
7158         // error should be ignored.
7159         EmitTLSUnsupportedError = true;
7160         // We still need to mark the variable as TLS so it shows up in AST with
7161         // proper storage class for other tools to use even if we're not going
7162         // to emit any code for it.
7163         NewVD->setTSCSpec(TSCS);
7164       } else
7165         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7166              diag::err_thread_unsupported);
7167     } else
7168       NewVD->setTSCSpec(TSCS);
7169   }
7170 
7171   switch (D.getDeclSpec().getConstexprSpecifier()) {
7172   case ConstexprSpecKind::Unspecified:
7173     break;
7174 
7175   case ConstexprSpecKind::Consteval:
7176     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7177          diag::err_constexpr_wrong_decl_kind)
7178         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7179     LLVM_FALLTHROUGH;
7180 
7181   case ConstexprSpecKind::Constexpr:
7182     NewVD->setConstexpr(true);
7183     MaybeAddCUDAConstantAttr(NewVD);
7184     // C++1z [dcl.spec.constexpr]p1:
7185     //   A static data member declared with the constexpr specifier is
7186     //   implicitly an inline variable.
7187     if (NewVD->isStaticDataMember() &&
7188         (getLangOpts().CPlusPlus17 ||
7189          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7190       NewVD->setImplicitlyInline();
7191     break;
7192 
7193   case ConstexprSpecKind::Constinit:
7194     if (!NewVD->hasGlobalStorage())
7195       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7196            diag::err_constinit_local_variable);
7197     else
7198       NewVD->addAttr(ConstInitAttr::Create(
7199           Context, D.getDeclSpec().getConstexprSpecLoc(),
7200           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7201     break;
7202   }
7203 
7204   // C99 6.7.4p3
7205   //   An inline definition of a function with external linkage shall
7206   //   not contain a definition of a modifiable object with static or
7207   //   thread storage duration...
7208   // We only apply this when the function is required to be defined
7209   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7210   // that a local variable with thread storage duration still has to
7211   // be marked 'static'.  Also note that it's possible to get these
7212   // semantics in C++ using __attribute__((gnu_inline)).
7213   if (SC == SC_Static && S->getFnParent() != nullptr &&
7214       !NewVD->getType().isConstQualified()) {
7215     FunctionDecl *CurFD = getCurFunctionDecl();
7216     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7217       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7218            diag::warn_static_local_in_extern_inline);
7219       MaybeSuggestAddingStaticToDecl(CurFD);
7220     }
7221   }
7222 
7223   if (D.getDeclSpec().isModulePrivateSpecified()) {
7224     if (IsVariableTemplateSpecialization)
7225       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7226           << (IsPartialSpecialization ? 1 : 0)
7227           << FixItHint::CreateRemoval(
7228                  D.getDeclSpec().getModulePrivateSpecLoc());
7229     else if (IsMemberSpecialization)
7230       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7231         << 2
7232         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7233     else if (NewVD->hasLocalStorage())
7234       Diag(NewVD->getLocation(), diag::err_module_private_local)
7235           << 0 << NewVD
7236           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7237           << FixItHint::CreateRemoval(
7238                  D.getDeclSpec().getModulePrivateSpecLoc());
7239     else {
7240       NewVD->setModulePrivate();
7241       if (NewTemplate)
7242         NewTemplate->setModulePrivate();
7243       for (auto *B : Bindings)
7244         B->setModulePrivate();
7245     }
7246   }
7247 
7248   if (getLangOpts().OpenCL) {
7249     deduceOpenCLAddressSpace(NewVD);
7250 
7251     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7252     if (TSC != TSCS_unspecified) {
7253       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7254       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7255            diag::err_opencl_unknown_type_specifier)
7256           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7257           << DeclSpec::getSpecifierName(TSC) << 1;
7258       NewVD->setInvalidDecl();
7259     }
7260   }
7261 
7262   // Handle attributes prior to checking for duplicates in MergeVarDecl
7263   ProcessDeclAttributes(S, NewVD, D);
7264 
7265   // FIXME: This is probably the wrong location to be doing this and we should
7266   // probably be doing this for more attributes (especially for function
7267   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7268   // the code to copy attributes would be generated by TableGen.
7269   if (R->isFunctionPointerType())
7270     if (const auto *TT = R->getAs<TypedefType>())
7271       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7272 
7273   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7274       getLangOpts().SYCLIsDevice) {
7275     if (EmitTLSUnsupportedError &&
7276         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7277          (getLangOpts().OpenMPIsDevice &&
7278           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7279       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7280            diag::err_thread_unsupported);
7281 
7282     if (EmitTLSUnsupportedError &&
7283         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7284       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7285     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7286     // storage [duration]."
7287     if (SC == SC_None && S->getFnParent() != nullptr &&
7288         (NewVD->hasAttr<CUDASharedAttr>() ||
7289          NewVD->hasAttr<CUDAConstantAttr>())) {
7290       NewVD->setStorageClass(SC_Static);
7291     }
7292   }
7293 
7294   // Ensure that dllimport globals without explicit storage class are treated as
7295   // extern. The storage class is set above using parsed attributes. Now we can
7296   // check the VarDecl itself.
7297   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7298          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7299          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7300 
7301   // In auto-retain/release, infer strong retension for variables of
7302   // retainable type.
7303   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7304     NewVD->setInvalidDecl();
7305 
7306   // Handle GNU asm-label extension (encoded as an attribute).
7307   if (Expr *E = (Expr*)D.getAsmLabel()) {
7308     // The parser guarantees this is a string.
7309     StringLiteral *SE = cast<StringLiteral>(E);
7310     StringRef Label = SE->getString();
7311     if (S->getFnParent() != nullptr) {
7312       switch (SC) {
7313       case SC_None:
7314       case SC_Auto:
7315         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7316         break;
7317       case SC_Register:
7318         // Local Named register
7319         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7320             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7321           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7322         break;
7323       case SC_Static:
7324       case SC_Extern:
7325       case SC_PrivateExtern:
7326         break;
7327       }
7328     } else if (SC == SC_Register) {
7329       // Global Named register
7330       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7331         const auto &TI = Context.getTargetInfo();
7332         bool HasSizeMismatch;
7333 
7334         if (!TI.isValidGCCRegisterName(Label))
7335           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7336         else if (!TI.validateGlobalRegisterVariable(Label,
7337                                                     Context.getTypeSize(R),
7338                                                     HasSizeMismatch))
7339           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7340         else if (HasSizeMismatch)
7341           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7342       }
7343 
7344       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7345         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7346         NewVD->setInvalidDecl(true);
7347       }
7348     }
7349 
7350     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7351                                         /*IsLiteralLabel=*/true,
7352                                         SE->getStrTokenLoc(0)));
7353   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7354     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7355       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7356     if (I != ExtnameUndeclaredIdentifiers.end()) {
7357       if (isDeclExternC(NewVD)) {
7358         NewVD->addAttr(I->second);
7359         ExtnameUndeclaredIdentifiers.erase(I);
7360       } else
7361         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7362             << /*Variable*/1 << NewVD;
7363     }
7364   }
7365 
7366   // Find the shadowed declaration before filtering for scope.
7367   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7368                                 ? getShadowedDeclaration(NewVD, Previous)
7369                                 : nullptr;
7370 
7371   // Don't consider existing declarations that are in a different
7372   // scope and are out-of-semantic-context declarations (if the new
7373   // declaration has linkage).
7374   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7375                        D.getCXXScopeSpec().isNotEmpty() ||
7376                        IsMemberSpecialization ||
7377                        IsVariableTemplateSpecialization);
7378 
7379   // Check whether the previous declaration is in the same block scope. This
7380   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7381   if (getLangOpts().CPlusPlus &&
7382       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7383     NewVD->setPreviousDeclInSameBlockScope(
7384         Previous.isSingleResult() && !Previous.isShadowed() &&
7385         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7386 
7387   if (!getLangOpts().CPlusPlus) {
7388     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7389   } else {
7390     // If this is an explicit specialization of a static data member, check it.
7391     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7392         CheckMemberSpecialization(NewVD, Previous))
7393       NewVD->setInvalidDecl();
7394 
7395     // Merge the decl with the existing one if appropriate.
7396     if (!Previous.empty()) {
7397       if (Previous.isSingleResult() &&
7398           isa<FieldDecl>(Previous.getFoundDecl()) &&
7399           D.getCXXScopeSpec().isSet()) {
7400         // The user tried to define a non-static data member
7401         // out-of-line (C++ [dcl.meaning]p1).
7402         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7403           << D.getCXXScopeSpec().getRange();
7404         Previous.clear();
7405         NewVD->setInvalidDecl();
7406       }
7407     } else if (D.getCXXScopeSpec().isSet()) {
7408       // No previous declaration in the qualifying scope.
7409       Diag(D.getIdentifierLoc(), diag::err_no_member)
7410         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7411         << D.getCXXScopeSpec().getRange();
7412       NewVD->setInvalidDecl();
7413     }
7414 
7415     if (!IsVariableTemplateSpecialization)
7416       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7417 
7418     if (NewTemplate) {
7419       VarTemplateDecl *PrevVarTemplate =
7420           NewVD->getPreviousDecl()
7421               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7422               : nullptr;
7423 
7424       // Check the template parameter list of this declaration, possibly
7425       // merging in the template parameter list from the previous variable
7426       // template declaration.
7427       if (CheckTemplateParameterList(
7428               TemplateParams,
7429               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7430                               : nullptr,
7431               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7432                DC->isDependentContext())
7433                   ? TPC_ClassTemplateMember
7434                   : TPC_VarTemplate))
7435         NewVD->setInvalidDecl();
7436 
7437       // If we are providing an explicit specialization of a static variable
7438       // template, make a note of that.
7439       if (PrevVarTemplate &&
7440           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7441         PrevVarTemplate->setMemberSpecialization();
7442     }
7443   }
7444 
7445   // Diagnose shadowed variables iff this isn't a redeclaration.
7446   if (ShadowedDecl && !D.isRedeclaration())
7447     CheckShadow(NewVD, ShadowedDecl, Previous);
7448 
7449   ProcessPragmaWeak(S, NewVD);
7450 
7451   // If this is the first declaration of an extern C variable, update
7452   // the map of such variables.
7453   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7454       isIncompleteDeclExternC(*this, NewVD))
7455     RegisterLocallyScopedExternCDecl(NewVD, S);
7456 
7457   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7458     MangleNumberingContext *MCtx;
7459     Decl *ManglingContextDecl;
7460     std::tie(MCtx, ManglingContextDecl) =
7461         getCurrentMangleNumberContext(NewVD->getDeclContext());
7462     if (MCtx) {
7463       Context.setManglingNumber(
7464           NewVD, MCtx->getManglingNumber(
7465                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7466       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7467     }
7468   }
7469 
7470   // Special handling of variable named 'main'.
7471   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7472       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7473       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7474 
7475     // C++ [basic.start.main]p3
7476     // A program that declares a variable main at global scope is ill-formed.
7477     if (getLangOpts().CPlusPlus)
7478       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7479 
7480     // In C, and external-linkage variable named main results in undefined
7481     // behavior.
7482     else if (NewVD->hasExternalFormalLinkage())
7483       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7484   }
7485 
7486   if (D.isRedeclaration() && !Previous.empty()) {
7487     NamedDecl *Prev = Previous.getRepresentativeDecl();
7488     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7489                                    D.isFunctionDefinition());
7490   }
7491 
7492   if (NewTemplate) {
7493     if (NewVD->isInvalidDecl())
7494       NewTemplate->setInvalidDecl();
7495     ActOnDocumentableDecl(NewTemplate);
7496     return NewTemplate;
7497   }
7498 
7499   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7500     CompleteMemberSpecialization(NewVD, Previous);
7501 
7502   return NewVD;
7503 }
7504 
7505 /// Enum describing the %select options in diag::warn_decl_shadow.
7506 enum ShadowedDeclKind {
7507   SDK_Local,
7508   SDK_Global,
7509   SDK_StaticMember,
7510   SDK_Field,
7511   SDK_Typedef,
7512   SDK_Using,
7513   SDK_StructuredBinding
7514 };
7515 
7516 /// Determine what kind of declaration we're shadowing.
7517 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7518                                                 const DeclContext *OldDC) {
7519   if (isa<TypeAliasDecl>(ShadowedDecl))
7520     return SDK_Using;
7521   else if (isa<TypedefDecl>(ShadowedDecl))
7522     return SDK_Typedef;
7523   else if (isa<BindingDecl>(ShadowedDecl))
7524     return SDK_StructuredBinding;
7525   else if (isa<RecordDecl>(OldDC))
7526     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7527 
7528   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7529 }
7530 
7531 /// Return the location of the capture if the given lambda captures the given
7532 /// variable \p VD, or an invalid source location otherwise.
7533 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7534                                          const VarDecl *VD) {
7535   for (const Capture &Capture : LSI->Captures) {
7536     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7537       return Capture.getLocation();
7538   }
7539   return SourceLocation();
7540 }
7541 
7542 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7543                                      const LookupResult &R) {
7544   // Only diagnose if we're shadowing an unambiguous field or variable.
7545   if (R.getResultKind() != LookupResult::Found)
7546     return false;
7547 
7548   // Return false if warning is ignored.
7549   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7550 }
7551 
7552 /// Return the declaration shadowed by the given variable \p D, or null
7553 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7554 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7555                                         const LookupResult &R) {
7556   if (!shouldWarnIfShadowedDecl(Diags, R))
7557     return nullptr;
7558 
7559   // Don't diagnose declarations at file scope.
7560   if (D->hasGlobalStorage())
7561     return nullptr;
7562 
7563   NamedDecl *ShadowedDecl = R.getFoundDecl();
7564   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7565                                                             : nullptr;
7566 }
7567 
7568 /// Return the declaration shadowed by the given typedef \p D, or null
7569 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7570 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7571                                         const LookupResult &R) {
7572   // Don't warn if typedef declaration is part of a class
7573   if (D->getDeclContext()->isRecord())
7574     return nullptr;
7575 
7576   if (!shouldWarnIfShadowedDecl(Diags, R))
7577     return nullptr;
7578 
7579   NamedDecl *ShadowedDecl = R.getFoundDecl();
7580   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7581 }
7582 
7583 /// Return the declaration shadowed by the given variable \p D, or null
7584 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7585 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7586                                         const LookupResult &R) {
7587   if (!shouldWarnIfShadowedDecl(Diags, R))
7588     return nullptr;
7589 
7590   NamedDecl *ShadowedDecl = R.getFoundDecl();
7591   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7592                                                             : nullptr;
7593 }
7594 
7595 /// Diagnose variable or built-in function shadowing.  Implements
7596 /// -Wshadow.
7597 ///
7598 /// This method is called whenever a VarDecl is added to a "useful"
7599 /// scope.
7600 ///
7601 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7602 /// \param R the lookup of the name
7603 ///
7604 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7605                        const LookupResult &R) {
7606   DeclContext *NewDC = D->getDeclContext();
7607 
7608   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7609     // Fields are not shadowed by variables in C++ static methods.
7610     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7611       if (MD->isStatic())
7612         return;
7613 
7614     // Fields shadowed by constructor parameters are a special case. Usually
7615     // the constructor initializes the field with the parameter.
7616     if (isa<CXXConstructorDecl>(NewDC))
7617       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7618         // Remember that this was shadowed so we can either warn about its
7619         // modification or its existence depending on warning settings.
7620         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7621         return;
7622       }
7623   }
7624 
7625   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7626     if (shadowedVar->isExternC()) {
7627       // For shadowing external vars, make sure that we point to the global
7628       // declaration, not a locally scoped extern declaration.
7629       for (auto I : shadowedVar->redecls())
7630         if (I->isFileVarDecl()) {
7631           ShadowedDecl = I;
7632           break;
7633         }
7634     }
7635 
7636   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7637 
7638   unsigned WarningDiag = diag::warn_decl_shadow;
7639   SourceLocation CaptureLoc;
7640   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7641       isa<CXXMethodDecl>(NewDC)) {
7642     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7643       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7644         if (RD->getLambdaCaptureDefault() == LCD_None) {
7645           // Try to avoid warnings for lambdas with an explicit capture list.
7646           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7647           // Warn only when the lambda captures the shadowed decl explicitly.
7648           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7649           if (CaptureLoc.isInvalid())
7650             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7651         } else {
7652           // Remember that this was shadowed so we can avoid the warning if the
7653           // shadowed decl isn't captured and the warning settings allow it.
7654           cast<LambdaScopeInfo>(getCurFunction())
7655               ->ShadowingDecls.push_back(
7656                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7657           return;
7658         }
7659       }
7660 
7661       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7662         // A variable can't shadow a local variable in an enclosing scope, if
7663         // they are separated by a non-capturing declaration context.
7664         for (DeclContext *ParentDC = NewDC;
7665              ParentDC && !ParentDC->Equals(OldDC);
7666              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7667           // Only block literals, captured statements, and lambda expressions
7668           // can capture; other scopes don't.
7669           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7670               !isLambdaCallOperator(ParentDC)) {
7671             return;
7672           }
7673         }
7674       }
7675     }
7676   }
7677 
7678   // Only warn about certain kinds of shadowing for class members.
7679   if (NewDC && NewDC->isRecord()) {
7680     // In particular, don't warn about shadowing non-class members.
7681     if (!OldDC->isRecord())
7682       return;
7683 
7684     // TODO: should we warn about static data members shadowing
7685     // static data members from base classes?
7686 
7687     // TODO: don't diagnose for inaccessible shadowed members.
7688     // This is hard to do perfectly because we might friend the
7689     // shadowing context, but that's just a false negative.
7690   }
7691 
7692 
7693   DeclarationName Name = R.getLookupName();
7694 
7695   // Emit warning and note.
7696   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7697     return;
7698   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7699   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7700   if (!CaptureLoc.isInvalid())
7701     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7702         << Name << /*explicitly*/ 1;
7703   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7704 }
7705 
7706 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7707 /// when these variables are captured by the lambda.
7708 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7709   for (const auto &Shadow : LSI->ShadowingDecls) {
7710     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7711     // Try to avoid the warning when the shadowed decl isn't captured.
7712     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7713     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7714     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7715                                        ? diag::warn_decl_shadow_uncaptured_local
7716                                        : diag::warn_decl_shadow)
7717         << Shadow.VD->getDeclName()
7718         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7719     if (!CaptureLoc.isInvalid())
7720       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7721           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7722     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7723   }
7724 }
7725 
7726 /// Check -Wshadow without the advantage of a previous lookup.
7727 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7728   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7729     return;
7730 
7731   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7732                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7733   LookupName(R, S);
7734   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7735     CheckShadow(D, ShadowedDecl, R);
7736 }
7737 
7738 /// Check if 'E', which is an expression that is about to be modified, refers
7739 /// to a constructor parameter that shadows a field.
7740 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7741   // Quickly ignore expressions that can't be shadowing ctor parameters.
7742   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7743     return;
7744   E = E->IgnoreParenImpCasts();
7745   auto *DRE = dyn_cast<DeclRefExpr>(E);
7746   if (!DRE)
7747     return;
7748   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7749   auto I = ShadowingDecls.find(D);
7750   if (I == ShadowingDecls.end())
7751     return;
7752   const NamedDecl *ShadowedDecl = I->second;
7753   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7754   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7755   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7756   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7757 
7758   // Avoid issuing multiple warnings about the same decl.
7759   ShadowingDecls.erase(I);
7760 }
7761 
7762 /// Check for conflict between this global or extern "C" declaration and
7763 /// previous global or extern "C" declarations. This is only used in C++.
7764 template<typename T>
7765 static bool checkGlobalOrExternCConflict(
7766     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7767   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7768   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7769 
7770   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7771     // The common case: this global doesn't conflict with any extern "C"
7772     // declaration.
7773     return false;
7774   }
7775 
7776   if (Prev) {
7777     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7778       // Both the old and new declarations have C language linkage. This is a
7779       // redeclaration.
7780       Previous.clear();
7781       Previous.addDecl(Prev);
7782       return true;
7783     }
7784 
7785     // This is a global, non-extern "C" declaration, and there is a previous
7786     // non-global extern "C" declaration. Diagnose if this is a variable
7787     // declaration.
7788     if (!isa<VarDecl>(ND))
7789       return false;
7790   } else {
7791     // The declaration is extern "C". Check for any declaration in the
7792     // translation unit which might conflict.
7793     if (IsGlobal) {
7794       // We have already performed the lookup into the translation unit.
7795       IsGlobal = false;
7796       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7797            I != E; ++I) {
7798         if (isa<VarDecl>(*I)) {
7799           Prev = *I;
7800           break;
7801         }
7802       }
7803     } else {
7804       DeclContext::lookup_result R =
7805           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7806       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7807            I != E; ++I) {
7808         if (isa<VarDecl>(*I)) {
7809           Prev = *I;
7810           break;
7811         }
7812         // FIXME: If we have any other entity with this name in global scope,
7813         // the declaration is ill-formed, but that is a defect: it breaks the
7814         // 'stat' hack, for instance. Only variables can have mangled name
7815         // clashes with extern "C" declarations, so only they deserve a
7816         // diagnostic.
7817       }
7818     }
7819 
7820     if (!Prev)
7821       return false;
7822   }
7823 
7824   // Use the first declaration's location to ensure we point at something which
7825   // is lexically inside an extern "C" linkage-spec.
7826   assert(Prev && "should have found a previous declaration to diagnose");
7827   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7828     Prev = FD->getFirstDecl();
7829   else
7830     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7831 
7832   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7833     << IsGlobal << ND;
7834   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7835     << IsGlobal;
7836   return false;
7837 }
7838 
7839 /// Apply special rules for handling extern "C" declarations. Returns \c true
7840 /// if we have found that this is a redeclaration of some prior entity.
7841 ///
7842 /// Per C++ [dcl.link]p6:
7843 ///   Two declarations [for a function or variable] with C language linkage
7844 ///   with the same name that appear in different scopes refer to the same
7845 ///   [entity]. An entity with C language linkage shall not be declared with
7846 ///   the same name as an entity in global scope.
7847 template<typename T>
7848 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7849                                                   LookupResult &Previous) {
7850   if (!S.getLangOpts().CPlusPlus) {
7851     // In C, when declaring a global variable, look for a corresponding 'extern'
7852     // variable declared in function scope. We don't need this in C++, because
7853     // we find local extern decls in the surrounding file-scope DeclContext.
7854     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7855       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7856         Previous.clear();
7857         Previous.addDecl(Prev);
7858         return true;
7859       }
7860     }
7861     return false;
7862   }
7863 
7864   // A declaration in the translation unit can conflict with an extern "C"
7865   // declaration.
7866   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7867     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7868 
7869   // An extern "C" declaration can conflict with a declaration in the
7870   // translation unit or can be a redeclaration of an extern "C" declaration
7871   // in another scope.
7872   if (isIncompleteDeclExternC(S,ND))
7873     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7874 
7875   // Neither global nor extern "C": nothing to do.
7876   return false;
7877 }
7878 
7879 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7880   // If the decl is already known invalid, don't check it.
7881   if (NewVD->isInvalidDecl())
7882     return;
7883 
7884   QualType T = NewVD->getType();
7885 
7886   // Defer checking an 'auto' type until its initializer is attached.
7887   if (T->isUndeducedType())
7888     return;
7889 
7890   if (NewVD->hasAttrs())
7891     CheckAlignasUnderalignment(NewVD);
7892 
7893   if (T->isObjCObjectType()) {
7894     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7895       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7896     T = Context.getObjCObjectPointerType(T);
7897     NewVD->setType(T);
7898   }
7899 
7900   // Emit an error if an address space was applied to decl with local storage.
7901   // This includes arrays of objects with address space qualifiers, but not
7902   // automatic variables that point to other address spaces.
7903   // ISO/IEC TR 18037 S5.1.2
7904   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7905       T.getAddressSpace() != LangAS::Default) {
7906     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7907     NewVD->setInvalidDecl();
7908     return;
7909   }
7910 
7911   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7912   // scope.
7913   if (getLangOpts().OpenCLVersion == 120 &&
7914       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7915                                             getLangOpts()) &&
7916       NewVD->isStaticLocal()) {
7917     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7918     NewVD->setInvalidDecl();
7919     return;
7920   }
7921 
7922   if (getLangOpts().OpenCL) {
7923     if (!diagnoseOpenCLTypes(*this, NewVD))
7924       return;
7925 
7926     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7927     if (NewVD->hasAttr<BlocksAttr>()) {
7928       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7929       return;
7930     }
7931 
7932     if (T->isBlockPointerType()) {
7933       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7934       // can't use 'extern' storage class.
7935       if (!T.isConstQualified()) {
7936         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7937             << 0 /*const*/;
7938         NewVD->setInvalidDecl();
7939         return;
7940       }
7941       if (NewVD->hasExternalStorage()) {
7942         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7943         NewVD->setInvalidDecl();
7944         return;
7945       }
7946     }
7947 
7948     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7949     // __constant address space.
7950     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7951     // variables inside a function can also be declared in the global
7952     // address space.
7953     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7954     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7955     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7956         NewVD->hasExternalStorage()) {
7957       if (!T->isSamplerT() &&
7958           !T->isDependentType() &&
7959           !(T.getAddressSpace() == LangAS::opencl_constant ||
7960             (T.getAddressSpace() == LangAS::opencl_global &&
7961              (getLangOpts().OpenCLVersion == 200 ||
7962               getLangOpts().OpenCLCPlusPlus)))) {
7963         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7964         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7965           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7966               << Scope << "global or constant";
7967         else
7968           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7969               << Scope << "constant";
7970         NewVD->setInvalidDecl();
7971         return;
7972       }
7973     } else {
7974       if (T.getAddressSpace() == LangAS::opencl_global) {
7975         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7976             << 1 /*is any function*/ << "global";
7977         NewVD->setInvalidDecl();
7978         return;
7979       }
7980       if (T.getAddressSpace() == LangAS::opencl_constant ||
7981           T.getAddressSpace() == LangAS::opencl_local) {
7982         FunctionDecl *FD = getCurFunctionDecl();
7983         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7984         // in functions.
7985         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7986           if (T.getAddressSpace() == LangAS::opencl_constant)
7987             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7988                 << 0 /*non-kernel only*/ << "constant";
7989           else
7990             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7991                 << 0 /*non-kernel only*/ << "local";
7992           NewVD->setInvalidDecl();
7993           return;
7994         }
7995         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7996         // in the outermost scope of a kernel function.
7997         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7998           if (!getCurScope()->isFunctionScope()) {
7999             if (T.getAddressSpace() == LangAS::opencl_constant)
8000               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8001                   << "constant";
8002             else
8003               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8004                   << "local";
8005             NewVD->setInvalidDecl();
8006             return;
8007           }
8008         }
8009       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8010                  // If we are parsing a template we didn't deduce an addr
8011                  // space yet.
8012                  T.getAddressSpace() != LangAS::Default) {
8013         // Do not allow other address spaces on automatic variable.
8014         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8015         NewVD->setInvalidDecl();
8016         return;
8017       }
8018     }
8019   }
8020 
8021   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8022       && !NewVD->hasAttr<BlocksAttr>()) {
8023     if (getLangOpts().getGC() != LangOptions::NonGC)
8024       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8025     else {
8026       assert(!getLangOpts().ObjCAutoRefCount);
8027       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8028     }
8029   }
8030 
8031   bool isVM = T->isVariablyModifiedType();
8032   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8033       NewVD->hasAttr<BlocksAttr>())
8034     setFunctionHasBranchProtectedScope();
8035 
8036   if ((isVM && NewVD->hasLinkage()) ||
8037       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8038     bool SizeIsNegative;
8039     llvm::APSInt Oversized;
8040     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8041         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8042     QualType FixedT;
8043     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8044       FixedT = FixedTInfo->getType();
8045     else if (FixedTInfo) {
8046       // Type and type-as-written are canonically different. We need to fix up
8047       // both types separately.
8048       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8049                                                    Oversized);
8050     }
8051     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8052       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8053       // FIXME: This won't give the correct result for
8054       // int a[10][n];
8055       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8056 
8057       if (NewVD->isFileVarDecl())
8058         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8059         << SizeRange;
8060       else if (NewVD->isStaticLocal())
8061         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8062         << SizeRange;
8063       else
8064         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8065         << SizeRange;
8066       NewVD->setInvalidDecl();
8067       return;
8068     }
8069 
8070     if (!FixedTInfo) {
8071       if (NewVD->isFileVarDecl())
8072         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8073       else
8074         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8075       NewVD->setInvalidDecl();
8076       return;
8077     }
8078 
8079     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8080     NewVD->setType(FixedT);
8081     NewVD->setTypeSourceInfo(FixedTInfo);
8082   }
8083 
8084   if (T->isVoidType()) {
8085     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8086     //                    of objects and functions.
8087     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8088       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8089         << T;
8090       NewVD->setInvalidDecl();
8091       return;
8092     }
8093   }
8094 
8095   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8096     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8097     NewVD->setInvalidDecl();
8098     return;
8099   }
8100 
8101   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8102     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8103     NewVD->setInvalidDecl();
8104     return;
8105   }
8106 
8107   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8108     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8109     NewVD->setInvalidDecl();
8110     return;
8111   }
8112 
8113   if (NewVD->isConstexpr() && !T->isDependentType() &&
8114       RequireLiteralType(NewVD->getLocation(), T,
8115                          diag::err_constexpr_var_non_literal)) {
8116     NewVD->setInvalidDecl();
8117     return;
8118   }
8119 
8120   // PPC MMA non-pointer types are not allowed as non-local variable types.
8121   if (Context.getTargetInfo().getTriple().isPPC64() &&
8122       !NewVD->isLocalVarDecl() &&
8123       CheckPPCMMAType(T, NewVD->getLocation())) {
8124     NewVD->setInvalidDecl();
8125     return;
8126   }
8127 }
8128 
8129 /// Perform semantic checking on a newly-created variable
8130 /// declaration.
8131 ///
8132 /// This routine performs all of the type-checking required for a
8133 /// variable declaration once it has been built. It is used both to
8134 /// check variables after they have been parsed and their declarators
8135 /// have been translated into a declaration, and to check variables
8136 /// that have been instantiated from a template.
8137 ///
8138 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8139 ///
8140 /// Returns true if the variable declaration is a redeclaration.
8141 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8142   CheckVariableDeclarationType(NewVD);
8143 
8144   // If the decl is already known invalid, don't check it.
8145   if (NewVD->isInvalidDecl())
8146     return false;
8147 
8148   // If we did not find anything by this name, look for a non-visible
8149   // extern "C" declaration with the same name.
8150   if (Previous.empty() &&
8151       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8152     Previous.setShadowed();
8153 
8154   if (!Previous.empty()) {
8155     MergeVarDecl(NewVD, Previous);
8156     return true;
8157   }
8158   return false;
8159 }
8160 
8161 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8162 /// and if so, check that it's a valid override and remember it.
8163 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8164   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8165 
8166   // Look for methods in base classes that this method might override.
8167   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8168                      /*DetectVirtual=*/false);
8169   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8170     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8171     DeclarationName Name = MD->getDeclName();
8172 
8173     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8174       // We really want to find the base class destructor here.
8175       QualType T = Context.getTypeDeclType(BaseRecord);
8176       CanQualType CT = Context.getCanonicalType(T);
8177       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8178     }
8179 
8180     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8181       CXXMethodDecl *BaseMD =
8182           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8183       if (!BaseMD || !BaseMD->isVirtual() ||
8184           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8185                      /*ConsiderCudaAttrs=*/true,
8186                      // C++2a [class.virtual]p2 does not consider requires
8187                      // clauses when overriding.
8188                      /*ConsiderRequiresClauses=*/false))
8189         continue;
8190 
8191       if (Overridden.insert(BaseMD).second) {
8192         MD->addOverriddenMethod(BaseMD);
8193         CheckOverridingFunctionReturnType(MD, BaseMD);
8194         CheckOverridingFunctionAttributes(MD, BaseMD);
8195         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8196         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8197       }
8198 
8199       // A method can only override one function from each base class. We
8200       // don't track indirectly overridden methods from bases of bases.
8201       return true;
8202     }
8203 
8204     return false;
8205   };
8206 
8207   DC->lookupInBases(VisitBase, Paths);
8208   return !Overridden.empty();
8209 }
8210 
8211 namespace {
8212   // Struct for holding all of the extra arguments needed by
8213   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8214   struct ActOnFDArgs {
8215     Scope *S;
8216     Declarator &D;
8217     MultiTemplateParamsArg TemplateParamLists;
8218     bool AddToScope;
8219   };
8220 } // end anonymous namespace
8221 
8222 namespace {
8223 
8224 // Callback to only accept typo corrections that have a non-zero edit distance.
8225 // Also only accept corrections that have the same parent decl.
8226 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8227  public:
8228   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8229                             CXXRecordDecl *Parent)
8230       : Context(Context), OriginalFD(TypoFD),
8231         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8232 
8233   bool ValidateCandidate(const TypoCorrection &candidate) override {
8234     if (candidate.getEditDistance() == 0)
8235       return false;
8236 
8237     SmallVector<unsigned, 1> MismatchedParams;
8238     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8239                                           CDeclEnd = candidate.end();
8240          CDecl != CDeclEnd; ++CDecl) {
8241       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8242 
8243       if (FD && !FD->hasBody() &&
8244           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8245         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8246           CXXRecordDecl *Parent = MD->getParent();
8247           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8248             return true;
8249         } else if (!ExpectedParent) {
8250           return true;
8251         }
8252       }
8253     }
8254 
8255     return false;
8256   }
8257 
8258   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8259     return std::make_unique<DifferentNameValidatorCCC>(*this);
8260   }
8261 
8262  private:
8263   ASTContext &Context;
8264   FunctionDecl *OriginalFD;
8265   CXXRecordDecl *ExpectedParent;
8266 };
8267 
8268 } // end anonymous namespace
8269 
8270 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8271   TypoCorrectedFunctionDefinitions.insert(F);
8272 }
8273 
8274 /// Generate diagnostics for an invalid function redeclaration.
8275 ///
8276 /// This routine handles generating the diagnostic messages for an invalid
8277 /// function redeclaration, including finding possible similar declarations
8278 /// or performing typo correction if there are no previous declarations with
8279 /// the same name.
8280 ///
8281 /// Returns a NamedDecl iff typo correction was performed and substituting in
8282 /// the new declaration name does not cause new errors.
8283 static NamedDecl *DiagnoseInvalidRedeclaration(
8284     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8285     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8286   DeclarationName Name = NewFD->getDeclName();
8287   DeclContext *NewDC = NewFD->getDeclContext();
8288   SmallVector<unsigned, 1> MismatchedParams;
8289   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8290   TypoCorrection Correction;
8291   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8292   unsigned DiagMsg =
8293     IsLocalFriend ? diag::err_no_matching_local_friend :
8294     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8295     diag::err_member_decl_does_not_match;
8296   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8297                     IsLocalFriend ? Sema::LookupLocalFriendName
8298                                   : Sema::LookupOrdinaryName,
8299                     Sema::ForVisibleRedeclaration);
8300 
8301   NewFD->setInvalidDecl();
8302   if (IsLocalFriend)
8303     SemaRef.LookupName(Prev, S);
8304   else
8305     SemaRef.LookupQualifiedName(Prev, NewDC);
8306   assert(!Prev.isAmbiguous() &&
8307          "Cannot have an ambiguity in previous-declaration lookup");
8308   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8309   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8310                                 MD ? MD->getParent() : nullptr);
8311   if (!Prev.empty()) {
8312     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8313          Func != FuncEnd; ++Func) {
8314       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8315       if (FD &&
8316           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8317         // Add 1 to the index so that 0 can mean the mismatch didn't
8318         // involve a parameter
8319         unsigned ParamNum =
8320             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8321         NearMatches.push_back(std::make_pair(FD, ParamNum));
8322       }
8323     }
8324   // If the qualified name lookup yielded nothing, try typo correction
8325   } else if ((Correction = SemaRef.CorrectTypo(
8326                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8327                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8328                   IsLocalFriend ? nullptr : NewDC))) {
8329     // Set up everything for the call to ActOnFunctionDeclarator
8330     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8331                               ExtraArgs.D.getIdentifierLoc());
8332     Previous.clear();
8333     Previous.setLookupName(Correction.getCorrection());
8334     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8335                                     CDeclEnd = Correction.end();
8336          CDecl != CDeclEnd; ++CDecl) {
8337       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8338       if (FD && !FD->hasBody() &&
8339           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8340         Previous.addDecl(FD);
8341       }
8342     }
8343     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8344 
8345     NamedDecl *Result;
8346     // Retry building the function declaration with the new previous
8347     // declarations, and with errors suppressed.
8348     {
8349       // Trap errors.
8350       Sema::SFINAETrap Trap(SemaRef);
8351 
8352       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8353       // pieces need to verify the typo-corrected C++ declaration and hopefully
8354       // eliminate the need for the parameter pack ExtraArgs.
8355       Result = SemaRef.ActOnFunctionDeclarator(
8356           ExtraArgs.S, ExtraArgs.D,
8357           Correction.getCorrectionDecl()->getDeclContext(),
8358           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8359           ExtraArgs.AddToScope);
8360 
8361       if (Trap.hasErrorOccurred())
8362         Result = nullptr;
8363     }
8364 
8365     if (Result) {
8366       // Determine which correction we picked.
8367       Decl *Canonical = Result->getCanonicalDecl();
8368       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8369            I != E; ++I)
8370         if ((*I)->getCanonicalDecl() == Canonical)
8371           Correction.setCorrectionDecl(*I);
8372 
8373       // Let Sema know about the correction.
8374       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8375       SemaRef.diagnoseTypo(
8376           Correction,
8377           SemaRef.PDiag(IsLocalFriend
8378                           ? diag::err_no_matching_local_friend_suggest
8379                           : diag::err_member_decl_does_not_match_suggest)
8380             << Name << NewDC << IsDefinition);
8381       return Result;
8382     }
8383 
8384     // Pretend the typo correction never occurred
8385     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8386                               ExtraArgs.D.getIdentifierLoc());
8387     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8388     Previous.clear();
8389     Previous.setLookupName(Name);
8390   }
8391 
8392   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8393       << Name << NewDC << IsDefinition << NewFD->getLocation();
8394 
8395   bool NewFDisConst = false;
8396   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8397     NewFDisConst = NewMD->isConst();
8398 
8399   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8400        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8401        NearMatch != NearMatchEnd; ++NearMatch) {
8402     FunctionDecl *FD = NearMatch->first;
8403     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8404     bool FDisConst = MD && MD->isConst();
8405     bool IsMember = MD || !IsLocalFriend;
8406 
8407     // FIXME: These notes are poorly worded for the local friend case.
8408     if (unsigned Idx = NearMatch->second) {
8409       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8410       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8411       if (Loc.isInvalid()) Loc = FD->getLocation();
8412       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8413                                  : diag::note_local_decl_close_param_match)
8414         << Idx << FDParam->getType()
8415         << NewFD->getParamDecl(Idx - 1)->getType();
8416     } else if (FDisConst != NewFDisConst) {
8417       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8418           << NewFDisConst << FD->getSourceRange().getEnd();
8419     } else
8420       SemaRef.Diag(FD->getLocation(),
8421                    IsMember ? diag::note_member_def_close_match
8422                             : diag::note_local_decl_close_match);
8423   }
8424   return nullptr;
8425 }
8426 
8427 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8428   switch (D.getDeclSpec().getStorageClassSpec()) {
8429   default: llvm_unreachable("Unknown storage class!");
8430   case DeclSpec::SCS_auto:
8431   case DeclSpec::SCS_register:
8432   case DeclSpec::SCS_mutable:
8433     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8434                  diag::err_typecheck_sclass_func);
8435     D.getMutableDeclSpec().ClearStorageClassSpecs();
8436     D.setInvalidType();
8437     break;
8438   case DeclSpec::SCS_unspecified: break;
8439   case DeclSpec::SCS_extern:
8440     if (D.getDeclSpec().isExternInLinkageSpec())
8441       return SC_None;
8442     return SC_Extern;
8443   case DeclSpec::SCS_static: {
8444     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8445       // C99 6.7.1p5:
8446       //   The declaration of an identifier for a function that has
8447       //   block scope shall have no explicit storage-class specifier
8448       //   other than extern
8449       // See also (C++ [dcl.stc]p4).
8450       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8451                    diag::err_static_block_func);
8452       break;
8453     } else
8454       return SC_Static;
8455   }
8456   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8457   }
8458 
8459   // No explicit storage class has already been returned
8460   return SC_None;
8461 }
8462 
8463 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8464                                            DeclContext *DC, QualType &R,
8465                                            TypeSourceInfo *TInfo,
8466                                            StorageClass SC,
8467                                            bool &IsVirtualOkay) {
8468   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8469   DeclarationName Name = NameInfo.getName();
8470 
8471   FunctionDecl *NewFD = nullptr;
8472   bool isInline = D.getDeclSpec().isInlineSpecified();
8473 
8474   if (!SemaRef.getLangOpts().CPlusPlus) {
8475     // Determine whether the function was written with a
8476     // prototype. This true when:
8477     //   - there is a prototype in the declarator, or
8478     //   - the type R of the function is some kind of typedef or other non-
8479     //     attributed reference to a type name (which eventually refers to a
8480     //     function type).
8481     bool HasPrototype =
8482       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8483       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8484 
8485     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8486                                  R, TInfo, SC, isInline, HasPrototype,
8487                                  ConstexprSpecKind::Unspecified,
8488                                  /*TrailingRequiresClause=*/nullptr);
8489     if (D.isInvalidType())
8490       NewFD->setInvalidDecl();
8491 
8492     return NewFD;
8493   }
8494 
8495   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8496 
8497   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8498   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8499     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8500                  diag::err_constexpr_wrong_decl_kind)
8501         << static_cast<int>(ConstexprKind);
8502     ConstexprKind = ConstexprSpecKind::Unspecified;
8503     D.getMutableDeclSpec().ClearConstexprSpec();
8504   }
8505   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8506 
8507   // Check that the return type is not an abstract class type.
8508   // For record types, this is done by the AbstractClassUsageDiagnoser once
8509   // the class has been completely parsed.
8510   if (!DC->isRecord() &&
8511       SemaRef.RequireNonAbstractType(
8512           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8513           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8514     D.setInvalidType();
8515 
8516   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8517     // This is a C++ constructor declaration.
8518     assert(DC->isRecord() &&
8519            "Constructors can only be declared in a member context");
8520 
8521     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8522     return CXXConstructorDecl::Create(
8523         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8524         TInfo, ExplicitSpecifier, isInline,
8525         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8526         TrailingRequiresClause);
8527 
8528   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8529     // This is a C++ destructor declaration.
8530     if (DC->isRecord()) {
8531       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8532       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8533       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8534           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8535           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8536           TrailingRequiresClause);
8537 
8538       // If the destructor needs an implicit exception specification, set it
8539       // now. FIXME: It'd be nice to be able to create the right type to start
8540       // with, but the type needs to reference the destructor declaration.
8541       if (SemaRef.getLangOpts().CPlusPlus11)
8542         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8543 
8544       IsVirtualOkay = true;
8545       return NewDD;
8546 
8547     } else {
8548       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8549       D.setInvalidType();
8550 
8551       // Create a FunctionDecl to satisfy the function definition parsing
8552       // code path.
8553       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8554                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8555                                   isInline,
8556                                   /*hasPrototype=*/true, ConstexprKind,
8557                                   TrailingRequiresClause);
8558     }
8559 
8560   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8561     if (!DC->isRecord()) {
8562       SemaRef.Diag(D.getIdentifierLoc(),
8563            diag::err_conv_function_not_member);
8564       return nullptr;
8565     }
8566 
8567     SemaRef.CheckConversionDeclarator(D, R, SC);
8568     if (D.isInvalidType())
8569       return nullptr;
8570 
8571     IsVirtualOkay = true;
8572     return CXXConversionDecl::Create(
8573         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8574         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8575         TrailingRequiresClause);
8576 
8577   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8578     if (TrailingRequiresClause)
8579       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8580                    diag::err_trailing_requires_clause_on_deduction_guide)
8581           << TrailingRequiresClause->getSourceRange();
8582     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8583 
8584     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8585                                          ExplicitSpecifier, NameInfo, R, TInfo,
8586                                          D.getEndLoc());
8587   } else if (DC->isRecord()) {
8588     // If the name of the function is the same as the name of the record,
8589     // then this must be an invalid constructor that has a return type.
8590     // (The parser checks for a return type and makes the declarator a
8591     // constructor if it has no return type).
8592     if (Name.getAsIdentifierInfo() &&
8593         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8594       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8595         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8596         << SourceRange(D.getIdentifierLoc());
8597       return nullptr;
8598     }
8599 
8600     // This is a C++ method declaration.
8601     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8602         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8603         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8604         TrailingRequiresClause);
8605     IsVirtualOkay = !Ret->isStatic();
8606     return Ret;
8607   } else {
8608     bool isFriend =
8609         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8610     if (!isFriend && SemaRef.CurContext->isRecord())
8611       return nullptr;
8612 
8613     // Determine whether the function was written with a
8614     // prototype. This true when:
8615     //   - we're in C++ (where every function has a prototype),
8616     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8617                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8618                                 ConstexprKind, TrailingRequiresClause);
8619   }
8620 }
8621 
8622 enum OpenCLParamType {
8623   ValidKernelParam,
8624   PtrPtrKernelParam,
8625   PtrKernelParam,
8626   InvalidAddrSpacePtrKernelParam,
8627   InvalidKernelParam,
8628   RecordKernelParam
8629 };
8630 
8631 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8632   // Size dependent types are just typedefs to normal integer types
8633   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8634   // integers other than by their names.
8635   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8636 
8637   // Remove typedefs one by one until we reach a typedef
8638   // for a size dependent type.
8639   QualType DesugaredTy = Ty;
8640   do {
8641     ArrayRef<StringRef> Names(SizeTypeNames);
8642     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8643     if (Names.end() != Match)
8644       return true;
8645 
8646     Ty = DesugaredTy;
8647     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8648   } while (DesugaredTy != Ty);
8649 
8650   return false;
8651 }
8652 
8653 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8654   if (PT->isPointerType() || PT->isReferenceType()) {
8655     QualType PointeeType = PT->getPointeeType();
8656     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8657         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8658         PointeeType.getAddressSpace() == LangAS::Default)
8659       return InvalidAddrSpacePtrKernelParam;
8660 
8661     if (PointeeType->isPointerType()) {
8662       // This is a pointer to pointer parameter.
8663       // Recursively check inner type.
8664       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8665       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8666           ParamKind == InvalidKernelParam)
8667         return ParamKind;
8668 
8669       return PtrPtrKernelParam;
8670     }
8671 
8672     // C++ for OpenCL v1.0 s2.4:
8673     // Moreover the types used in parameters of the kernel functions must be:
8674     // Standard layout types for pointer parameters. The same applies to
8675     // reference if an implementation supports them in kernel parameters.
8676     if (S.getLangOpts().OpenCLCPlusPlus && !PointeeType->isAtomicType() &&
8677         !PointeeType->isVoidType() && !PointeeType->isStandardLayoutType())
8678       return InvalidKernelParam;
8679 
8680     return PtrKernelParam;
8681   }
8682 
8683   // OpenCL v1.2 s6.9.k:
8684   // Arguments to kernel functions in a program cannot be declared with the
8685   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8686   // uintptr_t or a struct and/or union that contain fields declared to be one
8687   // of these built-in scalar types.
8688   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8689     return InvalidKernelParam;
8690 
8691   if (PT->isImageType())
8692     return PtrKernelParam;
8693 
8694   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8695     return InvalidKernelParam;
8696 
8697   // OpenCL extension spec v1.2 s9.5:
8698   // This extension adds support for half scalar and vector types as built-in
8699   // types that can be used for arithmetic operations, conversions etc.
8700   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8701       PT->isHalfType())
8702     return InvalidKernelParam;
8703 
8704   // Look into an array argument to check if it has a forbidden type.
8705   if (PT->isArrayType()) {
8706     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8707     // Call ourself to check an underlying type of an array. Since the
8708     // getPointeeOrArrayElementType returns an innermost type which is not an
8709     // array, this recursive call only happens once.
8710     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8711   }
8712 
8713   // C++ for OpenCL v1.0 s2.4:
8714   // Moreover the types used in parameters of the kernel functions must be:
8715   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8716   // types) for parameters passed by value;
8717   if (S.getLangOpts().OpenCLCPlusPlus && !PT->isOpenCLSpecificType() &&
8718       !PT.isPODType(S.Context))
8719     return InvalidKernelParam;
8720 
8721   if (PT->isRecordType())
8722     return RecordKernelParam;
8723 
8724   return ValidKernelParam;
8725 }
8726 
8727 static void checkIsValidOpenCLKernelParameter(
8728   Sema &S,
8729   Declarator &D,
8730   ParmVarDecl *Param,
8731   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8732   QualType PT = Param->getType();
8733 
8734   // Cache the valid types we encounter to avoid rechecking structs that are
8735   // used again
8736   if (ValidTypes.count(PT.getTypePtr()))
8737     return;
8738 
8739   switch (getOpenCLKernelParameterType(S, PT)) {
8740   case PtrPtrKernelParam:
8741     // OpenCL v3.0 s6.11.a:
8742     // A kernel function argument cannot be declared as a pointer to a pointer
8743     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8744     if (S.getLangOpts().OpenCLVersion < 120 &&
8745         !S.getLangOpts().OpenCLCPlusPlus) {
8746       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8747       D.setInvalidType();
8748       return;
8749     }
8750 
8751     ValidTypes.insert(PT.getTypePtr());
8752     return;
8753 
8754   case InvalidAddrSpacePtrKernelParam:
8755     // OpenCL v1.0 s6.5:
8756     // __kernel function arguments declared to be a pointer of a type can point
8757     // to one of the following address spaces only : __global, __local or
8758     // __constant.
8759     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8760     D.setInvalidType();
8761     return;
8762 
8763     // OpenCL v1.2 s6.9.k:
8764     // Arguments to kernel functions in a program cannot be declared with the
8765     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8766     // uintptr_t or a struct and/or union that contain fields declared to be
8767     // one of these built-in scalar types.
8768 
8769   case InvalidKernelParam:
8770     // OpenCL v1.2 s6.8 n:
8771     // A kernel function argument cannot be declared
8772     // of event_t type.
8773     // Do not diagnose half type since it is diagnosed as invalid argument
8774     // type for any function elsewhere.
8775     if (!PT->isHalfType()) {
8776       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8777 
8778       // Explain what typedefs are involved.
8779       const TypedefType *Typedef = nullptr;
8780       while ((Typedef = PT->getAs<TypedefType>())) {
8781         SourceLocation Loc = Typedef->getDecl()->getLocation();
8782         // SourceLocation may be invalid for a built-in type.
8783         if (Loc.isValid())
8784           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8785         PT = Typedef->desugar();
8786       }
8787     }
8788 
8789     D.setInvalidType();
8790     return;
8791 
8792   case PtrKernelParam:
8793   case ValidKernelParam:
8794     ValidTypes.insert(PT.getTypePtr());
8795     return;
8796 
8797   case RecordKernelParam:
8798     break;
8799   }
8800 
8801   // Track nested structs we will inspect
8802   SmallVector<const Decl *, 4> VisitStack;
8803 
8804   // Track where we are in the nested structs. Items will migrate from
8805   // VisitStack to HistoryStack as we do the DFS for bad field.
8806   SmallVector<const FieldDecl *, 4> HistoryStack;
8807   HistoryStack.push_back(nullptr);
8808 
8809   // At this point we already handled everything except of a RecordType or
8810   // an ArrayType of a RecordType.
8811   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8812   const RecordType *RecTy =
8813       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8814   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8815 
8816   VisitStack.push_back(RecTy->getDecl());
8817   assert(VisitStack.back() && "First decl null?");
8818 
8819   do {
8820     const Decl *Next = VisitStack.pop_back_val();
8821     if (!Next) {
8822       assert(!HistoryStack.empty());
8823       // Found a marker, we have gone up a level
8824       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8825         ValidTypes.insert(Hist->getType().getTypePtr());
8826 
8827       continue;
8828     }
8829 
8830     // Adds everything except the original parameter declaration (which is not a
8831     // field itself) to the history stack.
8832     const RecordDecl *RD;
8833     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8834       HistoryStack.push_back(Field);
8835 
8836       QualType FieldTy = Field->getType();
8837       // Other field types (known to be valid or invalid) are handled while we
8838       // walk around RecordDecl::fields().
8839       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8840              "Unexpected type.");
8841       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8842 
8843       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8844     } else {
8845       RD = cast<RecordDecl>(Next);
8846     }
8847 
8848     // Add a null marker so we know when we've gone back up a level
8849     VisitStack.push_back(nullptr);
8850 
8851     for (const auto *FD : RD->fields()) {
8852       QualType QT = FD->getType();
8853 
8854       if (ValidTypes.count(QT.getTypePtr()))
8855         continue;
8856 
8857       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8858       if (ParamType == ValidKernelParam)
8859         continue;
8860 
8861       if (ParamType == RecordKernelParam) {
8862         VisitStack.push_back(FD);
8863         continue;
8864       }
8865 
8866       // OpenCL v1.2 s6.9.p:
8867       // Arguments to kernel functions that are declared to be a struct or union
8868       // do not allow OpenCL objects to be passed as elements of the struct or
8869       // union.
8870       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8871           ParamType == InvalidAddrSpacePtrKernelParam) {
8872         S.Diag(Param->getLocation(),
8873                diag::err_record_with_pointers_kernel_param)
8874           << PT->isUnionType()
8875           << PT;
8876       } else {
8877         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8878       }
8879 
8880       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8881           << OrigRecDecl->getDeclName();
8882 
8883       // We have an error, now let's go back up through history and show where
8884       // the offending field came from
8885       for (ArrayRef<const FieldDecl *>::const_iterator
8886                I = HistoryStack.begin() + 1,
8887                E = HistoryStack.end();
8888            I != E; ++I) {
8889         const FieldDecl *OuterField = *I;
8890         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8891           << OuterField->getType();
8892       }
8893 
8894       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8895         << QT->isPointerType()
8896         << QT;
8897       D.setInvalidType();
8898       return;
8899     }
8900   } while (!VisitStack.empty());
8901 }
8902 
8903 /// Find the DeclContext in which a tag is implicitly declared if we see an
8904 /// elaborated type specifier in the specified context, and lookup finds
8905 /// nothing.
8906 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8907   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8908     DC = DC->getParent();
8909   return DC;
8910 }
8911 
8912 /// Find the Scope in which a tag is implicitly declared if we see an
8913 /// elaborated type specifier in the specified context, and lookup finds
8914 /// nothing.
8915 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8916   while (S->isClassScope() ||
8917          (LangOpts.CPlusPlus &&
8918           S->isFunctionPrototypeScope()) ||
8919          ((S->getFlags() & Scope::DeclScope) == 0) ||
8920          (S->getEntity() && S->getEntity()->isTransparentContext()))
8921     S = S->getParent();
8922   return S;
8923 }
8924 
8925 NamedDecl*
8926 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8927                               TypeSourceInfo *TInfo, LookupResult &Previous,
8928                               MultiTemplateParamsArg TemplateParamListsRef,
8929                               bool &AddToScope) {
8930   QualType R = TInfo->getType();
8931 
8932   assert(R->isFunctionType());
8933   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8934     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8935 
8936   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8937   for (TemplateParameterList *TPL : TemplateParamListsRef)
8938     TemplateParamLists.push_back(TPL);
8939   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8940     if (!TemplateParamLists.empty() &&
8941         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8942       TemplateParamLists.back() = Invented;
8943     else
8944       TemplateParamLists.push_back(Invented);
8945   }
8946 
8947   // TODO: consider using NameInfo for diagnostic.
8948   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8949   DeclarationName Name = NameInfo.getName();
8950   StorageClass SC = getFunctionStorageClass(*this, D);
8951 
8952   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8953     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8954          diag::err_invalid_thread)
8955       << DeclSpec::getSpecifierName(TSCS);
8956 
8957   if (D.isFirstDeclarationOfMember())
8958     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8959                            D.getIdentifierLoc());
8960 
8961   bool isFriend = false;
8962   FunctionTemplateDecl *FunctionTemplate = nullptr;
8963   bool isMemberSpecialization = false;
8964   bool isFunctionTemplateSpecialization = false;
8965 
8966   bool isDependentClassScopeExplicitSpecialization = false;
8967   bool HasExplicitTemplateArgs = false;
8968   TemplateArgumentListInfo TemplateArgs;
8969 
8970   bool isVirtualOkay = false;
8971 
8972   DeclContext *OriginalDC = DC;
8973   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8974 
8975   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8976                                               isVirtualOkay);
8977   if (!NewFD) return nullptr;
8978 
8979   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8980     NewFD->setTopLevelDeclInObjCContainer();
8981 
8982   // Set the lexical context. If this is a function-scope declaration, or has a
8983   // C++ scope specifier, or is the object of a friend declaration, the lexical
8984   // context will be different from the semantic context.
8985   NewFD->setLexicalDeclContext(CurContext);
8986 
8987   if (IsLocalExternDecl)
8988     NewFD->setLocalExternDecl();
8989 
8990   if (getLangOpts().CPlusPlus) {
8991     bool isInline = D.getDeclSpec().isInlineSpecified();
8992     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8993     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8994     isFriend = D.getDeclSpec().isFriendSpecified();
8995     if (isFriend && !isInline && D.isFunctionDefinition()) {
8996       // C++ [class.friend]p5
8997       //   A function can be defined in a friend declaration of a
8998       //   class . . . . Such a function is implicitly inline.
8999       NewFD->setImplicitlyInline();
9000     }
9001 
9002     // If this is a method defined in an __interface, and is not a constructor
9003     // or an overloaded operator, then set the pure flag (isVirtual will already
9004     // return true).
9005     if (const CXXRecordDecl *Parent =
9006           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9007       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9008         NewFD->setPure(true);
9009 
9010       // C++ [class.union]p2
9011       //   A union can have member functions, but not virtual functions.
9012       if (isVirtual && Parent->isUnion())
9013         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9014     }
9015 
9016     SetNestedNameSpecifier(*this, NewFD, D);
9017     isMemberSpecialization = false;
9018     isFunctionTemplateSpecialization = false;
9019     if (D.isInvalidType())
9020       NewFD->setInvalidDecl();
9021 
9022     // Match up the template parameter lists with the scope specifier, then
9023     // determine whether we have a template or a template specialization.
9024     bool Invalid = false;
9025     TemplateParameterList *TemplateParams =
9026         MatchTemplateParametersToScopeSpecifier(
9027             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9028             D.getCXXScopeSpec(),
9029             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9030                 ? D.getName().TemplateId
9031                 : nullptr,
9032             TemplateParamLists, isFriend, isMemberSpecialization,
9033             Invalid);
9034     if (TemplateParams) {
9035       // Check that we can declare a template here.
9036       if (CheckTemplateDeclScope(S, TemplateParams))
9037         NewFD->setInvalidDecl();
9038 
9039       if (TemplateParams->size() > 0) {
9040         // This is a function template
9041 
9042         // A destructor cannot be a template.
9043         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9044           Diag(NewFD->getLocation(), diag::err_destructor_template);
9045           NewFD->setInvalidDecl();
9046         }
9047 
9048         // If we're adding a template to a dependent context, we may need to
9049         // rebuilding some of the types used within the template parameter list,
9050         // now that we know what the current instantiation is.
9051         if (DC->isDependentContext()) {
9052           ContextRAII SavedContext(*this, DC);
9053           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9054             Invalid = true;
9055         }
9056 
9057         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9058                                                         NewFD->getLocation(),
9059                                                         Name, TemplateParams,
9060                                                         NewFD);
9061         FunctionTemplate->setLexicalDeclContext(CurContext);
9062         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9063 
9064         // For source fidelity, store the other template param lists.
9065         if (TemplateParamLists.size() > 1) {
9066           NewFD->setTemplateParameterListsInfo(Context,
9067               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9068                   .drop_back(1));
9069         }
9070       } else {
9071         // This is a function template specialization.
9072         isFunctionTemplateSpecialization = true;
9073         // For source fidelity, store all the template param lists.
9074         if (TemplateParamLists.size() > 0)
9075           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9076 
9077         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9078         if (isFriend) {
9079           // We want to remove the "template<>", found here.
9080           SourceRange RemoveRange = TemplateParams->getSourceRange();
9081 
9082           // If we remove the template<> and the name is not a
9083           // template-id, we're actually silently creating a problem:
9084           // the friend declaration will refer to an untemplated decl,
9085           // and clearly the user wants a template specialization.  So
9086           // we need to insert '<>' after the name.
9087           SourceLocation InsertLoc;
9088           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9089             InsertLoc = D.getName().getSourceRange().getEnd();
9090             InsertLoc = getLocForEndOfToken(InsertLoc);
9091           }
9092 
9093           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9094             << Name << RemoveRange
9095             << FixItHint::CreateRemoval(RemoveRange)
9096             << FixItHint::CreateInsertion(InsertLoc, "<>");
9097         }
9098       }
9099     } else {
9100       // Check that we can declare a template here.
9101       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9102           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9103         NewFD->setInvalidDecl();
9104 
9105       // All template param lists were matched against the scope specifier:
9106       // this is NOT (an explicit specialization of) a template.
9107       if (TemplateParamLists.size() > 0)
9108         // For source fidelity, store all the template param lists.
9109         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9110     }
9111 
9112     if (Invalid) {
9113       NewFD->setInvalidDecl();
9114       if (FunctionTemplate)
9115         FunctionTemplate->setInvalidDecl();
9116     }
9117 
9118     // C++ [dcl.fct.spec]p5:
9119     //   The virtual specifier shall only be used in declarations of
9120     //   nonstatic class member functions that appear within a
9121     //   member-specification of a class declaration; see 10.3.
9122     //
9123     if (isVirtual && !NewFD->isInvalidDecl()) {
9124       if (!isVirtualOkay) {
9125         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9126              diag::err_virtual_non_function);
9127       } else if (!CurContext->isRecord()) {
9128         // 'virtual' was specified outside of the class.
9129         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9130              diag::err_virtual_out_of_class)
9131           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9132       } else if (NewFD->getDescribedFunctionTemplate()) {
9133         // C++ [temp.mem]p3:
9134         //  A member function template shall not be virtual.
9135         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9136              diag::err_virtual_member_function_template)
9137           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9138       } else {
9139         // Okay: Add virtual to the method.
9140         NewFD->setVirtualAsWritten(true);
9141       }
9142 
9143       if (getLangOpts().CPlusPlus14 &&
9144           NewFD->getReturnType()->isUndeducedType())
9145         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9146     }
9147 
9148     if (getLangOpts().CPlusPlus14 &&
9149         (NewFD->isDependentContext() ||
9150          (isFriend && CurContext->isDependentContext())) &&
9151         NewFD->getReturnType()->isUndeducedType()) {
9152       // If the function template is referenced directly (for instance, as a
9153       // member of the current instantiation), pretend it has a dependent type.
9154       // This is not really justified by the standard, but is the only sane
9155       // thing to do.
9156       // FIXME: For a friend function, we have not marked the function as being
9157       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9158       const FunctionProtoType *FPT =
9159           NewFD->getType()->castAs<FunctionProtoType>();
9160       QualType Result =
9161           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9162       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9163                                              FPT->getExtProtoInfo()));
9164     }
9165 
9166     // C++ [dcl.fct.spec]p3:
9167     //  The inline specifier shall not appear on a block scope function
9168     //  declaration.
9169     if (isInline && !NewFD->isInvalidDecl()) {
9170       if (CurContext->isFunctionOrMethod()) {
9171         // 'inline' is not allowed on block scope function declaration.
9172         Diag(D.getDeclSpec().getInlineSpecLoc(),
9173              diag::err_inline_declaration_block_scope) << Name
9174           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9175       }
9176     }
9177 
9178     // C++ [dcl.fct.spec]p6:
9179     //  The explicit specifier shall be used only in the declaration of a
9180     //  constructor or conversion function within its class definition;
9181     //  see 12.3.1 and 12.3.2.
9182     if (hasExplicit && !NewFD->isInvalidDecl() &&
9183         !isa<CXXDeductionGuideDecl>(NewFD)) {
9184       if (!CurContext->isRecord()) {
9185         // 'explicit' was specified outside of the class.
9186         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9187              diag::err_explicit_out_of_class)
9188             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9189       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9190                  !isa<CXXConversionDecl>(NewFD)) {
9191         // 'explicit' was specified on a function that wasn't a constructor
9192         // or conversion function.
9193         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9194              diag::err_explicit_non_ctor_or_conv_function)
9195             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9196       }
9197     }
9198 
9199     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9200     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9201       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9202       // are implicitly inline.
9203       NewFD->setImplicitlyInline();
9204 
9205       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9206       // be either constructors or to return a literal type. Therefore,
9207       // destructors cannot be declared constexpr.
9208       if (isa<CXXDestructorDecl>(NewFD) &&
9209           (!getLangOpts().CPlusPlus20 ||
9210            ConstexprKind == ConstexprSpecKind::Consteval)) {
9211         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9212             << static_cast<int>(ConstexprKind);
9213         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9214                                     ? ConstexprSpecKind::Unspecified
9215                                     : ConstexprSpecKind::Constexpr);
9216       }
9217       // C++20 [dcl.constexpr]p2: An allocation function, or a
9218       // deallocation function shall not be declared with the consteval
9219       // specifier.
9220       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9221           (NewFD->getOverloadedOperator() == OO_New ||
9222            NewFD->getOverloadedOperator() == OO_Array_New ||
9223            NewFD->getOverloadedOperator() == OO_Delete ||
9224            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9225         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9226              diag::err_invalid_consteval_decl_kind)
9227             << NewFD;
9228         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9229       }
9230     }
9231 
9232     // If __module_private__ was specified, mark the function accordingly.
9233     if (D.getDeclSpec().isModulePrivateSpecified()) {
9234       if (isFunctionTemplateSpecialization) {
9235         SourceLocation ModulePrivateLoc
9236           = D.getDeclSpec().getModulePrivateSpecLoc();
9237         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9238           << 0
9239           << FixItHint::CreateRemoval(ModulePrivateLoc);
9240       } else {
9241         NewFD->setModulePrivate();
9242         if (FunctionTemplate)
9243           FunctionTemplate->setModulePrivate();
9244       }
9245     }
9246 
9247     if (isFriend) {
9248       if (FunctionTemplate) {
9249         FunctionTemplate->setObjectOfFriendDecl();
9250         FunctionTemplate->setAccess(AS_public);
9251       }
9252       NewFD->setObjectOfFriendDecl();
9253       NewFD->setAccess(AS_public);
9254     }
9255 
9256     // If a function is defined as defaulted or deleted, mark it as such now.
9257     // We'll do the relevant checks on defaulted / deleted functions later.
9258     switch (D.getFunctionDefinitionKind()) {
9259     case FunctionDefinitionKind::Declaration:
9260     case FunctionDefinitionKind::Definition:
9261       break;
9262 
9263     case FunctionDefinitionKind::Defaulted:
9264       NewFD->setDefaulted();
9265       break;
9266 
9267     case FunctionDefinitionKind::Deleted:
9268       NewFD->setDeletedAsWritten();
9269       break;
9270     }
9271 
9272     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9273         D.isFunctionDefinition()) {
9274       // C++ [class.mfct]p2:
9275       //   A member function may be defined (8.4) in its class definition, in
9276       //   which case it is an inline member function (7.1.2)
9277       NewFD->setImplicitlyInline();
9278     }
9279 
9280     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9281         !CurContext->isRecord()) {
9282       // C++ [class.static]p1:
9283       //   A data or function member of a class may be declared static
9284       //   in a class definition, in which case it is a static member of
9285       //   the class.
9286 
9287       // Complain about the 'static' specifier if it's on an out-of-line
9288       // member function definition.
9289 
9290       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9291       // member function template declaration and class member template
9292       // declaration (MSVC versions before 2015), warn about this.
9293       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9294            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9295              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9296            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9297            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9298         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9299     }
9300 
9301     // C++11 [except.spec]p15:
9302     //   A deallocation function with no exception-specification is treated
9303     //   as if it were specified with noexcept(true).
9304     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9305     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9306          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9307         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9308       NewFD->setType(Context.getFunctionType(
9309           FPT->getReturnType(), FPT->getParamTypes(),
9310           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9311   }
9312 
9313   // Filter out previous declarations that don't match the scope.
9314   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9315                        D.getCXXScopeSpec().isNotEmpty() ||
9316                        isMemberSpecialization ||
9317                        isFunctionTemplateSpecialization);
9318 
9319   // Handle GNU asm-label extension (encoded as an attribute).
9320   if (Expr *E = (Expr*) D.getAsmLabel()) {
9321     // The parser guarantees this is a string.
9322     StringLiteral *SE = cast<StringLiteral>(E);
9323     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9324                                         /*IsLiteralLabel=*/true,
9325                                         SE->getStrTokenLoc(0)));
9326   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9327     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9328       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9329     if (I != ExtnameUndeclaredIdentifiers.end()) {
9330       if (isDeclExternC(NewFD)) {
9331         NewFD->addAttr(I->second);
9332         ExtnameUndeclaredIdentifiers.erase(I);
9333       } else
9334         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9335             << /*Variable*/0 << NewFD;
9336     }
9337   }
9338 
9339   // Copy the parameter declarations from the declarator D to the function
9340   // declaration NewFD, if they are available.  First scavenge them into Params.
9341   SmallVector<ParmVarDecl*, 16> Params;
9342   unsigned FTIIdx;
9343   if (D.isFunctionDeclarator(FTIIdx)) {
9344     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9345 
9346     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9347     // function that takes no arguments, not a function that takes a
9348     // single void argument.
9349     // We let through "const void" here because Sema::GetTypeForDeclarator
9350     // already checks for that case.
9351     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9352       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9353         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9354         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9355         Param->setDeclContext(NewFD);
9356         Params.push_back(Param);
9357 
9358         if (Param->isInvalidDecl())
9359           NewFD->setInvalidDecl();
9360       }
9361     }
9362 
9363     if (!getLangOpts().CPlusPlus) {
9364       // In C, find all the tag declarations from the prototype and move them
9365       // into the function DeclContext. Remove them from the surrounding tag
9366       // injection context of the function, which is typically but not always
9367       // the TU.
9368       DeclContext *PrototypeTagContext =
9369           getTagInjectionContext(NewFD->getLexicalDeclContext());
9370       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9371         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9372 
9373         // We don't want to reparent enumerators. Look at their parent enum
9374         // instead.
9375         if (!TD) {
9376           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9377             TD = cast<EnumDecl>(ECD->getDeclContext());
9378         }
9379         if (!TD)
9380           continue;
9381         DeclContext *TagDC = TD->getLexicalDeclContext();
9382         if (!TagDC->containsDecl(TD))
9383           continue;
9384         TagDC->removeDecl(TD);
9385         TD->setDeclContext(NewFD);
9386         NewFD->addDecl(TD);
9387 
9388         // Preserve the lexical DeclContext if it is not the surrounding tag
9389         // injection context of the FD. In this example, the semantic context of
9390         // E will be f and the lexical context will be S, while both the
9391         // semantic and lexical contexts of S will be f:
9392         //   void f(struct S { enum E { a } f; } s);
9393         if (TagDC != PrototypeTagContext)
9394           TD->setLexicalDeclContext(TagDC);
9395       }
9396     }
9397   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9398     // When we're declaring a function with a typedef, typeof, etc as in the
9399     // following example, we'll need to synthesize (unnamed)
9400     // parameters for use in the declaration.
9401     //
9402     // @code
9403     // typedef void fn(int);
9404     // fn f;
9405     // @endcode
9406 
9407     // Synthesize a parameter for each argument type.
9408     for (const auto &AI : FT->param_types()) {
9409       ParmVarDecl *Param =
9410           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9411       Param->setScopeInfo(0, Params.size());
9412       Params.push_back(Param);
9413     }
9414   } else {
9415     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9416            "Should not need args for typedef of non-prototype fn");
9417   }
9418 
9419   // Finally, we know we have the right number of parameters, install them.
9420   NewFD->setParams(Params);
9421 
9422   if (D.getDeclSpec().isNoreturnSpecified())
9423     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9424                                            D.getDeclSpec().getNoreturnSpecLoc(),
9425                                            AttributeCommonInfo::AS_Keyword));
9426 
9427   // Functions returning a variably modified type violate C99 6.7.5.2p2
9428   // because all functions have linkage.
9429   if (!NewFD->isInvalidDecl() &&
9430       NewFD->getReturnType()->isVariablyModifiedType()) {
9431     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9432     NewFD->setInvalidDecl();
9433   }
9434 
9435   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9436   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9437       !NewFD->hasAttr<SectionAttr>())
9438     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9439         Context, PragmaClangTextSection.SectionName,
9440         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9441 
9442   // Apply an implicit SectionAttr if #pragma code_seg is active.
9443   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9444       !NewFD->hasAttr<SectionAttr>()) {
9445     NewFD->addAttr(SectionAttr::CreateImplicit(
9446         Context, CodeSegStack.CurrentValue->getString(),
9447         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9448         SectionAttr::Declspec_allocate));
9449     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9450                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9451                          ASTContext::PSF_Read,
9452                      NewFD))
9453       NewFD->dropAttr<SectionAttr>();
9454   }
9455 
9456   // Apply an implicit CodeSegAttr from class declspec or
9457   // apply an implicit SectionAttr from #pragma code_seg if active.
9458   if (!NewFD->hasAttr<CodeSegAttr>()) {
9459     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9460                                                                  D.isFunctionDefinition())) {
9461       NewFD->addAttr(SAttr);
9462     }
9463   }
9464 
9465   // Handle attributes.
9466   ProcessDeclAttributes(S, NewFD, D);
9467 
9468   if (getLangOpts().OpenCL) {
9469     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9470     // type declaration will generate a compilation error.
9471     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9472     if (AddressSpace != LangAS::Default) {
9473       Diag(NewFD->getLocation(),
9474            diag::err_opencl_return_value_with_address_space);
9475       NewFD->setInvalidDecl();
9476     }
9477   }
9478 
9479   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9480     checkDeviceDecl(NewFD, D.getBeginLoc());
9481 
9482   if (!getLangOpts().CPlusPlus) {
9483     // Perform semantic checking on the function declaration.
9484     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9485       CheckMain(NewFD, D.getDeclSpec());
9486 
9487     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9488       CheckMSVCRTEntryPoint(NewFD);
9489 
9490     if (!NewFD->isInvalidDecl())
9491       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9492                                                   isMemberSpecialization));
9493     else if (!Previous.empty())
9494       // Recover gracefully from an invalid redeclaration.
9495       D.setRedeclaration(true);
9496     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9497             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9498            "previous declaration set still overloaded");
9499 
9500     // Diagnose no-prototype function declarations with calling conventions that
9501     // don't support variadic calls. Only do this in C and do it after merging
9502     // possibly prototyped redeclarations.
9503     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9504     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9505       CallingConv CC = FT->getExtInfo().getCC();
9506       if (!supportsVariadicCall(CC)) {
9507         // Windows system headers sometimes accidentally use stdcall without
9508         // (void) parameters, so we relax this to a warning.
9509         int DiagID =
9510             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9511         Diag(NewFD->getLocation(), DiagID)
9512             << FunctionType::getNameForCallConv(CC);
9513       }
9514     }
9515 
9516    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9517        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9518      checkNonTrivialCUnion(NewFD->getReturnType(),
9519                            NewFD->getReturnTypeSourceRange().getBegin(),
9520                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9521   } else {
9522     // C++11 [replacement.functions]p3:
9523     //  The program's definitions shall not be specified as inline.
9524     //
9525     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9526     //
9527     // Suppress the diagnostic if the function is __attribute__((used)), since
9528     // that forces an external definition to be emitted.
9529     if (D.getDeclSpec().isInlineSpecified() &&
9530         NewFD->isReplaceableGlobalAllocationFunction() &&
9531         !NewFD->hasAttr<UsedAttr>())
9532       Diag(D.getDeclSpec().getInlineSpecLoc(),
9533            diag::ext_operator_new_delete_declared_inline)
9534         << NewFD->getDeclName();
9535 
9536     // If the declarator is a template-id, translate the parser's template
9537     // argument list into our AST format.
9538     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9539       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9540       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9541       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9542       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9543                                          TemplateId->NumArgs);
9544       translateTemplateArguments(TemplateArgsPtr,
9545                                  TemplateArgs);
9546 
9547       HasExplicitTemplateArgs = true;
9548 
9549       if (NewFD->isInvalidDecl()) {
9550         HasExplicitTemplateArgs = false;
9551       } else if (FunctionTemplate) {
9552         // Function template with explicit template arguments.
9553         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9554           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9555 
9556         HasExplicitTemplateArgs = false;
9557       } else {
9558         assert((isFunctionTemplateSpecialization ||
9559                 D.getDeclSpec().isFriendSpecified()) &&
9560                "should have a 'template<>' for this decl");
9561         // "friend void foo<>(int);" is an implicit specialization decl.
9562         isFunctionTemplateSpecialization = true;
9563       }
9564     } else if (isFriend && isFunctionTemplateSpecialization) {
9565       // This combination is only possible in a recovery case;  the user
9566       // wrote something like:
9567       //   template <> friend void foo(int);
9568       // which we're recovering from as if the user had written:
9569       //   friend void foo<>(int);
9570       // Go ahead and fake up a template id.
9571       HasExplicitTemplateArgs = true;
9572       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9573       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9574     }
9575 
9576     // We do not add HD attributes to specializations here because
9577     // they may have different constexpr-ness compared to their
9578     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9579     // may end up with different effective targets. Instead, a
9580     // specialization inherits its target attributes from its template
9581     // in the CheckFunctionTemplateSpecialization() call below.
9582     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9583       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9584 
9585     // If it's a friend (and only if it's a friend), it's possible
9586     // that either the specialized function type or the specialized
9587     // template is dependent, and therefore matching will fail.  In
9588     // this case, don't check the specialization yet.
9589     if (isFunctionTemplateSpecialization && isFriend &&
9590         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9591          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9592              TemplateArgs.arguments()))) {
9593       assert(HasExplicitTemplateArgs &&
9594              "friend function specialization without template args");
9595       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9596                                                        Previous))
9597         NewFD->setInvalidDecl();
9598     } else if (isFunctionTemplateSpecialization) {
9599       if (CurContext->isDependentContext() && CurContext->isRecord()
9600           && !isFriend) {
9601         isDependentClassScopeExplicitSpecialization = true;
9602       } else if (!NewFD->isInvalidDecl() &&
9603                  CheckFunctionTemplateSpecialization(
9604                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9605                      Previous))
9606         NewFD->setInvalidDecl();
9607 
9608       // C++ [dcl.stc]p1:
9609       //   A storage-class-specifier shall not be specified in an explicit
9610       //   specialization (14.7.3)
9611       FunctionTemplateSpecializationInfo *Info =
9612           NewFD->getTemplateSpecializationInfo();
9613       if (Info && SC != SC_None) {
9614         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9615           Diag(NewFD->getLocation(),
9616                diag::err_explicit_specialization_inconsistent_storage_class)
9617             << SC
9618             << FixItHint::CreateRemoval(
9619                                       D.getDeclSpec().getStorageClassSpecLoc());
9620 
9621         else
9622           Diag(NewFD->getLocation(),
9623                diag::ext_explicit_specialization_storage_class)
9624             << FixItHint::CreateRemoval(
9625                                       D.getDeclSpec().getStorageClassSpecLoc());
9626       }
9627     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9628       if (CheckMemberSpecialization(NewFD, Previous))
9629           NewFD->setInvalidDecl();
9630     }
9631 
9632     // Perform semantic checking on the function declaration.
9633     if (!isDependentClassScopeExplicitSpecialization) {
9634       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9635         CheckMain(NewFD, D.getDeclSpec());
9636 
9637       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9638         CheckMSVCRTEntryPoint(NewFD);
9639 
9640       if (!NewFD->isInvalidDecl())
9641         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9642                                                     isMemberSpecialization));
9643       else if (!Previous.empty())
9644         // Recover gracefully from an invalid redeclaration.
9645         D.setRedeclaration(true);
9646     }
9647 
9648     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9649             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9650            "previous declaration set still overloaded");
9651 
9652     NamedDecl *PrincipalDecl = (FunctionTemplate
9653                                 ? cast<NamedDecl>(FunctionTemplate)
9654                                 : NewFD);
9655 
9656     if (isFriend && NewFD->getPreviousDecl()) {
9657       AccessSpecifier Access = AS_public;
9658       if (!NewFD->isInvalidDecl())
9659         Access = NewFD->getPreviousDecl()->getAccess();
9660 
9661       NewFD->setAccess(Access);
9662       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9663     }
9664 
9665     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9666         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9667       PrincipalDecl->setNonMemberOperator();
9668 
9669     // If we have a function template, check the template parameter
9670     // list. This will check and merge default template arguments.
9671     if (FunctionTemplate) {
9672       FunctionTemplateDecl *PrevTemplate =
9673                                      FunctionTemplate->getPreviousDecl();
9674       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9675                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9676                                     : nullptr,
9677                             D.getDeclSpec().isFriendSpecified()
9678                               ? (D.isFunctionDefinition()
9679                                    ? TPC_FriendFunctionTemplateDefinition
9680                                    : TPC_FriendFunctionTemplate)
9681                               : (D.getCXXScopeSpec().isSet() &&
9682                                  DC && DC->isRecord() &&
9683                                  DC->isDependentContext())
9684                                   ? TPC_ClassTemplateMember
9685                                   : TPC_FunctionTemplate);
9686     }
9687 
9688     if (NewFD->isInvalidDecl()) {
9689       // Ignore all the rest of this.
9690     } else if (!D.isRedeclaration()) {
9691       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9692                                        AddToScope };
9693       // Fake up an access specifier if it's supposed to be a class member.
9694       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9695         NewFD->setAccess(AS_public);
9696 
9697       // Qualified decls generally require a previous declaration.
9698       if (D.getCXXScopeSpec().isSet()) {
9699         // ...with the major exception of templated-scope or
9700         // dependent-scope friend declarations.
9701 
9702         // TODO: we currently also suppress this check in dependent
9703         // contexts because (1) the parameter depth will be off when
9704         // matching friend templates and (2) we might actually be
9705         // selecting a friend based on a dependent factor.  But there
9706         // are situations where these conditions don't apply and we
9707         // can actually do this check immediately.
9708         //
9709         // Unless the scope is dependent, it's always an error if qualified
9710         // redeclaration lookup found nothing at all. Diagnose that now;
9711         // nothing will diagnose that error later.
9712         if (isFriend &&
9713             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9714              (!Previous.empty() && CurContext->isDependentContext()))) {
9715           // ignore these
9716         } else if (NewFD->isCPUDispatchMultiVersion() ||
9717                    NewFD->isCPUSpecificMultiVersion()) {
9718           // ignore this, we allow the redeclaration behavior here to create new
9719           // versions of the function.
9720         } else {
9721           // The user tried to provide an out-of-line definition for a
9722           // function that is a member of a class or namespace, but there
9723           // was no such member function declared (C++ [class.mfct]p2,
9724           // C++ [namespace.memdef]p2). For example:
9725           //
9726           // class X {
9727           //   void f() const;
9728           // };
9729           //
9730           // void X::f() { } // ill-formed
9731           //
9732           // Complain about this problem, and attempt to suggest close
9733           // matches (e.g., those that differ only in cv-qualifiers and
9734           // whether the parameter types are references).
9735 
9736           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9737                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9738             AddToScope = ExtraArgs.AddToScope;
9739             return Result;
9740           }
9741         }
9742 
9743         // Unqualified local friend declarations are required to resolve
9744         // to something.
9745       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9746         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9747                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9748           AddToScope = ExtraArgs.AddToScope;
9749           return Result;
9750         }
9751       }
9752     } else if (!D.isFunctionDefinition() &&
9753                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9754                !isFriend && !isFunctionTemplateSpecialization &&
9755                !isMemberSpecialization) {
9756       // An out-of-line member function declaration must also be a
9757       // definition (C++ [class.mfct]p2).
9758       // Note that this is not the case for explicit specializations of
9759       // function templates or member functions of class templates, per
9760       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9761       // extension for compatibility with old SWIG code which likes to
9762       // generate them.
9763       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9764         << D.getCXXScopeSpec().getRange();
9765     }
9766   }
9767 
9768   // If this is the first declaration of a library builtin function, add
9769   // attributes as appropriate.
9770   if (!D.isRedeclaration() &&
9771       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9772     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9773       if (unsigned BuiltinID = II->getBuiltinID()) {
9774         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9775           // Validate the type matches unless this builtin is specified as
9776           // matching regardless of its declared type.
9777           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9778             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9779           } else {
9780             ASTContext::GetBuiltinTypeError Error;
9781             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9782             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9783 
9784             if (!Error && !BuiltinType.isNull() &&
9785                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9786                     NewFD->getType(), BuiltinType))
9787               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9788           }
9789         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9790                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9791           // FIXME: We should consider this a builtin only in the std namespace.
9792           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9793         }
9794       }
9795     }
9796   }
9797 
9798   ProcessPragmaWeak(S, NewFD);
9799   checkAttributesAfterMerging(*this, *NewFD);
9800 
9801   AddKnownFunctionAttributes(NewFD);
9802 
9803   if (NewFD->hasAttr<OverloadableAttr>() &&
9804       !NewFD->getType()->getAs<FunctionProtoType>()) {
9805     Diag(NewFD->getLocation(),
9806          diag::err_attribute_overloadable_no_prototype)
9807       << NewFD;
9808 
9809     // Turn this into a variadic function with no parameters.
9810     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9811     FunctionProtoType::ExtProtoInfo EPI(
9812         Context.getDefaultCallingConvention(true, false));
9813     EPI.Variadic = true;
9814     EPI.ExtInfo = FT->getExtInfo();
9815 
9816     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9817     NewFD->setType(R);
9818   }
9819 
9820   // If there's a #pragma GCC visibility in scope, and this isn't a class
9821   // member, set the visibility of this function.
9822   if (!DC->isRecord() && NewFD->isExternallyVisible())
9823     AddPushedVisibilityAttribute(NewFD);
9824 
9825   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9826   // marking the function.
9827   AddCFAuditedAttribute(NewFD);
9828 
9829   // If this is a function definition, check if we have to apply optnone due to
9830   // a pragma.
9831   if(D.isFunctionDefinition())
9832     AddRangeBasedOptnone(NewFD);
9833 
9834   // If this is the first declaration of an extern C variable, update
9835   // the map of such variables.
9836   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9837       isIncompleteDeclExternC(*this, NewFD))
9838     RegisterLocallyScopedExternCDecl(NewFD, S);
9839 
9840   // Set this FunctionDecl's range up to the right paren.
9841   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9842 
9843   if (D.isRedeclaration() && !Previous.empty()) {
9844     NamedDecl *Prev = Previous.getRepresentativeDecl();
9845     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9846                                    isMemberSpecialization ||
9847                                        isFunctionTemplateSpecialization,
9848                                    D.isFunctionDefinition());
9849   }
9850 
9851   if (getLangOpts().CUDA) {
9852     IdentifierInfo *II = NewFD->getIdentifier();
9853     if (II && II->isStr(getCudaConfigureFuncName()) &&
9854         !NewFD->isInvalidDecl() &&
9855         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9856       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9857         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9858             << getCudaConfigureFuncName();
9859       Context.setcudaConfigureCallDecl(NewFD);
9860     }
9861 
9862     // Variadic functions, other than a *declaration* of printf, are not allowed
9863     // in device-side CUDA code, unless someone passed
9864     // -fcuda-allow-variadic-functions.
9865     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9866         (NewFD->hasAttr<CUDADeviceAttr>() ||
9867          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9868         !(II && II->isStr("printf") && NewFD->isExternC() &&
9869           !D.isFunctionDefinition())) {
9870       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9871     }
9872   }
9873 
9874   MarkUnusedFileScopedDecl(NewFD);
9875 
9876 
9877 
9878   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9879     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9880     if ((getLangOpts().OpenCLVersion >= 120)
9881         && (SC == SC_Static)) {
9882       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9883       D.setInvalidType();
9884     }
9885 
9886     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9887     if (!NewFD->getReturnType()->isVoidType()) {
9888       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9889       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9890           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9891                                 : FixItHint());
9892       D.setInvalidType();
9893     }
9894 
9895     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9896     for (auto Param : NewFD->parameters())
9897       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9898 
9899     if (getLangOpts().OpenCLCPlusPlus) {
9900       if (DC->isRecord()) {
9901         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9902         D.setInvalidType();
9903       }
9904       if (FunctionTemplate) {
9905         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9906         D.setInvalidType();
9907       }
9908     }
9909   }
9910 
9911   if (getLangOpts().CPlusPlus) {
9912     if (FunctionTemplate) {
9913       if (NewFD->isInvalidDecl())
9914         FunctionTemplate->setInvalidDecl();
9915       return FunctionTemplate;
9916     }
9917 
9918     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9919       CompleteMemberSpecialization(NewFD, Previous);
9920   }
9921 
9922   for (const ParmVarDecl *Param : NewFD->parameters()) {
9923     QualType PT = Param->getType();
9924 
9925     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9926     // types.
9927     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9928       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9929         QualType ElemTy = PipeTy->getElementType();
9930           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9931             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9932             D.setInvalidType();
9933           }
9934       }
9935     }
9936   }
9937 
9938   // Here we have an function template explicit specialization at class scope.
9939   // The actual specialization will be postponed to template instatiation
9940   // time via the ClassScopeFunctionSpecializationDecl node.
9941   if (isDependentClassScopeExplicitSpecialization) {
9942     ClassScopeFunctionSpecializationDecl *NewSpec =
9943                          ClassScopeFunctionSpecializationDecl::Create(
9944                                 Context, CurContext, NewFD->getLocation(),
9945                                 cast<CXXMethodDecl>(NewFD),
9946                                 HasExplicitTemplateArgs, TemplateArgs);
9947     CurContext->addDecl(NewSpec);
9948     AddToScope = false;
9949   }
9950 
9951   // Diagnose availability attributes. Availability cannot be used on functions
9952   // that are run during load/unload.
9953   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9954     if (NewFD->hasAttr<ConstructorAttr>()) {
9955       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9956           << 1;
9957       NewFD->dropAttr<AvailabilityAttr>();
9958     }
9959     if (NewFD->hasAttr<DestructorAttr>()) {
9960       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9961           << 2;
9962       NewFD->dropAttr<AvailabilityAttr>();
9963     }
9964   }
9965 
9966   // Diagnose no_builtin attribute on function declaration that are not a
9967   // definition.
9968   // FIXME: We should really be doing this in
9969   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9970   // the FunctionDecl and at this point of the code
9971   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9972   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9973   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9974     switch (D.getFunctionDefinitionKind()) {
9975     case FunctionDefinitionKind::Defaulted:
9976     case FunctionDefinitionKind::Deleted:
9977       Diag(NBA->getLocation(),
9978            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9979           << NBA->getSpelling();
9980       break;
9981     case FunctionDefinitionKind::Declaration:
9982       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9983           << NBA->getSpelling();
9984       break;
9985     case FunctionDefinitionKind::Definition:
9986       break;
9987     }
9988 
9989   return NewFD;
9990 }
9991 
9992 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9993 /// when __declspec(code_seg) "is applied to a class, all member functions of
9994 /// the class and nested classes -- this includes compiler-generated special
9995 /// member functions -- are put in the specified segment."
9996 /// The actual behavior is a little more complicated. The Microsoft compiler
9997 /// won't check outer classes if there is an active value from #pragma code_seg.
9998 /// The CodeSeg is always applied from the direct parent but only from outer
9999 /// classes when the #pragma code_seg stack is empty. See:
10000 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10001 /// available since MS has removed the page.
10002 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10003   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10004   if (!Method)
10005     return nullptr;
10006   const CXXRecordDecl *Parent = Method->getParent();
10007   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10008     Attr *NewAttr = SAttr->clone(S.getASTContext());
10009     NewAttr->setImplicit(true);
10010     return NewAttr;
10011   }
10012 
10013   // The Microsoft compiler won't check outer classes for the CodeSeg
10014   // when the #pragma code_seg stack is active.
10015   if (S.CodeSegStack.CurrentValue)
10016    return nullptr;
10017 
10018   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10019     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10020       Attr *NewAttr = SAttr->clone(S.getASTContext());
10021       NewAttr->setImplicit(true);
10022       return NewAttr;
10023     }
10024   }
10025   return nullptr;
10026 }
10027 
10028 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10029 /// containing class. Otherwise it will return implicit SectionAttr if the
10030 /// function is a definition and there is an active value on CodeSegStack
10031 /// (from the current #pragma code-seg value).
10032 ///
10033 /// \param FD Function being declared.
10034 /// \param IsDefinition Whether it is a definition or just a declarartion.
10035 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10036 ///          nullptr if no attribute should be added.
10037 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10038                                                        bool IsDefinition) {
10039   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10040     return A;
10041   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10042       CodeSegStack.CurrentValue)
10043     return SectionAttr::CreateImplicit(
10044         getASTContext(), CodeSegStack.CurrentValue->getString(),
10045         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10046         SectionAttr::Declspec_allocate);
10047   return nullptr;
10048 }
10049 
10050 /// Determines if we can perform a correct type check for \p D as a
10051 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10052 /// best-effort check.
10053 ///
10054 /// \param NewD The new declaration.
10055 /// \param OldD The old declaration.
10056 /// \param NewT The portion of the type of the new declaration to check.
10057 /// \param OldT The portion of the type of the old declaration to check.
10058 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10059                                           QualType NewT, QualType OldT) {
10060   if (!NewD->getLexicalDeclContext()->isDependentContext())
10061     return true;
10062 
10063   // For dependently-typed local extern declarations and friends, we can't
10064   // perform a correct type check in general until instantiation:
10065   //
10066   //   int f();
10067   //   template<typename T> void g() { T f(); }
10068   //
10069   // (valid if g() is only instantiated with T = int).
10070   if (NewT->isDependentType() &&
10071       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10072     return false;
10073 
10074   // Similarly, if the previous declaration was a dependent local extern
10075   // declaration, we don't really know its type yet.
10076   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10077     return false;
10078 
10079   return true;
10080 }
10081 
10082 /// Checks if the new declaration declared in dependent context must be
10083 /// put in the same redeclaration chain as the specified declaration.
10084 ///
10085 /// \param D Declaration that is checked.
10086 /// \param PrevDecl Previous declaration found with proper lookup method for the
10087 ///                 same declaration name.
10088 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10089 ///          belongs to.
10090 ///
10091 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10092   if (!D->getLexicalDeclContext()->isDependentContext())
10093     return true;
10094 
10095   // Don't chain dependent friend function definitions until instantiation, to
10096   // permit cases like
10097   //
10098   //   void func();
10099   //   template<typename T> class C1 { friend void func() {} };
10100   //   template<typename T> class C2 { friend void func() {} };
10101   //
10102   // ... which is valid if only one of C1 and C2 is ever instantiated.
10103   //
10104   // FIXME: This need only apply to function definitions. For now, we proxy
10105   // this by checking for a file-scope function. We do not want this to apply
10106   // to friend declarations nominating member functions, because that gets in
10107   // the way of access checks.
10108   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10109     return false;
10110 
10111   auto *VD = dyn_cast<ValueDecl>(D);
10112   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10113   return !VD || !PrevVD ||
10114          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10115                                         PrevVD->getType());
10116 }
10117 
10118 /// Check the target attribute of the function for MultiVersion
10119 /// validity.
10120 ///
10121 /// Returns true if there was an error, false otherwise.
10122 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10123   const auto *TA = FD->getAttr<TargetAttr>();
10124   assert(TA && "MultiVersion Candidate requires a target attribute");
10125   ParsedTargetAttr ParseInfo = TA->parse();
10126   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10127   enum ErrType { Feature = 0, Architecture = 1 };
10128 
10129   if (!ParseInfo.Architecture.empty() &&
10130       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10131     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10132         << Architecture << ParseInfo.Architecture;
10133     return true;
10134   }
10135 
10136   for (const auto &Feat : ParseInfo.Features) {
10137     auto BareFeat = StringRef{Feat}.substr(1);
10138     if (Feat[0] == '-') {
10139       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10140           << Feature << ("no-" + BareFeat).str();
10141       return true;
10142     }
10143 
10144     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10145         !TargetInfo.isValidFeatureName(BareFeat)) {
10146       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10147           << Feature << BareFeat;
10148       return true;
10149     }
10150   }
10151   return false;
10152 }
10153 
10154 // Provide a white-list of attributes that are allowed to be combined with
10155 // multiversion functions.
10156 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10157                                            MultiVersionKind MVType) {
10158   // Note: this list/diagnosis must match the list in
10159   // checkMultiversionAttributesAllSame.
10160   switch (Kind) {
10161   default:
10162     return false;
10163   case attr::Used:
10164     return MVType == MultiVersionKind::Target;
10165   case attr::NonNull:
10166   case attr::NoThrow:
10167     return true;
10168   }
10169 }
10170 
10171 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10172                                                  const FunctionDecl *FD,
10173                                                  const FunctionDecl *CausedFD,
10174                                                  MultiVersionKind MVType) {
10175   bool IsCPUSpecificCPUDispatchMVType =
10176       MVType == MultiVersionKind::CPUDispatch ||
10177       MVType == MultiVersionKind::CPUSpecific;
10178   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10179                             Sema &S, const Attr *A) {
10180     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10181         << IsCPUSpecificCPUDispatchMVType << A;
10182     if (CausedFD)
10183       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10184     return true;
10185   };
10186 
10187   for (const Attr *A : FD->attrs()) {
10188     switch (A->getKind()) {
10189     case attr::CPUDispatch:
10190     case attr::CPUSpecific:
10191       if (MVType != MultiVersionKind::CPUDispatch &&
10192           MVType != MultiVersionKind::CPUSpecific)
10193         return Diagnose(S, A);
10194       break;
10195     case attr::Target:
10196       if (MVType != MultiVersionKind::Target)
10197         return Diagnose(S, A);
10198       break;
10199     default:
10200       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10201         return Diagnose(S, A);
10202       break;
10203     }
10204   }
10205   return false;
10206 }
10207 
10208 bool Sema::areMultiversionVariantFunctionsCompatible(
10209     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10210     const PartialDiagnostic &NoProtoDiagID,
10211     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10212     const PartialDiagnosticAt &NoSupportDiagIDAt,
10213     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10214     bool ConstexprSupported, bool CLinkageMayDiffer) {
10215   enum DoesntSupport {
10216     FuncTemplates = 0,
10217     VirtFuncs = 1,
10218     DeducedReturn = 2,
10219     Constructors = 3,
10220     Destructors = 4,
10221     DeletedFuncs = 5,
10222     DefaultedFuncs = 6,
10223     ConstexprFuncs = 7,
10224     ConstevalFuncs = 8,
10225   };
10226   enum Different {
10227     CallingConv = 0,
10228     ReturnType = 1,
10229     ConstexprSpec = 2,
10230     InlineSpec = 3,
10231     StorageClass = 4,
10232     Linkage = 5,
10233   };
10234 
10235   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10236       !OldFD->getType()->getAs<FunctionProtoType>()) {
10237     Diag(OldFD->getLocation(), NoProtoDiagID);
10238     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10239     return true;
10240   }
10241 
10242   if (NoProtoDiagID.getDiagID() != 0 &&
10243       !NewFD->getType()->getAs<FunctionProtoType>())
10244     return Diag(NewFD->getLocation(), NoProtoDiagID);
10245 
10246   if (!TemplatesSupported &&
10247       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10248     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10249            << FuncTemplates;
10250 
10251   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10252     if (NewCXXFD->isVirtual())
10253       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10254              << VirtFuncs;
10255 
10256     if (isa<CXXConstructorDecl>(NewCXXFD))
10257       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10258              << Constructors;
10259 
10260     if (isa<CXXDestructorDecl>(NewCXXFD))
10261       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10262              << Destructors;
10263   }
10264 
10265   if (NewFD->isDeleted())
10266     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10267            << DeletedFuncs;
10268 
10269   if (NewFD->isDefaulted())
10270     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10271            << DefaultedFuncs;
10272 
10273   if (!ConstexprSupported && NewFD->isConstexpr())
10274     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10275            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10276 
10277   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10278   const auto *NewType = cast<FunctionType>(NewQType);
10279   QualType NewReturnType = NewType->getReturnType();
10280 
10281   if (NewReturnType->isUndeducedType())
10282     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10283            << DeducedReturn;
10284 
10285   // Ensure the return type is identical.
10286   if (OldFD) {
10287     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10288     const auto *OldType = cast<FunctionType>(OldQType);
10289     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10290     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10291 
10292     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10293       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10294 
10295     QualType OldReturnType = OldType->getReturnType();
10296 
10297     if (OldReturnType != NewReturnType)
10298       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10299 
10300     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10301       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10302 
10303     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10304       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10305 
10306     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10307       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10308 
10309     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10310       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10311 
10312     if (CheckEquivalentExceptionSpec(
10313             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10314             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10315       return true;
10316   }
10317   return false;
10318 }
10319 
10320 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10321                                              const FunctionDecl *NewFD,
10322                                              bool CausesMV,
10323                                              MultiVersionKind MVType) {
10324   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10325     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10326     if (OldFD)
10327       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10328     return true;
10329   }
10330 
10331   bool IsCPUSpecificCPUDispatchMVType =
10332       MVType == MultiVersionKind::CPUDispatch ||
10333       MVType == MultiVersionKind::CPUSpecific;
10334 
10335   if (CausesMV && OldFD &&
10336       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10337     return true;
10338 
10339   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10340     return true;
10341 
10342   // Only allow transition to MultiVersion if it hasn't been used.
10343   if (OldFD && CausesMV && OldFD->isUsed(false))
10344     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10345 
10346   return S.areMultiversionVariantFunctionsCompatible(
10347       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10348       PartialDiagnosticAt(NewFD->getLocation(),
10349                           S.PDiag(diag::note_multiversioning_caused_here)),
10350       PartialDiagnosticAt(NewFD->getLocation(),
10351                           S.PDiag(diag::err_multiversion_doesnt_support)
10352                               << IsCPUSpecificCPUDispatchMVType),
10353       PartialDiagnosticAt(NewFD->getLocation(),
10354                           S.PDiag(diag::err_multiversion_diff)),
10355       /*TemplatesSupported=*/false,
10356       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10357       /*CLinkageMayDiffer=*/false);
10358 }
10359 
10360 /// Check the validity of a multiversion function declaration that is the
10361 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10362 ///
10363 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10364 ///
10365 /// Returns true if there was an error, false otherwise.
10366 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10367                                            MultiVersionKind MVType,
10368                                            const TargetAttr *TA) {
10369   assert(MVType != MultiVersionKind::None &&
10370          "Function lacks multiversion attribute");
10371 
10372   // Target only causes MV if it is default, otherwise this is a normal
10373   // function.
10374   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10375     return false;
10376 
10377   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10378     FD->setInvalidDecl();
10379     return true;
10380   }
10381 
10382   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10383     FD->setInvalidDecl();
10384     return true;
10385   }
10386 
10387   FD->setIsMultiVersion();
10388   return false;
10389 }
10390 
10391 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10392   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10393     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10394       return true;
10395   }
10396 
10397   return false;
10398 }
10399 
10400 static bool CheckTargetCausesMultiVersioning(
10401     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10402     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10403     LookupResult &Previous) {
10404   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10405   ParsedTargetAttr NewParsed = NewTA->parse();
10406   // Sort order doesn't matter, it just needs to be consistent.
10407   llvm::sort(NewParsed.Features);
10408 
10409   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10410   // to change, this is a simple redeclaration.
10411   if (!NewTA->isDefaultVersion() &&
10412       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10413     return false;
10414 
10415   // Otherwise, this decl causes MultiVersioning.
10416   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10417     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10418     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10419     NewFD->setInvalidDecl();
10420     return true;
10421   }
10422 
10423   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10424                                        MultiVersionKind::Target)) {
10425     NewFD->setInvalidDecl();
10426     return true;
10427   }
10428 
10429   if (CheckMultiVersionValue(S, NewFD)) {
10430     NewFD->setInvalidDecl();
10431     return true;
10432   }
10433 
10434   // If this is 'default', permit the forward declaration.
10435   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10436     Redeclaration = true;
10437     OldDecl = OldFD;
10438     OldFD->setIsMultiVersion();
10439     NewFD->setIsMultiVersion();
10440     return false;
10441   }
10442 
10443   if (CheckMultiVersionValue(S, OldFD)) {
10444     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10445     NewFD->setInvalidDecl();
10446     return true;
10447   }
10448 
10449   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10450 
10451   if (OldParsed == NewParsed) {
10452     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10453     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10454     NewFD->setInvalidDecl();
10455     return true;
10456   }
10457 
10458   for (const auto *FD : OldFD->redecls()) {
10459     const auto *CurTA = FD->getAttr<TargetAttr>();
10460     // We allow forward declarations before ANY multiversioning attributes, but
10461     // nothing after the fact.
10462     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10463         (!CurTA || CurTA->isInherited())) {
10464       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10465           << 0;
10466       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10467       NewFD->setInvalidDecl();
10468       return true;
10469     }
10470   }
10471 
10472   OldFD->setIsMultiVersion();
10473   NewFD->setIsMultiVersion();
10474   Redeclaration = false;
10475   MergeTypeWithPrevious = false;
10476   OldDecl = nullptr;
10477   Previous.clear();
10478   return false;
10479 }
10480 
10481 /// Check the validity of a new function declaration being added to an existing
10482 /// multiversioned declaration collection.
10483 static bool CheckMultiVersionAdditionalDecl(
10484     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10485     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10486     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10487     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10488     LookupResult &Previous) {
10489 
10490   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10491   // Disallow mixing of multiversioning types.
10492   if ((OldMVType == MultiVersionKind::Target &&
10493        NewMVType != MultiVersionKind::Target) ||
10494       (NewMVType == MultiVersionKind::Target &&
10495        OldMVType != MultiVersionKind::Target)) {
10496     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10497     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10498     NewFD->setInvalidDecl();
10499     return true;
10500   }
10501 
10502   ParsedTargetAttr NewParsed;
10503   if (NewTA) {
10504     NewParsed = NewTA->parse();
10505     llvm::sort(NewParsed.Features);
10506   }
10507 
10508   bool UseMemberUsingDeclRules =
10509       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10510 
10511   // Next, check ALL non-overloads to see if this is a redeclaration of a
10512   // previous member of the MultiVersion set.
10513   for (NamedDecl *ND : Previous) {
10514     FunctionDecl *CurFD = ND->getAsFunction();
10515     if (!CurFD)
10516       continue;
10517     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10518       continue;
10519 
10520     if (NewMVType == MultiVersionKind::Target) {
10521       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10522       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10523         NewFD->setIsMultiVersion();
10524         Redeclaration = true;
10525         OldDecl = ND;
10526         return false;
10527       }
10528 
10529       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10530       if (CurParsed == NewParsed) {
10531         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10532         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10533         NewFD->setInvalidDecl();
10534         return true;
10535       }
10536     } else {
10537       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10538       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10539       // Handle CPUDispatch/CPUSpecific versions.
10540       // Only 1 CPUDispatch function is allowed, this will make it go through
10541       // the redeclaration errors.
10542       if (NewMVType == MultiVersionKind::CPUDispatch &&
10543           CurFD->hasAttr<CPUDispatchAttr>()) {
10544         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10545             std::equal(
10546                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10547                 NewCPUDisp->cpus_begin(),
10548                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10549                   return Cur->getName() == New->getName();
10550                 })) {
10551           NewFD->setIsMultiVersion();
10552           Redeclaration = true;
10553           OldDecl = ND;
10554           return false;
10555         }
10556 
10557         // If the declarations don't match, this is an error condition.
10558         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10559         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10560         NewFD->setInvalidDecl();
10561         return true;
10562       }
10563       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10564 
10565         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10566             std::equal(
10567                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10568                 NewCPUSpec->cpus_begin(),
10569                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10570                   return Cur->getName() == New->getName();
10571                 })) {
10572           NewFD->setIsMultiVersion();
10573           Redeclaration = true;
10574           OldDecl = ND;
10575           return false;
10576         }
10577 
10578         // Only 1 version of CPUSpecific is allowed for each CPU.
10579         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10580           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10581             if (CurII == NewII) {
10582               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10583                   << NewII;
10584               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10585               NewFD->setInvalidDecl();
10586               return true;
10587             }
10588           }
10589         }
10590       }
10591       // If the two decls aren't the same MVType, there is no possible error
10592       // condition.
10593     }
10594   }
10595 
10596   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10597   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10598   // handled in the attribute adding step.
10599   if (NewMVType == MultiVersionKind::Target &&
10600       CheckMultiVersionValue(S, NewFD)) {
10601     NewFD->setInvalidDecl();
10602     return true;
10603   }
10604 
10605   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10606                                        !OldFD->isMultiVersion(), NewMVType)) {
10607     NewFD->setInvalidDecl();
10608     return true;
10609   }
10610 
10611   // Permit forward declarations in the case where these two are compatible.
10612   if (!OldFD->isMultiVersion()) {
10613     OldFD->setIsMultiVersion();
10614     NewFD->setIsMultiVersion();
10615     Redeclaration = true;
10616     OldDecl = OldFD;
10617     return false;
10618   }
10619 
10620   NewFD->setIsMultiVersion();
10621   Redeclaration = false;
10622   MergeTypeWithPrevious = false;
10623   OldDecl = nullptr;
10624   Previous.clear();
10625   return false;
10626 }
10627 
10628 
10629 /// Check the validity of a mulitversion function declaration.
10630 /// Also sets the multiversion'ness' of the function itself.
10631 ///
10632 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10633 ///
10634 /// Returns true if there was an error, false otherwise.
10635 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10636                                       bool &Redeclaration, NamedDecl *&OldDecl,
10637                                       bool &MergeTypeWithPrevious,
10638                                       LookupResult &Previous) {
10639   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10640   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10641   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10642 
10643   // Mixing Multiversioning types is prohibited.
10644   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10645       (NewCPUDisp && NewCPUSpec)) {
10646     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10647     NewFD->setInvalidDecl();
10648     return true;
10649   }
10650 
10651   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10652 
10653   // Main isn't allowed to become a multiversion function, however it IS
10654   // permitted to have 'main' be marked with the 'target' optimization hint.
10655   if (NewFD->isMain()) {
10656     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10657         MVType == MultiVersionKind::CPUDispatch ||
10658         MVType == MultiVersionKind::CPUSpecific) {
10659       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10660       NewFD->setInvalidDecl();
10661       return true;
10662     }
10663     return false;
10664   }
10665 
10666   if (!OldDecl || !OldDecl->getAsFunction() ||
10667       OldDecl->getDeclContext()->getRedeclContext() !=
10668           NewFD->getDeclContext()->getRedeclContext()) {
10669     // If there's no previous declaration, AND this isn't attempting to cause
10670     // multiversioning, this isn't an error condition.
10671     if (MVType == MultiVersionKind::None)
10672       return false;
10673     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10674   }
10675 
10676   FunctionDecl *OldFD = OldDecl->getAsFunction();
10677 
10678   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10679     return false;
10680 
10681   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10682     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10683         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10684     NewFD->setInvalidDecl();
10685     return true;
10686   }
10687 
10688   // Handle the target potentially causes multiversioning case.
10689   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10690     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10691                                             Redeclaration, OldDecl,
10692                                             MergeTypeWithPrevious, Previous);
10693 
10694   // At this point, we have a multiversion function decl (in OldFD) AND an
10695   // appropriate attribute in the current function decl.  Resolve that these are
10696   // still compatible with previous declarations.
10697   return CheckMultiVersionAdditionalDecl(
10698       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10699       OldDecl, MergeTypeWithPrevious, Previous);
10700 }
10701 
10702 /// Perform semantic checking of a new function declaration.
10703 ///
10704 /// Performs semantic analysis of the new function declaration
10705 /// NewFD. This routine performs all semantic checking that does not
10706 /// require the actual declarator involved in the declaration, and is
10707 /// used both for the declaration of functions as they are parsed
10708 /// (called via ActOnDeclarator) and for the declaration of functions
10709 /// that have been instantiated via C++ template instantiation (called
10710 /// via InstantiateDecl).
10711 ///
10712 /// \param IsMemberSpecialization whether this new function declaration is
10713 /// a member specialization (that replaces any definition provided by the
10714 /// previous declaration).
10715 ///
10716 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10717 ///
10718 /// \returns true if the function declaration is a redeclaration.
10719 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10720                                     LookupResult &Previous,
10721                                     bool IsMemberSpecialization) {
10722   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10723          "Variably modified return types are not handled here");
10724 
10725   // Determine whether the type of this function should be merged with
10726   // a previous visible declaration. This never happens for functions in C++,
10727   // and always happens in C if the previous declaration was visible.
10728   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10729                                !Previous.isShadowed();
10730 
10731   bool Redeclaration = false;
10732   NamedDecl *OldDecl = nullptr;
10733   bool MayNeedOverloadableChecks = false;
10734 
10735   // Merge or overload the declaration with an existing declaration of
10736   // the same name, if appropriate.
10737   if (!Previous.empty()) {
10738     // Determine whether NewFD is an overload of PrevDecl or
10739     // a declaration that requires merging. If it's an overload,
10740     // there's no more work to do here; we'll just add the new
10741     // function to the scope.
10742     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10743       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10744       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10745         Redeclaration = true;
10746         OldDecl = Candidate;
10747       }
10748     } else {
10749       MayNeedOverloadableChecks = true;
10750       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10751                             /*NewIsUsingDecl*/ false)) {
10752       case Ovl_Match:
10753         Redeclaration = true;
10754         break;
10755 
10756       case Ovl_NonFunction:
10757         Redeclaration = true;
10758         break;
10759 
10760       case Ovl_Overload:
10761         Redeclaration = false;
10762         break;
10763       }
10764     }
10765   }
10766 
10767   // Check for a previous extern "C" declaration with this name.
10768   if (!Redeclaration &&
10769       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10770     if (!Previous.empty()) {
10771       // This is an extern "C" declaration with the same name as a previous
10772       // declaration, and thus redeclares that entity...
10773       Redeclaration = true;
10774       OldDecl = Previous.getFoundDecl();
10775       MergeTypeWithPrevious = false;
10776 
10777       // ... except in the presence of __attribute__((overloadable)).
10778       if (OldDecl->hasAttr<OverloadableAttr>() ||
10779           NewFD->hasAttr<OverloadableAttr>()) {
10780         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10781           MayNeedOverloadableChecks = true;
10782           Redeclaration = false;
10783           OldDecl = nullptr;
10784         }
10785       }
10786     }
10787   }
10788 
10789   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10790                                 MergeTypeWithPrevious, Previous))
10791     return Redeclaration;
10792 
10793   // PPC MMA non-pointer types are not allowed as function return types.
10794   if (Context.getTargetInfo().getTriple().isPPC64() &&
10795       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10796     NewFD->setInvalidDecl();
10797   }
10798 
10799   // C++11 [dcl.constexpr]p8:
10800   //   A constexpr specifier for a non-static member function that is not
10801   //   a constructor declares that member function to be const.
10802   //
10803   // This needs to be delayed until we know whether this is an out-of-line
10804   // definition of a static member function.
10805   //
10806   // This rule is not present in C++1y, so we produce a backwards
10807   // compatibility warning whenever it happens in C++11.
10808   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10809   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10810       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10811       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10812     CXXMethodDecl *OldMD = nullptr;
10813     if (OldDecl)
10814       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10815     if (!OldMD || !OldMD->isStatic()) {
10816       const FunctionProtoType *FPT =
10817         MD->getType()->castAs<FunctionProtoType>();
10818       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10819       EPI.TypeQuals.addConst();
10820       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10821                                           FPT->getParamTypes(), EPI));
10822 
10823       // Warn that we did this, if we're not performing template instantiation.
10824       // In that case, we'll have warned already when the template was defined.
10825       if (!inTemplateInstantiation()) {
10826         SourceLocation AddConstLoc;
10827         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10828                 .IgnoreParens().getAs<FunctionTypeLoc>())
10829           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10830 
10831         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10832           << FixItHint::CreateInsertion(AddConstLoc, " const");
10833       }
10834     }
10835   }
10836 
10837   if (Redeclaration) {
10838     // NewFD and OldDecl represent declarations that need to be
10839     // merged.
10840     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10841       NewFD->setInvalidDecl();
10842       return Redeclaration;
10843     }
10844 
10845     Previous.clear();
10846     Previous.addDecl(OldDecl);
10847 
10848     if (FunctionTemplateDecl *OldTemplateDecl =
10849             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10850       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10851       FunctionTemplateDecl *NewTemplateDecl
10852         = NewFD->getDescribedFunctionTemplate();
10853       assert(NewTemplateDecl && "Template/non-template mismatch");
10854 
10855       // The call to MergeFunctionDecl above may have created some state in
10856       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10857       // can add it as a redeclaration.
10858       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10859 
10860       NewFD->setPreviousDeclaration(OldFD);
10861       if (NewFD->isCXXClassMember()) {
10862         NewFD->setAccess(OldTemplateDecl->getAccess());
10863         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10864       }
10865 
10866       // If this is an explicit specialization of a member that is a function
10867       // template, mark it as a member specialization.
10868       if (IsMemberSpecialization &&
10869           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10870         NewTemplateDecl->setMemberSpecialization();
10871         assert(OldTemplateDecl->isMemberSpecialization());
10872         // Explicit specializations of a member template do not inherit deleted
10873         // status from the parent member template that they are specializing.
10874         if (OldFD->isDeleted()) {
10875           // FIXME: This assert will not hold in the presence of modules.
10876           assert(OldFD->getCanonicalDecl() == OldFD);
10877           // FIXME: We need an update record for this AST mutation.
10878           OldFD->setDeletedAsWritten(false);
10879         }
10880       }
10881 
10882     } else {
10883       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10884         auto *OldFD = cast<FunctionDecl>(OldDecl);
10885         // This needs to happen first so that 'inline' propagates.
10886         NewFD->setPreviousDeclaration(OldFD);
10887         if (NewFD->isCXXClassMember())
10888           NewFD->setAccess(OldFD->getAccess());
10889       }
10890     }
10891   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10892              !NewFD->getAttr<OverloadableAttr>()) {
10893     assert((Previous.empty() ||
10894             llvm::any_of(Previous,
10895                          [](const NamedDecl *ND) {
10896                            return ND->hasAttr<OverloadableAttr>();
10897                          })) &&
10898            "Non-redecls shouldn't happen without overloadable present");
10899 
10900     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10901       const auto *FD = dyn_cast<FunctionDecl>(ND);
10902       return FD && !FD->hasAttr<OverloadableAttr>();
10903     });
10904 
10905     if (OtherUnmarkedIter != Previous.end()) {
10906       Diag(NewFD->getLocation(),
10907            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10908       Diag((*OtherUnmarkedIter)->getLocation(),
10909            diag::note_attribute_overloadable_prev_overload)
10910           << false;
10911 
10912       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10913     }
10914   }
10915 
10916   if (LangOpts.OpenMP)
10917     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10918 
10919   // Semantic checking for this function declaration (in isolation).
10920 
10921   if (getLangOpts().CPlusPlus) {
10922     // C++-specific checks.
10923     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10924       CheckConstructor(Constructor);
10925     } else if (CXXDestructorDecl *Destructor =
10926                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10927       CXXRecordDecl *Record = Destructor->getParent();
10928       QualType ClassType = Context.getTypeDeclType(Record);
10929 
10930       // FIXME: Shouldn't we be able to perform this check even when the class
10931       // type is dependent? Both gcc and edg can handle that.
10932       if (!ClassType->isDependentType()) {
10933         DeclarationName Name
10934           = Context.DeclarationNames.getCXXDestructorName(
10935                                         Context.getCanonicalType(ClassType));
10936         if (NewFD->getDeclName() != Name) {
10937           Diag(NewFD->getLocation(), diag::err_destructor_name);
10938           NewFD->setInvalidDecl();
10939           return Redeclaration;
10940         }
10941       }
10942     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10943       if (auto *TD = Guide->getDescribedFunctionTemplate())
10944         CheckDeductionGuideTemplate(TD);
10945 
10946       // A deduction guide is not on the list of entities that can be
10947       // explicitly specialized.
10948       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10949         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10950             << /*explicit specialization*/ 1;
10951     }
10952 
10953     // Find any virtual functions that this function overrides.
10954     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10955       if (!Method->isFunctionTemplateSpecialization() &&
10956           !Method->getDescribedFunctionTemplate() &&
10957           Method->isCanonicalDecl()) {
10958         AddOverriddenMethods(Method->getParent(), Method);
10959       }
10960       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10961         // C++2a [class.virtual]p6
10962         // A virtual method shall not have a requires-clause.
10963         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10964              diag::err_constrained_virtual_method);
10965 
10966       if (Method->isStatic())
10967         checkThisInStaticMemberFunctionType(Method);
10968     }
10969 
10970     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10971       ActOnConversionDeclarator(Conversion);
10972 
10973     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10974     if (NewFD->isOverloadedOperator() &&
10975         CheckOverloadedOperatorDeclaration(NewFD)) {
10976       NewFD->setInvalidDecl();
10977       return Redeclaration;
10978     }
10979 
10980     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10981     if (NewFD->getLiteralIdentifier() &&
10982         CheckLiteralOperatorDeclaration(NewFD)) {
10983       NewFD->setInvalidDecl();
10984       return Redeclaration;
10985     }
10986 
10987     // In C++, check default arguments now that we have merged decls. Unless
10988     // the lexical context is the class, because in this case this is done
10989     // during delayed parsing anyway.
10990     if (!CurContext->isRecord())
10991       CheckCXXDefaultArguments(NewFD);
10992 
10993     // If this function is declared as being extern "C", then check to see if
10994     // the function returns a UDT (class, struct, or union type) that is not C
10995     // compatible, and if it does, warn the user.
10996     // But, issue any diagnostic on the first declaration only.
10997     if (Previous.empty() && NewFD->isExternC()) {
10998       QualType R = NewFD->getReturnType();
10999       if (R->isIncompleteType() && !R->isVoidType())
11000         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11001             << NewFD << R;
11002       else if (!R.isPODType(Context) && !R->isVoidType() &&
11003                !R->isObjCObjectPointerType())
11004         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11005     }
11006 
11007     // C++1z [dcl.fct]p6:
11008     //   [...] whether the function has a non-throwing exception-specification
11009     //   [is] part of the function type
11010     //
11011     // This results in an ABI break between C++14 and C++17 for functions whose
11012     // declared type includes an exception-specification in a parameter or
11013     // return type. (Exception specifications on the function itself are OK in
11014     // most cases, and exception specifications are not permitted in most other
11015     // contexts where they could make it into a mangling.)
11016     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11017       auto HasNoexcept = [&](QualType T) -> bool {
11018         // Strip off declarator chunks that could be between us and a function
11019         // type. We don't need to look far, exception specifications are very
11020         // restricted prior to C++17.
11021         if (auto *RT = T->getAs<ReferenceType>())
11022           T = RT->getPointeeType();
11023         else if (T->isAnyPointerType())
11024           T = T->getPointeeType();
11025         else if (auto *MPT = T->getAs<MemberPointerType>())
11026           T = MPT->getPointeeType();
11027         if (auto *FPT = T->getAs<FunctionProtoType>())
11028           if (FPT->isNothrow())
11029             return true;
11030         return false;
11031       };
11032 
11033       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11034       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11035       for (QualType T : FPT->param_types())
11036         AnyNoexcept |= HasNoexcept(T);
11037       if (AnyNoexcept)
11038         Diag(NewFD->getLocation(),
11039              diag::warn_cxx17_compat_exception_spec_in_signature)
11040             << NewFD;
11041     }
11042 
11043     if (!Redeclaration && LangOpts.CUDA)
11044       checkCUDATargetOverload(NewFD, Previous);
11045   }
11046   return Redeclaration;
11047 }
11048 
11049 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11050   // C++11 [basic.start.main]p3:
11051   //   A program that [...] declares main to be inline, static or
11052   //   constexpr is ill-formed.
11053   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11054   //   appear in a declaration of main.
11055   // static main is not an error under C99, but we should warn about it.
11056   // We accept _Noreturn main as an extension.
11057   if (FD->getStorageClass() == SC_Static)
11058     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11059          ? diag::err_static_main : diag::warn_static_main)
11060       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11061   if (FD->isInlineSpecified())
11062     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11063       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11064   if (DS.isNoreturnSpecified()) {
11065     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11066     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11067     Diag(NoreturnLoc, diag::ext_noreturn_main);
11068     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11069       << FixItHint::CreateRemoval(NoreturnRange);
11070   }
11071   if (FD->isConstexpr()) {
11072     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11073         << FD->isConsteval()
11074         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11075     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11076   }
11077 
11078   if (getLangOpts().OpenCL) {
11079     Diag(FD->getLocation(), diag::err_opencl_no_main)
11080         << FD->hasAttr<OpenCLKernelAttr>();
11081     FD->setInvalidDecl();
11082     return;
11083   }
11084 
11085   QualType T = FD->getType();
11086   assert(T->isFunctionType() && "function decl is not of function type");
11087   const FunctionType* FT = T->castAs<FunctionType>();
11088 
11089   // Set default calling convention for main()
11090   if (FT->getCallConv() != CC_C) {
11091     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11092     FD->setType(QualType(FT, 0));
11093     T = Context.getCanonicalType(FD->getType());
11094   }
11095 
11096   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11097     // In C with GNU extensions we allow main() to have non-integer return
11098     // type, but we should warn about the extension, and we disable the
11099     // implicit-return-zero rule.
11100 
11101     // GCC in C mode accepts qualified 'int'.
11102     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11103       FD->setHasImplicitReturnZero(true);
11104     else {
11105       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11106       SourceRange RTRange = FD->getReturnTypeSourceRange();
11107       if (RTRange.isValid())
11108         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11109             << FixItHint::CreateReplacement(RTRange, "int");
11110     }
11111   } else {
11112     // In C and C++, main magically returns 0 if you fall off the end;
11113     // set the flag which tells us that.
11114     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11115 
11116     // All the standards say that main() should return 'int'.
11117     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11118       FD->setHasImplicitReturnZero(true);
11119     else {
11120       // Otherwise, this is just a flat-out error.
11121       SourceRange RTRange = FD->getReturnTypeSourceRange();
11122       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11123           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11124                                 : FixItHint());
11125       FD->setInvalidDecl(true);
11126     }
11127   }
11128 
11129   // Treat protoless main() as nullary.
11130   if (isa<FunctionNoProtoType>(FT)) return;
11131 
11132   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11133   unsigned nparams = FTP->getNumParams();
11134   assert(FD->getNumParams() == nparams);
11135 
11136   bool HasExtraParameters = (nparams > 3);
11137 
11138   if (FTP->isVariadic()) {
11139     Diag(FD->getLocation(), diag::ext_variadic_main);
11140     // FIXME: if we had information about the location of the ellipsis, we
11141     // could add a FixIt hint to remove it as a parameter.
11142   }
11143 
11144   // Darwin passes an undocumented fourth argument of type char**.  If
11145   // other platforms start sprouting these, the logic below will start
11146   // getting shifty.
11147   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11148     HasExtraParameters = false;
11149 
11150   if (HasExtraParameters) {
11151     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11152     FD->setInvalidDecl(true);
11153     nparams = 3;
11154   }
11155 
11156   // FIXME: a lot of the following diagnostics would be improved
11157   // if we had some location information about types.
11158 
11159   QualType CharPP =
11160     Context.getPointerType(Context.getPointerType(Context.CharTy));
11161   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11162 
11163   for (unsigned i = 0; i < nparams; ++i) {
11164     QualType AT = FTP->getParamType(i);
11165 
11166     bool mismatch = true;
11167 
11168     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11169       mismatch = false;
11170     else if (Expected[i] == CharPP) {
11171       // As an extension, the following forms are okay:
11172       //   char const **
11173       //   char const * const *
11174       //   char * const *
11175 
11176       QualifierCollector qs;
11177       const PointerType* PT;
11178       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11179           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11180           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11181                               Context.CharTy)) {
11182         qs.removeConst();
11183         mismatch = !qs.empty();
11184       }
11185     }
11186 
11187     if (mismatch) {
11188       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11189       // TODO: suggest replacing given type with expected type
11190       FD->setInvalidDecl(true);
11191     }
11192   }
11193 
11194   if (nparams == 1 && !FD->isInvalidDecl()) {
11195     Diag(FD->getLocation(), diag::warn_main_one_arg);
11196   }
11197 
11198   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11199     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11200     FD->setInvalidDecl();
11201   }
11202 }
11203 
11204 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11205 
11206   // Default calling convention for main and wmain is __cdecl
11207   if (FD->getName() == "main" || FD->getName() == "wmain")
11208     return false;
11209 
11210   // Default calling convention for MinGW is __cdecl
11211   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11212   if (T.isWindowsGNUEnvironment())
11213     return false;
11214 
11215   // Default calling convention for WinMain, wWinMain and DllMain
11216   // is __stdcall on 32 bit Windows
11217   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11218     return true;
11219 
11220   return false;
11221 }
11222 
11223 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11224   QualType T = FD->getType();
11225   assert(T->isFunctionType() && "function decl is not of function type");
11226   const FunctionType *FT = T->castAs<FunctionType>();
11227 
11228   // Set an implicit return of 'zero' if the function can return some integral,
11229   // enumeration, pointer or nullptr type.
11230   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11231       FT->getReturnType()->isAnyPointerType() ||
11232       FT->getReturnType()->isNullPtrType())
11233     // DllMain is exempt because a return value of zero means it failed.
11234     if (FD->getName() != "DllMain")
11235       FD->setHasImplicitReturnZero(true);
11236 
11237   // Explicity specified calling conventions are applied to MSVC entry points
11238   if (!hasExplicitCallingConv(T)) {
11239     if (isDefaultStdCall(FD, *this)) {
11240       if (FT->getCallConv() != CC_X86StdCall) {
11241         FT = Context.adjustFunctionType(
11242             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11243         FD->setType(QualType(FT, 0));
11244       }
11245     } else if (FT->getCallConv() != CC_C) {
11246       FT = Context.adjustFunctionType(FT,
11247                                       FT->getExtInfo().withCallingConv(CC_C));
11248       FD->setType(QualType(FT, 0));
11249     }
11250   }
11251 
11252   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11253     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11254     FD->setInvalidDecl();
11255   }
11256 }
11257 
11258 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11259   // FIXME: Need strict checking.  In C89, we need to check for
11260   // any assignment, increment, decrement, function-calls, or
11261   // commas outside of a sizeof.  In C99, it's the same list,
11262   // except that the aforementioned are allowed in unevaluated
11263   // expressions.  Everything else falls under the
11264   // "may accept other forms of constant expressions" exception.
11265   //
11266   // Regular C++ code will not end up here (exceptions: language extensions,
11267   // OpenCL C++ etc), so the constant expression rules there don't matter.
11268   if (Init->isValueDependent()) {
11269     assert(Init->containsErrors() &&
11270            "Dependent code should only occur in error-recovery path.");
11271     return true;
11272   }
11273   const Expr *Culprit;
11274   if (Init->isConstantInitializer(Context, false, &Culprit))
11275     return false;
11276   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11277     << Culprit->getSourceRange();
11278   return true;
11279 }
11280 
11281 namespace {
11282   // Visits an initialization expression to see if OrigDecl is evaluated in
11283   // its own initialization and throws a warning if it does.
11284   class SelfReferenceChecker
11285       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11286     Sema &S;
11287     Decl *OrigDecl;
11288     bool isRecordType;
11289     bool isPODType;
11290     bool isReferenceType;
11291 
11292     bool isInitList;
11293     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11294 
11295   public:
11296     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11297 
11298     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11299                                                     S(S), OrigDecl(OrigDecl) {
11300       isPODType = false;
11301       isRecordType = false;
11302       isReferenceType = false;
11303       isInitList = false;
11304       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11305         isPODType = VD->getType().isPODType(S.Context);
11306         isRecordType = VD->getType()->isRecordType();
11307         isReferenceType = VD->getType()->isReferenceType();
11308       }
11309     }
11310 
11311     // For most expressions, just call the visitor.  For initializer lists,
11312     // track the index of the field being initialized since fields are
11313     // initialized in order allowing use of previously initialized fields.
11314     void CheckExpr(Expr *E) {
11315       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11316       if (!InitList) {
11317         Visit(E);
11318         return;
11319       }
11320 
11321       // Track and increment the index here.
11322       isInitList = true;
11323       InitFieldIndex.push_back(0);
11324       for (auto Child : InitList->children()) {
11325         CheckExpr(cast<Expr>(Child));
11326         ++InitFieldIndex.back();
11327       }
11328       InitFieldIndex.pop_back();
11329     }
11330 
11331     // Returns true if MemberExpr is checked and no further checking is needed.
11332     // Returns false if additional checking is required.
11333     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11334       llvm::SmallVector<FieldDecl*, 4> Fields;
11335       Expr *Base = E;
11336       bool ReferenceField = false;
11337 
11338       // Get the field members used.
11339       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11340         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11341         if (!FD)
11342           return false;
11343         Fields.push_back(FD);
11344         if (FD->getType()->isReferenceType())
11345           ReferenceField = true;
11346         Base = ME->getBase()->IgnoreParenImpCasts();
11347       }
11348 
11349       // Keep checking only if the base Decl is the same.
11350       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11351       if (!DRE || DRE->getDecl() != OrigDecl)
11352         return false;
11353 
11354       // A reference field can be bound to an unininitialized field.
11355       if (CheckReference && !ReferenceField)
11356         return true;
11357 
11358       // Convert FieldDecls to their index number.
11359       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11360       for (const FieldDecl *I : llvm::reverse(Fields))
11361         UsedFieldIndex.push_back(I->getFieldIndex());
11362 
11363       // See if a warning is needed by checking the first difference in index
11364       // numbers.  If field being used has index less than the field being
11365       // initialized, then the use is safe.
11366       for (auto UsedIter = UsedFieldIndex.begin(),
11367                 UsedEnd = UsedFieldIndex.end(),
11368                 OrigIter = InitFieldIndex.begin(),
11369                 OrigEnd = InitFieldIndex.end();
11370            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11371         if (*UsedIter < *OrigIter)
11372           return true;
11373         if (*UsedIter > *OrigIter)
11374           break;
11375       }
11376 
11377       // TODO: Add a different warning which will print the field names.
11378       HandleDeclRefExpr(DRE);
11379       return true;
11380     }
11381 
11382     // For most expressions, the cast is directly above the DeclRefExpr.
11383     // For conditional operators, the cast can be outside the conditional
11384     // operator if both expressions are DeclRefExpr's.
11385     void HandleValue(Expr *E) {
11386       E = E->IgnoreParens();
11387       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11388         HandleDeclRefExpr(DRE);
11389         return;
11390       }
11391 
11392       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11393         Visit(CO->getCond());
11394         HandleValue(CO->getTrueExpr());
11395         HandleValue(CO->getFalseExpr());
11396         return;
11397       }
11398 
11399       if (BinaryConditionalOperator *BCO =
11400               dyn_cast<BinaryConditionalOperator>(E)) {
11401         Visit(BCO->getCond());
11402         HandleValue(BCO->getFalseExpr());
11403         return;
11404       }
11405 
11406       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11407         HandleValue(OVE->getSourceExpr());
11408         return;
11409       }
11410 
11411       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11412         if (BO->getOpcode() == BO_Comma) {
11413           Visit(BO->getLHS());
11414           HandleValue(BO->getRHS());
11415           return;
11416         }
11417       }
11418 
11419       if (isa<MemberExpr>(E)) {
11420         if (isInitList) {
11421           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11422                                       false /*CheckReference*/))
11423             return;
11424         }
11425 
11426         Expr *Base = E->IgnoreParenImpCasts();
11427         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11428           // Check for static member variables and don't warn on them.
11429           if (!isa<FieldDecl>(ME->getMemberDecl()))
11430             return;
11431           Base = ME->getBase()->IgnoreParenImpCasts();
11432         }
11433         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11434           HandleDeclRefExpr(DRE);
11435         return;
11436       }
11437 
11438       Visit(E);
11439     }
11440 
11441     // Reference types not handled in HandleValue are handled here since all
11442     // uses of references are bad, not just r-value uses.
11443     void VisitDeclRefExpr(DeclRefExpr *E) {
11444       if (isReferenceType)
11445         HandleDeclRefExpr(E);
11446     }
11447 
11448     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11449       if (E->getCastKind() == CK_LValueToRValue) {
11450         HandleValue(E->getSubExpr());
11451         return;
11452       }
11453 
11454       Inherited::VisitImplicitCastExpr(E);
11455     }
11456 
11457     void VisitMemberExpr(MemberExpr *E) {
11458       if (isInitList) {
11459         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11460           return;
11461       }
11462 
11463       // Don't warn on arrays since they can be treated as pointers.
11464       if (E->getType()->canDecayToPointerType()) return;
11465 
11466       // Warn when a non-static method call is followed by non-static member
11467       // field accesses, which is followed by a DeclRefExpr.
11468       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11469       bool Warn = (MD && !MD->isStatic());
11470       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11471       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11472         if (!isa<FieldDecl>(ME->getMemberDecl()))
11473           Warn = false;
11474         Base = ME->getBase()->IgnoreParenImpCasts();
11475       }
11476 
11477       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11478         if (Warn)
11479           HandleDeclRefExpr(DRE);
11480         return;
11481       }
11482 
11483       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11484       // Visit that expression.
11485       Visit(Base);
11486     }
11487 
11488     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11489       Expr *Callee = E->getCallee();
11490 
11491       if (isa<UnresolvedLookupExpr>(Callee))
11492         return Inherited::VisitCXXOperatorCallExpr(E);
11493 
11494       Visit(Callee);
11495       for (auto Arg: E->arguments())
11496         HandleValue(Arg->IgnoreParenImpCasts());
11497     }
11498 
11499     void VisitUnaryOperator(UnaryOperator *E) {
11500       // For POD record types, addresses of its own members are well-defined.
11501       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11502           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11503         if (!isPODType)
11504           HandleValue(E->getSubExpr());
11505         return;
11506       }
11507 
11508       if (E->isIncrementDecrementOp()) {
11509         HandleValue(E->getSubExpr());
11510         return;
11511       }
11512 
11513       Inherited::VisitUnaryOperator(E);
11514     }
11515 
11516     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11517 
11518     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11519       if (E->getConstructor()->isCopyConstructor()) {
11520         Expr *ArgExpr = E->getArg(0);
11521         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11522           if (ILE->getNumInits() == 1)
11523             ArgExpr = ILE->getInit(0);
11524         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11525           if (ICE->getCastKind() == CK_NoOp)
11526             ArgExpr = ICE->getSubExpr();
11527         HandleValue(ArgExpr);
11528         return;
11529       }
11530       Inherited::VisitCXXConstructExpr(E);
11531     }
11532 
11533     void VisitCallExpr(CallExpr *E) {
11534       // Treat std::move as a use.
11535       if (E->isCallToStdMove()) {
11536         HandleValue(E->getArg(0));
11537         return;
11538       }
11539 
11540       Inherited::VisitCallExpr(E);
11541     }
11542 
11543     void VisitBinaryOperator(BinaryOperator *E) {
11544       if (E->isCompoundAssignmentOp()) {
11545         HandleValue(E->getLHS());
11546         Visit(E->getRHS());
11547         return;
11548       }
11549 
11550       Inherited::VisitBinaryOperator(E);
11551     }
11552 
11553     // A custom visitor for BinaryConditionalOperator is needed because the
11554     // regular visitor would check the condition and true expression separately
11555     // but both point to the same place giving duplicate diagnostics.
11556     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11557       Visit(E->getCond());
11558       Visit(E->getFalseExpr());
11559     }
11560 
11561     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11562       Decl* ReferenceDecl = DRE->getDecl();
11563       if (OrigDecl != ReferenceDecl) return;
11564       unsigned diag;
11565       if (isReferenceType) {
11566         diag = diag::warn_uninit_self_reference_in_reference_init;
11567       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11568         diag = diag::warn_static_self_reference_in_init;
11569       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11570                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11571                  DRE->getDecl()->getType()->isRecordType()) {
11572         diag = diag::warn_uninit_self_reference_in_init;
11573       } else {
11574         // Local variables will be handled by the CFG analysis.
11575         return;
11576       }
11577 
11578       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11579                             S.PDiag(diag)
11580                                 << DRE->getDecl() << OrigDecl->getLocation()
11581                                 << DRE->getSourceRange());
11582     }
11583   };
11584 
11585   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11586   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11587                                  bool DirectInit) {
11588     // Parameters arguments are occassionially constructed with itself,
11589     // for instance, in recursive functions.  Skip them.
11590     if (isa<ParmVarDecl>(OrigDecl))
11591       return;
11592 
11593     E = E->IgnoreParens();
11594 
11595     // Skip checking T a = a where T is not a record or reference type.
11596     // Doing so is a way to silence uninitialized warnings.
11597     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11598       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11599         if (ICE->getCastKind() == CK_LValueToRValue)
11600           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11601             if (DRE->getDecl() == OrigDecl)
11602               return;
11603 
11604     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11605   }
11606 } // end anonymous namespace
11607 
11608 namespace {
11609   // Simple wrapper to add the name of a variable or (if no variable is
11610   // available) a DeclarationName into a diagnostic.
11611   struct VarDeclOrName {
11612     VarDecl *VDecl;
11613     DeclarationName Name;
11614 
11615     friend const Sema::SemaDiagnosticBuilder &
11616     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11617       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11618     }
11619   };
11620 } // end anonymous namespace
11621 
11622 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11623                                             DeclarationName Name, QualType Type,
11624                                             TypeSourceInfo *TSI,
11625                                             SourceRange Range, bool DirectInit,
11626                                             Expr *Init) {
11627   bool IsInitCapture = !VDecl;
11628   assert((!VDecl || !VDecl->isInitCapture()) &&
11629          "init captures are expected to be deduced prior to initialization");
11630 
11631   VarDeclOrName VN{VDecl, Name};
11632 
11633   DeducedType *Deduced = Type->getContainedDeducedType();
11634   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11635 
11636   // C++11 [dcl.spec.auto]p3
11637   if (!Init) {
11638     assert(VDecl && "no init for init capture deduction?");
11639 
11640     // Except for class argument deduction, and then for an initializing
11641     // declaration only, i.e. no static at class scope or extern.
11642     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11643         VDecl->hasExternalStorage() ||
11644         VDecl->isStaticDataMember()) {
11645       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11646         << VDecl->getDeclName() << Type;
11647       return QualType();
11648     }
11649   }
11650 
11651   ArrayRef<Expr*> DeduceInits;
11652   if (Init)
11653     DeduceInits = Init;
11654 
11655   if (DirectInit) {
11656     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11657       DeduceInits = PL->exprs();
11658   }
11659 
11660   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11661     assert(VDecl && "non-auto type for init capture deduction?");
11662     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11663     InitializationKind Kind = InitializationKind::CreateForInit(
11664         VDecl->getLocation(), DirectInit, Init);
11665     // FIXME: Initialization should not be taking a mutable list of inits.
11666     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11667     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11668                                                        InitsCopy);
11669   }
11670 
11671   if (DirectInit) {
11672     if (auto *IL = dyn_cast<InitListExpr>(Init))
11673       DeduceInits = IL->inits();
11674   }
11675 
11676   // Deduction only works if we have exactly one source expression.
11677   if (DeduceInits.empty()) {
11678     // It isn't possible to write this directly, but it is possible to
11679     // end up in this situation with "auto x(some_pack...);"
11680     Diag(Init->getBeginLoc(), IsInitCapture
11681                                   ? diag::err_init_capture_no_expression
11682                                   : diag::err_auto_var_init_no_expression)
11683         << VN << Type << Range;
11684     return QualType();
11685   }
11686 
11687   if (DeduceInits.size() > 1) {
11688     Diag(DeduceInits[1]->getBeginLoc(),
11689          IsInitCapture ? diag::err_init_capture_multiple_expressions
11690                        : diag::err_auto_var_init_multiple_expressions)
11691         << VN << Type << Range;
11692     return QualType();
11693   }
11694 
11695   Expr *DeduceInit = DeduceInits[0];
11696   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11697     Diag(Init->getBeginLoc(), IsInitCapture
11698                                   ? diag::err_init_capture_paren_braces
11699                                   : diag::err_auto_var_init_paren_braces)
11700         << isa<InitListExpr>(Init) << VN << Type << Range;
11701     return QualType();
11702   }
11703 
11704   // Expressions default to 'id' when we're in a debugger.
11705   bool DefaultedAnyToId = false;
11706   if (getLangOpts().DebuggerCastResultToId &&
11707       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11708     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11709     if (Result.isInvalid()) {
11710       return QualType();
11711     }
11712     Init = Result.get();
11713     DefaultedAnyToId = true;
11714   }
11715 
11716   // C++ [dcl.decomp]p1:
11717   //   If the assignment-expression [...] has array type A and no ref-qualifier
11718   //   is present, e has type cv A
11719   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11720       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11721       DeduceInit->getType()->isConstantArrayType())
11722     return Context.getQualifiedType(DeduceInit->getType(),
11723                                     Type.getQualifiers());
11724 
11725   QualType DeducedType;
11726   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11727     if (!IsInitCapture)
11728       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11729     else if (isa<InitListExpr>(Init))
11730       Diag(Range.getBegin(),
11731            diag::err_init_capture_deduction_failure_from_init_list)
11732           << VN
11733           << (DeduceInit->getType().isNull() ? TSI->getType()
11734                                              : DeduceInit->getType())
11735           << DeduceInit->getSourceRange();
11736     else
11737       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11738           << VN << TSI->getType()
11739           << (DeduceInit->getType().isNull() ? TSI->getType()
11740                                              : DeduceInit->getType())
11741           << DeduceInit->getSourceRange();
11742   }
11743 
11744   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11745   // 'id' instead of a specific object type prevents most of our usual
11746   // checks.
11747   // We only want to warn outside of template instantiations, though:
11748   // inside a template, the 'id' could have come from a parameter.
11749   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11750       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11751     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11752     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11753   }
11754 
11755   return DeducedType;
11756 }
11757 
11758 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11759                                          Expr *Init) {
11760   assert(!Init || !Init->containsErrors());
11761   QualType DeducedType = deduceVarTypeFromInitializer(
11762       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11763       VDecl->getSourceRange(), DirectInit, Init);
11764   if (DeducedType.isNull()) {
11765     VDecl->setInvalidDecl();
11766     return true;
11767   }
11768 
11769   VDecl->setType(DeducedType);
11770   assert(VDecl->isLinkageValid());
11771 
11772   // In ARC, infer lifetime.
11773   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11774     VDecl->setInvalidDecl();
11775 
11776   if (getLangOpts().OpenCL)
11777     deduceOpenCLAddressSpace(VDecl);
11778 
11779   // If this is a redeclaration, check that the type we just deduced matches
11780   // the previously declared type.
11781   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11782     // We never need to merge the type, because we cannot form an incomplete
11783     // array of auto, nor deduce such a type.
11784     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11785   }
11786 
11787   // Check the deduced type is valid for a variable declaration.
11788   CheckVariableDeclarationType(VDecl);
11789   return VDecl->isInvalidDecl();
11790 }
11791 
11792 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11793                                               SourceLocation Loc) {
11794   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11795     Init = EWC->getSubExpr();
11796 
11797   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11798     Init = CE->getSubExpr();
11799 
11800   QualType InitType = Init->getType();
11801   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11802           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11803          "shouldn't be called if type doesn't have a non-trivial C struct");
11804   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11805     for (auto I : ILE->inits()) {
11806       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11807           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11808         continue;
11809       SourceLocation SL = I->getExprLoc();
11810       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11811     }
11812     return;
11813   }
11814 
11815   if (isa<ImplicitValueInitExpr>(Init)) {
11816     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11817       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11818                             NTCUK_Init);
11819   } else {
11820     // Assume all other explicit initializers involving copying some existing
11821     // object.
11822     // TODO: ignore any explicit initializers where we can guarantee
11823     // copy-elision.
11824     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11825       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11826   }
11827 }
11828 
11829 namespace {
11830 
11831 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11832   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11833   // in the source code or implicitly by the compiler if it is in a union
11834   // defined in a system header and has non-trivial ObjC ownership
11835   // qualifications. We don't want those fields to participate in determining
11836   // whether the containing union is non-trivial.
11837   return FD->hasAttr<UnavailableAttr>();
11838 }
11839 
11840 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11841     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11842                                     void> {
11843   using Super =
11844       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11845                                     void>;
11846 
11847   DiagNonTrivalCUnionDefaultInitializeVisitor(
11848       QualType OrigTy, SourceLocation OrigLoc,
11849       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11850       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11851 
11852   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11853                      const FieldDecl *FD, bool InNonTrivialUnion) {
11854     if (const auto *AT = S.Context.getAsArrayType(QT))
11855       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11856                                      InNonTrivialUnion);
11857     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11858   }
11859 
11860   void visitARCStrong(QualType QT, const FieldDecl *FD,
11861                       bool InNonTrivialUnion) {
11862     if (InNonTrivialUnion)
11863       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11864           << 1 << 0 << QT << FD->getName();
11865   }
11866 
11867   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11868     if (InNonTrivialUnion)
11869       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11870           << 1 << 0 << QT << FD->getName();
11871   }
11872 
11873   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11874     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11875     if (RD->isUnion()) {
11876       if (OrigLoc.isValid()) {
11877         bool IsUnion = false;
11878         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11879           IsUnion = OrigRD->isUnion();
11880         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11881             << 0 << OrigTy << IsUnion << UseContext;
11882         // Reset OrigLoc so that this diagnostic is emitted only once.
11883         OrigLoc = SourceLocation();
11884       }
11885       InNonTrivialUnion = true;
11886     }
11887 
11888     if (InNonTrivialUnion)
11889       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11890           << 0 << 0 << QT.getUnqualifiedType() << "";
11891 
11892     for (const FieldDecl *FD : RD->fields())
11893       if (!shouldIgnoreForRecordTriviality(FD))
11894         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11895   }
11896 
11897   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11898 
11899   // The non-trivial C union type or the struct/union type that contains a
11900   // non-trivial C union.
11901   QualType OrigTy;
11902   SourceLocation OrigLoc;
11903   Sema::NonTrivialCUnionContext UseContext;
11904   Sema &S;
11905 };
11906 
11907 struct DiagNonTrivalCUnionDestructedTypeVisitor
11908     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11909   using Super =
11910       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11911 
11912   DiagNonTrivalCUnionDestructedTypeVisitor(
11913       QualType OrigTy, SourceLocation OrigLoc,
11914       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11915       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11916 
11917   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11918                      const FieldDecl *FD, bool InNonTrivialUnion) {
11919     if (const auto *AT = S.Context.getAsArrayType(QT))
11920       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11921                                      InNonTrivialUnion);
11922     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11923   }
11924 
11925   void visitARCStrong(QualType QT, const FieldDecl *FD,
11926                       bool InNonTrivialUnion) {
11927     if (InNonTrivialUnion)
11928       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11929           << 1 << 1 << QT << FD->getName();
11930   }
11931 
11932   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11933     if (InNonTrivialUnion)
11934       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11935           << 1 << 1 << QT << FD->getName();
11936   }
11937 
11938   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11939     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11940     if (RD->isUnion()) {
11941       if (OrigLoc.isValid()) {
11942         bool IsUnion = false;
11943         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11944           IsUnion = OrigRD->isUnion();
11945         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11946             << 1 << OrigTy << IsUnion << UseContext;
11947         // Reset OrigLoc so that this diagnostic is emitted only once.
11948         OrigLoc = SourceLocation();
11949       }
11950       InNonTrivialUnion = true;
11951     }
11952 
11953     if (InNonTrivialUnion)
11954       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11955           << 0 << 1 << QT.getUnqualifiedType() << "";
11956 
11957     for (const FieldDecl *FD : RD->fields())
11958       if (!shouldIgnoreForRecordTriviality(FD))
11959         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11960   }
11961 
11962   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11963   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11964                           bool InNonTrivialUnion) {}
11965 
11966   // The non-trivial C union type or the struct/union type that contains a
11967   // non-trivial C union.
11968   QualType OrigTy;
11969   SourceLocation OrigLoc;
11970   Sema::NonTrivialCUnionContext UseContext;
11971   Sema &S;
11972 };
11973 
11974 struct DiagNonTrivalCUnionCopyVisitor
11975     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11976   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11977 
11978   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11979                                  Sema::NonTrivialCUnionContext UseContext,
11980                                  Sema &S)
11981       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11982 
11983   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11984                      const FieldDecl *FD, bool InNonTrivialUnion) {
11985     if (const auto *AT = S.Context.getAsArrayType(QT))
11986       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11987                                      InNonTrivialUnion);
11988     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11989   }
11990 
11991   void visitARCStrong(QualType QT, const FieldDecl *FD,
11992                       bool InNonTrivialUnion) {
11993     if (InNonTrivialUnion)
11994       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11995           << 1 << 2 << QT << FD->getName();
11996   }
11997 
11998   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11999     if (InNonTrivialUnion)
12000       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12001           << 1 << 2 << QT << FD->getName();
12002   }
12003 
12004   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12005     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12006     if (RD->isUnion()) {
12007       if (OrigLoc.isValid()) {
12008         bool IsUnion = false;
12009         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12010           IsUnion = OrigRD->isUnion();
12011         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12012             << 2 << OrigTy << IsUnion << UseContext;
12013         // Reset OrigLoc so that this diagnostic is emitted only once.
12014         OrigLoc = SourceLocation();
12015       }
12016       InNonTrivialUnion = true;
12017     }
12018 
12019     if (InNonTrivialUnion)
12020       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12021           << 0 << 2 << QT.getUnqualifiedType() << "";
12022 
12023     for (const FieldDecl *FD : RD->fields())
12024       if (!shouldIgnoreForRecordTriviality(FD))
12025         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12026   }
12027 
12028   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12029                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12030   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12031   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12032                             bool InNonTrivialUnion) {}
12033 
12034   // The non-trivial C union type or the struct/union type that contains a
12035   // non-trivial C union.
12036   QualType OrigTy;
12037   SourceLocation OrigLoc;
12038   Sema::NonTrivialCUnionContext UseContext;
12039   Sema &S;
12040 };
12041 
12042 } // namespace
12043 
12044 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12045                                  NonTrivialCUnionContext UseContext,
12046                                  unsigned NonTrivialKind) {
12047   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12048           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12049           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12050          "shouldn't be called if type doesn't have a non-trivial C union");
12051 
12052   if ((NonTrivialKind & NTCUK_Init) &&
12053       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12054     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12055         .visit(QT, nullptr, false);
12056   if ((NonTrivialKind & NTCUK_Destruct) &&
12057       QT.hasNonTrivialToPrimitiveDestructCUnion())
12058     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12059         .visit(QT, nullptr, false);
12060   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12061     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12062         .visit(QT, nullptr, false);
12063 }
12064 
12065 /// AddInitializerToDecl - Adds the initializer Init to the
12066 /// declaration dcl. If DirectInit is true, this is C++ direct
12067 /// initialization rather than copy initialization.
12068 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12069   // If there is no declaration, there was an error parsing it.  Just ignore
12070   // the initializer.
12071   if (!RealDecl || RealDecl->isInvalidDecl()) {
12072     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12073     return;
12074   }
12075 
12076   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12077     // Pure-specifiers are handled in ActOnPureSpecifier.
12078     Diag(Method->getLocation(), diag::err_member_function_initialization)
12079       << Method->getDeclName() << Init->getSourceRange();
12080     Method->setInvalidDecl();
12081     return;
12082   }
12083 
12084   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12085   if (!VDecl) {
12086     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12087     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12088     RealDecl->setInvalidDecl();
12089     return;
12090   }
12091 
12092   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12093   if (VDecl->getType()->isUndeducedType()) {
12094     // Attempt typo correction early so that the type of the init expression can
12095     // be deduced based on the chosen correction if the original init contains a
12096     // TypoExpr.
12097     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12098     if (!Res.isUsable()) {
12099       // There are unresolved typos in Init, just drop them.
12100       // FIXME: improve the recovery strategy to preserve the Init.
12101       RealDecl->setInvalidDecl();
12102       return;
12103     }
12104     if (Res.get()->containsErrors()) {
12105       // Invalidate the decl as we don't know the type for recovery-expr yet.
12106       RealDecl->setInvalidDecl();
12107       VDecl->setInit(Res.get());
12108       return;
12109     }
12110     Init = Res.get();
12111 
12112     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12113       return;
12114   }
12115 
12116   // dllimport cannot be used on variable definitions.
12117   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12118     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12119     VDecl->setInvalidDecl();
12120     return;
12121   }
12122 
12123   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12124     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12125     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12126     VDecl->setInvalidDecl();
12127     return;
12128   }
12129 
12130   if (!VDecl->getType()->isDependentType()) {
12131     // A definition must end up with a complete type, which means it must be
12132     // complete with the restriction that an array type might be completed by
12133     // the initializer; note that later code assumes this restriction.
12134     QualType BaseDeclType = VDecl->getType();
12135     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12136       BaseDeclType = Array->getElementType();
12137     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12138                             diag::err_typecheck_decl_incomplete_type)) {
12139       RealDecl->setInvalidDecl();
12140       return;
12141     }
12142 
12143     // The variable can not have an abstract class type.
12144     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12145                                diag::err_abstract_type_in_decl,
12146                                AbstractVariableType))
12147       VDecl->setInvalidDecl();
12148   }
12149 
12150   // If adding the initializer will turn this declaration into a definition,
12151   // and we already have a definition for this variable, diagnose or otherwise
12152   // handle the situation.
12153   VarDecl *Def;
12154   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12155       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12156       !VDecl->isThisDeclarationADemotedDefinition() &&
12157       checkVarDeclRedefinition(Def, VDecl))
12158     return;
12159 
12160   if (getLangOpts().CPlusPlus) {
12161     // C++ [class.static.data]p4
12162     //   If a static data member is of const integral or const
12163     //   enumeration type, its declaration in the class definition can
12164     //   specify a constant-initializer which shall be an integral
12165     //   constant expression (5.19). In that case, the member can appear
12166     //   in integral constant expressions. The member shall still be
12167     //   defined in a namespace scope if it is used in the program and the
12168     //   namespace scope definition shall not contain an initializer.
12169     //
12170     // We already performed a redefinition check above, but for static
12171     // data members we also need to check whether there was an in-class
12172     // declaration with an initializer.
12173     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12174       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12175           << VDecl->getDeclName();
12176       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12177            diag::note_previous_initializer)
12178           << 0;
12179       return;
12180     }
12181 
12182     if (VDecl->hasLocalStorage())
12183       setFunctionHasBranchProtectedScope();
12184 
12185     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12186       VDecl->setInvalidDecl();
12187       return;
12188     }
12189   }
12190 
12191   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12192   // a kernel function cannot be initialized."
12193   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12194     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12195     VDecl->setInvalidDecl();
12196     return;
12197   }
12198 
12199   // The LoaderUninitialized attribute acts as a definition (of undef).
12200   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12201     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12202     VDecl->setInvalidDecl();
12203     return;
12204   }
12205 
12206   // Get the decls type and save a reference for later, since
12207   // CheckInitializerTypes may change it.
12208   QualType DclT = VDecl->getType(), SavT = DclT;
12209 
12210   // Expressions default to 'id' when we're in a debugger
12211   // and we are assigning it to a variable of Objective-C pointer type.
12212   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12213       Init->getType() == Context.UnknownAnyTy) {
12214     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12215     if (Result.isInvalid()) {
12216       VDecl->setInvalidDecl();
12217       return;
12218     }
12219     Init = Result.get();
12220   }
12221 
12222   // Perform the initialization.
12223   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12224   if (!VDecl->isInvalidDecl()) {
12225     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12226     InitializationKind Kind = InitializationKind::CreateForInit(
12227         VDecl->getLocation(), DirectInit, Init);
12228 
12229     MultiExprArg Args = Init;
12230     if (CXXDirectInit)
12231       Args = MultiExprArg(CXXDirectInit->getExprs(),
12232                           CXXDirectInit->getNumExprs());
12233 
12234     // Try to correct any TypoExprs in the initialization arguments.
12235     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12236       ExprResult Res = CorrectDelayedTyposInExpr(
12237           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12238           [this, Entity, Kind](Expr *E) {
12239             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12240             return Init.Failed() ? ExprError() : E;
12241           });
12242       if (Res.isInvalid()) {
12243         VDecl->setInvalidDecl();
12244       } else if (Res.get() != Args[Idx]) {
12245         Args[Idx] = Res.get();
12246       }
12247     }
12248     if (VDecl->isInvalidDecl())
12249       return;
12250 
12251     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12252                                    /*TopLevelOfInitList=*/false,
12253                                    /*TreatUnavailableAsInvalid=*/false);
12254     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12255     if (Result.isInvalid()) {
12256       // If the provied initializer fails to initialize the var decl,
12257       // we attach a recovery expr for better recovery.
12258       auto RecoveryExpr =
12259           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12260       if (RecoveryExpr.get())
12261         VDecl->setInit(RecoveryExpr.get());
12262       return;
12263     }
12264 
12265     Init = Result.getAs<Expr>();
12266   }
12267 
12268   // Check for self-references within variable initializers.
12269   // Variables declared within a function/method body (except for references)
12270   // are handled by a dataflow analysis.
12271   // This is undefined behavior in C++, but valid in C.
12272   if (getLangOpts().CPlusPlus) {
12273     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12274         VDecl->getType()->isReferenceType()) {
12275       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12276     }
12277   }
12278 
12279   // If the type changed, it means we had an incomplete type that was
12280   // completed by the initializer. For example:
12281   //   int ary[] = { 1, 3, 5 };
12282   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12283   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12284     VDecl->setType(DclT);
12285 
12286   if (!VDecl->isInvalidDecl()) {
12287     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12288 
12289     if (VDecl->hasAttr<BlocksAttr>())
12290       checkRetainCycles(VDecl, Init);
12291 
12292     // It is safe to assign a weak reference into a strong variable.
12293     // Although this code can still have problems:
12294     //   id x = self.weakProp;
12295     //   id y = self.weakProp;
12296     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12297     // paths through the function. This should be revisited if
12298     // -Wrepeated-use-of-weak is made flow-sensitive.
12299     if (FunctionScopeInfo *FSI = getCurFunction())
12300       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12301            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12302           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12303                            Init->getBeginLoc()))
12304         FSI->markSafeWeakUse(Init);
12305   }
12306 
12307   // The initialization is usually a full-expression.
12308   //
12309   // FIXME: If this is a braced initialization of an aggregate, it is not
12310   // an expression, and each individual field initializer is a separate
12311   // full-expression. For instance, in:
12312   //
12313   //   struct Temp { ~Temp(); };
12314   //   struct S { S(Temp); };
12315   //   struct T { S a, b; } t = { Temp(), Temp() }
12316   //
12317   // we should destroy the first Temp before constructing the second.
12318   ExprResult Result =
12319       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12320                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12321   if (Result.isInvalid()) {
12322     VDecl->setInvalidDecl();
12323     return;
12324   }
12325   Init = Result.get();
12326 
12327   // Attach the initializer to the decl.
12328   VDecl->setInit(Init);
12329 
12330   if (VDecl->isLocalVarDecl()) {
12331     // Don't check the initializer if the declaration is malformed.
12332     if (VDecl->isInvalidDecl()) {
12333       // do nothing
12334 
12335     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12336     // This is true even in C++ for OpenCL.
12337     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12338       CheckForConstantInitializer(Init, DclT);
12339 
12340     // Otherwise, C++ does not restrict the initializer.
12341     } else if (getLangOpts().CPlusPlus) {
12342       // do nothing
12343 
12344     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12345     // static storage duration shall be constant expressions or string literals.
12346     } else if (VDecl->getStorageClass() == SC_Static) {
12347       CheckForConstantInitializer(Init, DclT);
12348 
12349     // C89 is stricter than C99 for aggregate initializers.
12350     // C89 6.5.7p3: All the expressions [...] in an initializer list
12351     // for an object that has aggregate or union type shall be
12352     // constant expressions.
12353     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12354                isa<InitListExpr>(Init)) {
12355       const Expr *Culprit;
12356       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12357         Diag(Culprit->getExprLoc(),
12358              diag::ext_aggregate_init_not_constant)
12359           << Culprit->getSourceRange();
12360       }
12361     }
12362 
12363     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12364       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12365         if (VDecl->hasLocalStorage())
12366           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12367   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12368              VDecl->getLexicalDeclContext()->isRecord()) {
12369     // This is an in-class initialization for a static data member, e.g.,
12370     //
12371     // struct S {
12372     //   static const int value = 17;
12373     // };
12374 
12375     // C++ [class.mem]p4:
12376     //   A member-declarator can contain a constant-initializer only
12377     //   if it declares a static member (9.4) of const integral or
12378     //   const enumeration type, see 9.4.2.
12379     //
12380     // C++11 [class.static.data]p3:
12381     //   If a non-volatile non-inline const static data member is of integral
12382     //   or enumeration type, its declaration in the class definition can
12383     //   specify a brace-or-equal-initializer in which every initializer-clause
12384     //   that is an assignment-expression is a constant expression. A static
12385     //   data member of literal type can be declared in the class definition
12386     //   with the constexpr specifier; if so, its declaration shall specify a
12387     //   brace-or-equal-initializer in which every initializer-clause that is
12388     //   an assignment-expression is a constant expression.
12389 
12390     // Do nothing on dependent types.
12391     if (DclT->isDependentType()) {
12392 
12393     // Allow any 'static constexpr' members, whether or not they are of literal
12394     // type. We separately check that every constexpr variable is of literal
12395     // type.
12396     } else if (VDecl->isConstexpr()) {
12397 
12398     // Require constness.
12399     } else if (!DclT.isConstQualified()) {
12400       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12401         << Init->getSourceRange();
12402       VDecl->setInvalidDecl();
12403 
12404     // We allow integer constant expressions in all cases.
12405     } else if (DclT->isIntegralOrEnumerationType()) {
12406       // Check whether the expression is a constant expression.
12407       SourceLocation Loc;
12408       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12409         // In C++11, a non-constexpr const static data member with an
12410         // in-class initializer cannot be volatile.
12411         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12412       else if (Init->isValueDependent())
12413         ; // Nothing to check.
12414       else if (Init->isIntegerConstantExpr(Context, &Loc))
12415         ; // Ok, it's an ICE!
12416       else if (Init->getType()->isScopedEnumeralType() &&
12417                Init->isCXX11ConstantExpr(Context))
12418         ; // Ok, it is a scoped-enum constant expression.
12419       else if (Init->isEvaluatable(Context)) {
12420         // If we can constant fold the initializer through heroics, accept it,
12421         // but report this as a use of an extension for -pedantic.
12422         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12423           << Init->getSourceRange();
12424       } else {
12425         // Otherwise, this is some crazy unknown case.  Report the issue at the
12426         // location provided by the isIntegerConstantExpr failed check.
12427         Diag(Loc, diag::err_in_class_initializer_non_constant)
12428           << Init->getSourceRange();
12429         VDecl->setInvalidDecl();
12430       }
12431 
12432     // We allow foldable floating-point constants as an extension.
12433     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12434       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12435       // it anyway and provide a fixit to add the 'constexpr'.
12436       if (getLangOpts().CPlusPlus11) {
12437         Diag(VDecl->getLocation(),
12438              diag::ext_in_class_initializer_float_type_cxx11)
12439             << DclT << Init->getSourceRange();
12440         Diag(VDecl->getBeginLoc(),
12441              diag::note_in_class_initializer_float_type_cxx11)
12442             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12443       } else {
12444         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12445           << DclT << Init->getSourceRange();
12446 
12447         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12448           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12449             << Init->getSourceRange();
12450           VDecl->setInvalidDecl();
12451         }
12452       }
12453 
12454     // Suggest adding 'constexpr' in C++11 for literal types.
12455     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12456       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12457           << DclT << Init->getSourceRange()
12458           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12459       VDecl->setConstexpr(true);
12460 
12461     } else {
12462       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12463         << DclT << Init->getSourceRange();
12464       VDecl->setInvalidDecl();
12465     }
12466   } else if (VDecl->isFileVarDecl()) {
12467     // In C, extern is typically used to avoid tentative definitions when
12468     // declaring variables in headers, but adding an intializer makes it a
12469     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12470     // In C++, extern is often used to give implictly static const variables
12471     // external linkage, so don't warn in that case. If selectany is present,
12472     // this might be header code intended for C and C++ inclusion, so apply the
12473     // C++ rules.
12474     if (VDecl->getStorageClass() == SC_Extern &&
12475         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12476          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12477         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12478         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12479       Diag(VDecl->getLocation(), diag::warn_extern_init);
12480 
12481     // In Microsoft C++ mode, a const variable defined in namespace scope has
12482     // external linkage by default if the variable is declared with
12483     // __declspec(dllexport).
12484     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12485         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12486         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12487       VDecl->setStorageClass(SC_Extern);
12488 
12489     // C99 6.7.8p4. All file scoped initializers need to be constant.
12490     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12491       CheckForConstantInitializer(Init, DclT);
12492   }
12493 
12494   QualType InitType = Init->getType();
12495   if (!InitType.isNull() &&
12496       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12497        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12498     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12499 
12500   // We will represent direct-initialization similarly to copy-initialization:
12501   //    int x(1);  -as-> int x = 1;
12502   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12503   //
12504   // Clients that want to distinguish between the two forms, can check for
12505   // direct initializer using VarDecl::getInitStyle().
12506   // A major benefit is that clients that don't particularly care about which
12507   // exactly form was it (like the CodeGen) can handle both cases without
12508   // special case code.
12509 
12510   // C++ 8.5p11:
12511   // The form of initialization (using parentheses or '=') is generally
12512   // insignificant, but does matter when the entity being initialized has a
12513   // class type.
12514   if (CXXDirectInit) {
12515     assert(DirectInit && "Call-style initializer must be direct init.");
12516     VDecl->setInitStyle(VarDecl::CallInit);
12517   } else if (DirectInit) {
12518     // This must be list-initialization. No other way is direct-initialization.
12519     VDecl->setInitStyle(VarDecl::ListInit);
12520   }
12521 
12522   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12523     DeclsToCheckForDeferredDiags.push_back(VDecl);
12524   CheckCompleteVariableDeclaration(VDecl);
12525 }
12526 
12527 /// ActOnInitializerError - Given that there was an error parsing an
12528 /// initializer for the given declaration, try to return to some form
12529 /// of sanity.
12530 void Sema::ActOnInitializerError(Decl *D) {
12531   // Our main concern here is re-establishing invariants like "a
12532   // variable's type is either dependent or complete".
12533   if (!D || D->isInvalidDecl()) return;
12534 
12535   VarDecl *VD = dyn_cast<VarDecl>(D);
12536   if (!VD) return;
12537 
12538   // Bindings are not usable if we can't make sense of the initializer.
12539   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12540     for (auto *BD : DD->bindings())
12541       BD->setInvalidDecl();
12542 
12543   // Auto types are meaningless if we can't make sense of the initializer.
12544   if (VD->getType()->isUndeducedType()) {
12545     D->setInvalidDecl();
12546     return;
12547   }
12548 
12549   QualType Ty = VD->getType();
12550   if (Ty->isDependentType()) return;
12551 
12552   // Require a complete type.
12553   if (RequireCompleteType(VD->getLocation(),
12554                           Context.getBaseElementType(Ty),
12555                           diag::err_typecheck_decl_incomplete_type)) {
12556     VD->setInvalidDecl();
12557     return;
12558   }
12559 
12560   // Require a non-abstract type.
12561   if (RequireNonAbstractType(VD->getLocation(), Ty,
12562                              diag::err_abstract_type_in_decl,
12563                              AbstractVariableType)) {
12564     VD->setInvalidDecl();
12565     return;
12566   }
12567 
12568   // Don't bother complaining about constructors or destructors,
12569   // though.
12570 }
12571 
12572 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12573   // If there is no declaration, there was an error parsing it. Just ignore it.
12574   if (!RealDecl)
12575     return;
12576 
12577   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12578     QualType Type = Var->getType();
12579 
12580     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12581     if (isa<DecompositionDecl>(RealDecl)) {
12582       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12583       Var->setInvalidDecl();
12584       return;
12585     }
12586 
12587     if (Type->isUndeducedType() &&
12588         DeduceVariableDeclarationType(Var, false, nullptr))
12589       return;
12590 
12591     // C++11 [class.static.data]p3: A static data member can be declared with
12592     // the constexpr specifier; if so, its declaration shall specify
12593     // a brace-or-equal-initializer.
12594     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12595     // the definition of a variable [...] or the declaration of a static data
12596     // member.
12597     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12598         !Var->isThisDeclarationADemotedDefinition()) {
12599       if (Var->isStaticDataMember()) {
12600         // C++1z removes the relevant rule; the in-class declaration is always
12601         // a definition there.
12602         if (!getLangOpts().CPlusPlus17 &&
12603             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12604           Diag(Var->getLocation(),
12605                diag::err_constexpr_static_mem_var_requires_init)
12606               << Var;
12607           Var->setInvalidDecl();
12608           return;
12609         }
12610       } else {
12611         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12612         Var->setInvalidDecl();
12613         return;
12614       }
12615     }
12616 
12617     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12618     // be initialized.
12619     if (!Var->isInvalidDecl() &&
12620         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12621         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12622       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12623       Var->setInvalidDecl();
12624       return;
12625     }
12626 
12627     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12628       if (Var->getStorageClass() == SC_Extern) {
12629         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12630             << Var;
12631         Var->setInvalidDecl();
12632         return;
12633       }
12634       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12635                               diag::err_typecheck_decl_incomplete_type)) {
12636         Var->setInvalidDecl();
12637         return;
12638       }
12639       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12640         if (!RD->hasTrivialDefaultConstructor()) {
12641           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12642           Var->setInvalidDecl();
12643           return;
12644         }
12645       }
12646       // The declaration is unitialized, no need for further checks.
12647       return;
12648     }
12649 
12650     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12651     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12652         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12653       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12654                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12655 
12656 
12657     switch (DefKind) {
12658     case VarDecl::Definition:
12659       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12660         break;
12661 
12662       // We have an out-of-line definition of a static data member
12663       // that has an in-class initializer, so we type-check this like
12664       // a declaration.
12665       //
12666       LLVM_FALLTHROUGH;
12667 
12668     case VarDecl::DeclarationOnly:
12669       // It's only a declaration.
12670 
12671       // Block scope. C99 6.7p7: If an identifier for an object is
12672       // declared with no linkage (C99 6.2.2p6), the type for the
12673       // object shall be complete.
12674       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12675           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12676           RequireCompleteType(Var->getLocation(), Type,
12677                               diag::err_typecheck_decl_incomplete_type))
12678         Var->setInvalidDecl();
12679 
12680       // Make sure that the type is not abstract.
12681       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12682           RequireNonAbstractType(Var->getLocation(), Type,
12683                                  diag::err_abstract_type_in_decl,
12684                                  AbstractVariableType))
12685         Var->setInvalidDecl();
12686       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12687           Var->getStorageClass() == SC_PrivateExtern) {
12688         Diag(Var->getLocation(), diag::warn_private_extern);
12689         Diag(Var->getLocation(), diag::note_private_extern);
12690       }
12691 
12692       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12693           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12694         ExternalDeclarations.push_back(Var);
12695 
12696       return;
12697 
12698     case VarDecl::TentativeDefinition:
12699       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12700       // object that has file scope without an initializer, and without a
12701       // storage-class specifier or with the storage-class specifier "static",
12702       // constitutes a tentative definition. Note: A tentative definition with
12703       // external linkage is valid (C99 6.2.2p5).
12704       if (!Var->isInvalidDecl()) {
12705         if (const IncompleteArrayType *ArrayT
12706                                     = Context.getAsIncompleteArrayType(Type)) {
12707           if (RequireCompleteSizedType(
12708                   Var->getLocation(), ArrayT->getElementType(),
12709                   diag::err_array_incomplete_or_sizeless_type))
12710             Var->setInvalidDecl();
12711         } else if (Var->getStorageClass() == SC_Static) {
12712           // C99 6.9.2p3: If the declaration of an identifier for an object is
12713           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12714           // declared type shall not be an incomplete type.
12715           // NOTE: code such as the following
12716           //     static struct s;
12717           //     struct s { int a; };
12718           // is accepted by gcc. Hence here we issue a warning instead of
12719           // an error and we do not invalidate the static declaration.
12720           // NOTE: to avoid multiple warnings, only check the first declaration.
12721           if (Var->isFirstDecl())
12722             RequireCompleteType(Var->getLocation(), Type,
12723                                 diag::ext_typecheck_decl_incomplete_type);
12724         }
12725       }
12726 
12727       // Record the tentative definition; we're done.
12728       if (!Var->isInvalidDecl())
12729         TentativeDefinitions.push_back(Var);
12730       return;
12731     }
12732 
12733     // Provide a specific diagnostic for uninitialized variable
12734     // definitions with incomplete array type.
12735     if (Type->isIncompleteArrayType()) {
12736       Diag(Var->getLocation(),
12737            diag::err_typecheck_incomplete_array_needs_initializer);
12738       Var->setInvalidDecl();
12739       return;
12740     }
12741 
12742     // Provide a specific diagnostic for uninitialized variable
12743     // definitions with reference type.
12744     if (Type->isReferenceType()) {
12745       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12746           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12747       Var->setInvalidDecl();
12748       return;
12749     }
12750 
12751     // Do not attempt to type-check the default initializer for a
12752     // variable with dependent type.
12753     if (Type->isDependentType())
12754       return;
12755 
12756     if (Var->isInvalidDecl())
12757       return;
12758 
12759     if (!Var->hasAttr<AliasAttr>()) {
12760       if (RequireCompleteType(Var->getLocation(),
12761                               Context.getBaseElementType(Type),
12762                               diag::err_typecheck_decl_incomplete_type)) {
12763         Var->setInvalidDecl();
12764         return;
12765       }
12766     } else {
12767       return;
12768     }
12769 
12770     // The variable can not have an abstract class type.
12771     if (RequireNonAbstractType(Var->getLocation(), Type,
12772                                diag::err_abstract_type_in_decl,
12773                                AbstractVariableType)) {
12774       Var->setInvalidDecl();
12775       return;
12776     }
12777 
12778     // Check for jumps past the implicit initializer.  C++0x
12779     // clarifies that this applies to a "variable with automatic
12780     // storage duration", not a "local variable".
12781     // C++11 [stmt.dcl]p3
12782     //   A program that jumps from a point where a variable with automatic
12783     //   storage duration is not in scope to a point where it is in scope is
12784     //   ill-formed unless the variable has scalar type, class type with a
12785     //   trivial default constructor and a trivial destructor, a cv-qualified
12786     //   version of one of these types, or an array of one of the preceding
12787     //   types and is declared without an initializer.
12788     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12789       if (const RecordType *Record
12790             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12791         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12792         // Mark the function (if we're in one) for further checking even if the
12793         // looser rules of C++11 do not require such checks, so that we can
12794         // diagnose incompatibilities with C++98.
12795         if (!CXXRecord->isPOD())
12796           setFunctionHasBranchProtectedScope();
12797       }
12798     }
12799     // In OpenCL, we can't initialize objects in the __local address space,
12800     // even implicitly, so don't synthesize an implicit initializer.
12801     if (getLangOpts().OpenCL &&
12802         Var->getType().getAddressSpace() == LangAS::opencl_local)
12803       return;
12804     // C++03 [dcl.init]p9:
12805     //   If no initializer is specified for an object, and the
12806     //   object is of (possibly cv-qualified) non-POD class type (or
12807     //   array thereof), the object shall be default-initialized; if
12808     //   the object is of const-qualified type, the underlying class
12809     //   type shall have a user-declared default
12810     //   constructor. Otherwise, if no initializer is specified for
12811     //   a non- static object, the object and its subobjects, if
12812     //   any, have an indeterminate initial value); if the object
12813     //   or any of its subobjects are of const-qualified type, the
12814     //   program is ill-formed.
12815     // C++0x [dcl.init]p11:
12816     //   If no initializer is specified for an object, the object is
12817     //   default-initialized; [...].
12818     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12819     InitializationKind Kind
12820       = InitializationKind::CreateDefault(Var->getLocation());
12821 
12822     InitializationSequence InitSeq(*this, Entity, Kind, None);
12823     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12824 
12825     if (Init.get()) {
12826       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12827       // This is important for template substitution.
12828       Var->setInitStyle(VarDecl::CallInit);
12829     } else if (Init.isInvalid()) {
12830       // If default-init fails, attach a recovery-expr initializer to track
12831       // that initialization was attempted and failed.
12832       auto RecoveryExpr =
12833           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12834       if (RecoveryExpr.get())
12835         Var->setInit(RecoveryExpr.get());
12836     }
12837 
12838     CheckCompleteVariableDeclaration(Var);
12839   }
12840 }
12841 
12842 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12843   // If there is no declaration, there was an error parsing it. Ignore it.
12844   if (!D)
12845     return;
12846 
12847   VarDecl *VD = dyn_cast<VarDecl>(D);
12848   if (!VD) {
12849     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12850     D->setInvalidDecl();
12851     return;
12852   }
12853 
12854   VD->setCXXForRangeDecl(true);
12855 
12856   // for-range-declaration cannot be given a storage class specifier.
12857   int Error = -1;
12858   switch (VD->getStorageClass()) {
12859   case SC_None:
12860     break;
12861   case SC_Extern:
12862     Error = 0;
12863     break;
12864   case SC_Static:
12865     Error = 1;
12866     break;
12867   case SC_PrivateExtern:
12868     Error = 2;
12869     break;
12870   case SC_Auto:
12871     Error = 3;
12872     break;
12873   case SC_Register:
12874     Error = 4;
12875     break;
12876   }
12877 
12878   // for-range-declaration cannot be given a storage class specifier con't.
12879   switch (VD->getTSCSpec()) {
12880   case TSCS_thread_local:
12881     Error = 6;
12882     break;
12883   case TSCS___thread:
12884   case TSCS__Thread_local:
12885   case TSCS_unspecified:
12886     break;
12887   }
12888 
12889   if (Error != -1) {
12890     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12891         << VD << Error;
12892     D->setInvalidDecl();
12893   }
12894 }
12895 
12896 StmtResult
12897 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12898                                  IdentifierInfo *Ident,
12899                                  ParsedAttributes &Attrs,
12900                                  SourceLocation AttrEnd) {
12901   // C++1y [stmt.iter]p1:
12902   //   A range-based for statement of the form
12903   //      for ( for-range-identifier : for-range-initializer ) statement
12904   //   is equivalent to
12905   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12906   DeclSpec DS(Attrs.getPool().getFactory());
12907 
12908   const char *PrevSpec;
12909   unsigned DiagID;
12910   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12911                      getPrintingPolicy());
12912 
12913   Declarator D(DS, DeclaratorContext::ForInit);
12914   D.SetIdentifier(Ident, IdentLoc);
12915   D.takeAttributes(Attrs, AttrEnd);
12916 
12917   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12918                 IdentLoc);
12919   Decl *Var = ActOnDeclarator(S, D);
12920   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12921   FinalizeDeclaration(Var);
12922   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12923                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12924 }
12925 
12926 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12927   if (var->isInvalidDecl()) return;
12928 
12929   if (getLangOpts().OpenCL) {
12930     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12931     // initialiser
12932     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12933         !var->hasInit()) {
12934       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12935           << 1 /*Init*/;
12936       var->setInvalidDecl();
12937       return;
12938     }
12939   }
12940 
12941   // In Objective-C, don't allow jumps past the implicit initialization of a
12942   // local retaining variable.
12943   if (getLangOpts().ObjC &&
12944       var->hasLocalStorage()) {
12945     switch (var->getType().getObjCLifetime()) {
12946     case Qualifiers::OCL_None:
12947     case Qualifiers::OCL_ExplicitNone:
12948     case Qualifiers::OCL_Autoreleasing:
12949       break;
12950 
12951     case Qualifiers::OCL_Weak:
12952     case Qualifiers::OCL_Strong:
12953       setFunctionHasBranchProtectedScope();
12954       break;
12955     }
12956   }
12957 
12958   if (var->hasLocalStorage() &&
12959       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12960     setFunctionHasBranchProtectedScope();
12961 
12962   // Warn about externally-visible variables being defined without a
12963   // prior declaration.  We only want to do this for global
12964   // declarations, but we also specifically need to avoid doing it for
12965   // class members because the linkage of an anonymous class can
12966   // change if it's later given a typedef name.
12967   if (var->isThisDeclarationADefinition() &&
12968       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12969       var->isExternallyVisible() && var->hasLinkage() &&
12970       !var->isInline() && !var->getDescribedVarTemplate() &&
12971       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12972       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12973       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12974                                   var->getLocation())) {
12975     // Find a previous declaration that's not a definition.
12976     VarDecl *prev = var->getPreviousDecl();
12977     while (prev && prev->isThisDeclarationADefinition())
12978       prev = prev->getPreviousDecl();
12979 
12980     if (!prev) {
12981       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12982       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12983           << /* variable */ 0;
12984     }
12985   }
12986 
12987   // Cache the result of checking for constant initialization.
12988   Optional<bool> CacheHasConstInit;
12989   const Expr *CacheCulprit = nullptr;
12990   auto checkConstInit = [&]() mutable {
12991     if (!CacheHasConstInit)
12992       CacheHasConstInit = var->getInit()->isConstantInitializer(
12993             Context, var->getType()->isReferenceType(), &CacheCulprit);
12994     return *CacheHasConstInit;
12995   };
12996 
12997   if (var->getTLSKind() == VarDecl::TLS_Static) {
12998     if (var->getType().isDestructedType()) {
12999       // GNU C++98 edits for __thread, [basic.start.term]p3:
13000       //   The type of an object with thread storage duration shall not
13001       //   have a non-trivial destructor.
13002       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13003       if (getLangOpts().CPlusPlus11)
13004         Diag(var->getLocation(), diag::note_use_thread_local);
13005     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13006       if (!checkConstInit()) {
13007         // GNU C++98 edits for __thread, [basic.start.init]p4:
13008         //   An object of thread storage duration shall not require dynamic
13009         //   initialization.
13010         // FIXME: Need strict checking here.
13011         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13012           << CacheCulprit->getSourceRange();
13013         if (getLangOpts().CPlusPlus11)
13014           Diag(var->getLocation(), diag::note_use_thread_local);
13015       }
13016     }
13017   }
13018 
13019   // Apply section attributes and pragmas to global variables.
13020   bool GlobalStorage = var->hasGlobalStorage();
13021   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13022       !inTemplateInstantiation()) {
13023     PragmaStack<StringLiteral *> *Stack = nullptr;
13024     int SectionFlags = ASTContext::PSF_Read;
13025     if (var->getType().isConstQualified())
13026       Stack = &ConstSegStack;
13027     else if (!var->getInit()) {
13028       Stack = &BSSSegStack;
13029       SectionFlags |= ASTContext::PSF_Write;
13030     } else {
13031       Stack = &DataSegStack;
13032       SectionFlags |= ASTContext::PSF_Write;
13033     }
13034     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13035       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13036         SectionFlags |= ASTContext::PSF_Implicit;
13037       UnifySection(SA->getName(), SectionFlags, var);
13038     } else if (Stack->CurrentValue) {
13039       SectionFlags |= ASTContext::PSF_Implicit;
13040       auto SectionName = Stack->CurrentValue->getString();
13041       var->addAttr(SectionAttr::CreateImplicit(
13042           Context, SectionName, Stack->CurrentPragmaLocation,
13043           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13044       if (UnifySection(SectionName, SectionFlags, var))
13045         var->dropAttr<SectionAttr>();
13046     }
13047 
13048     // Apply the init_seg attribute if this has an initializer.  If the
13049     // initializer turns out to not be dynamic, we'll end up ignoring this
13050     // attribute.
13051     if (CurInitSeg && var->getInit())
13052       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13053                                                CurInitSegLoc,
13054                                                AttributeCommonInfo::AS_Pragma));
13055   }
13056 
13057   if (!var->getType()->isStructureType() && var->hasInit() &&
13058       isa<InitListExpr>(var->getInit())) {
13059     const auto *ILE = cast<InitListExpr>(var->getInit());
13060     unsigned NumInits = ILE->getNumInits();
13061     if (NumInits > 2)
13062       for (unsigned I = 0; I < NumInits; ++I) {
13063         const auto *Init = ILE->getInit(I);
13064         if (!Init)
13065           break;
13066         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13067         if (!SL)
13068           break;
13069 
13070         unsigned NumConcat = SL->getNumConcatenated();
13071         // Diagnose missing comma in string array initialization.
13072         // Do not warn when all the elements in the initializer are concatenated
13073         // together. Do not warn for macros too.
13074         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13075           bool OnlyOneMissingComma = true;
13076           for (unsigned J = I + 1; J < NumInits; ++J) {
13077             const auto *Init = ILE->getInit(J);
13078             if (!Init)
13079               break;
13080             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13081             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13082               OnlyOneMissingComma = false;
13083               break;
13084             }
13085           }
13086 
13087           if (OnlyOneMissingComma) {
13088             SmallVector<FixItHint, 1> Hints;
13089             for (unsigned i = 0; i < NumConcat - 1; ++i)
13090               Hints.push_back(FixItHint::CreateInsertion(
13091                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13092 
13093             Diag(SL->getStrTokenLoc(1),
13094                  diag::warn_concatenated_literal_array_init)
13095                 << Hints;
13096             Diag(SL->getBeginLoc(),
13097                  diag::note_concatenated_string_literal_silence);
13098           }
13099           // In any case, stop now.
13100           break;
13101         }
13102       }
13103   }
13104 
13105   // All the following checks are C++ only.
13106   if (!getLangOpts().CPlusPlus) {
13107     // If this variable must be emitted, add it as an initializer for the
13108     // current module.
13109     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13110       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13111     return;
13112   }
13113 
13114   QualType type = var->getType();
13115 
13116   if (var->hasAttr<BlocksAttr>())
13117     getCurFunction()->addByrefBlockVar(var);
13118 
13119   Expr *Init = var->getInit();
13120   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13121   QualType baseType = Context.getBaseElementType(type);
13122 
13123   // Check whether the initializer is sufficiently constant.
13124   if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13125       (GlobalStorage || var->isConstexpr() ||
13126        var->mightBeUsableInConstantExpressions(Context))) {
13127     // If this variable might have a constant initializer or might be usable in
13128     // constant expressions, check whether or not it actually is now.  We can't
13129     // do this lazily, because the result might depend on things that change
13130     // later, such as which constexpr functions happen to be defined.
13131     SmallVector<PartialDiagnosticAt, 8> Notes;
13132     bool HasConstInit;
13133     if (!getLangOpts().CPlusPlus11) {
13134       // Prior to C++11, in contexts where a constant initializer is required,
13135       // the set of valid constant initializers is described by syntactic rules
13136       // in [expr.const]p2-6.
13137       // FIXME: Stricter checking for these rules would be useful for constinit /
13138       // -Wglobal-constructors.
13139       HasConstInit = checkConstInit();
13140 
13141       // Compute and cache the constant value, and remember that we have a
13142       // constant initializer.
13143       if (HasConstInit) {
13144         (void)var->checkForConstantInitialization(Notes);
13145         Notes.clear();
13146       } else if (CacheCulprit) {
13147         Notes.emplace_back(CacheCulprit->getExprLoc(),
13148                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13149         Notes.back().second << CacheCulprit->getSourceRange();
13150       }
13151     } else {
13152       // Evaluate the initializer to see if it's a constant initializer.
13153       HasConstInit = var->checkForConstantInitialization(Notes);
13154     }
13155 
13156     if (HasConstInit) {
13157       // FIXME: Consider replacing the initializer with a ConstantExpr.
13158     } else if (var->isConstexpr()) {
13159       SourceLocation DiagLoc = var->getLocation();
13160       // If the note doesn't add any useful information other than a source
13161       // location, fold it into the primary diagnostic.
13162       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13163                                    diag::note_invalid_subexpr_in_const_expr) {
13164         DiagLoc = Notes[0].first;
13165         Notes.clear();
13166       }
13167       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13168           << var << Init->getSourceRange();
13169       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13170         Diag(Notes[I].first, Notes[I].second);
13171     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13172       auto *Attr = var->getAttr<ConstInitAttr>();
13173       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13174           << Init->getSourceRange();
13175       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13176           << Attr->getRange() << Attr->isConstinit();
13177       for (auto &it : Notes)
13178         Diag(it.first, it.second);
13179     } else if (IsGlobal &&
13180                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13181                                            var->getLocation())) {
13182       // Warn about globals which don't have a constant initializer.  Don't
13183       // warn about globals with a non-trivial destructor because we already
13184       // warned about them.
13185       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13186       if (!(RD && !RD->hasTrivialDestructor())) {
13187         // checkConstInit() here permits trivial default initialization even in
13188         // C++11 onwards, where such an initializer is not a constant initializer
13189         // but nonetheless doesn't require a global constructor.
13190         if (!checkConstInit())
13191           Diag(var->getLocation(), diag::warn_global_constructor)
13192               << Init->getSourceRange();
13193       }
13194     }
13195   }
13196 
13197   // Require the destructor.
13198   if (!type->isDependentType())
13199     if (const RecordType *recordType = baseType->getAs<RecordType>())
13200       FinalizeVarWithDestructor(var, recordType);
13201 
13202   // If this variable must be emitted, add it as an initializer for the current
13203   // module.
13204   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13205     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13206 
13207   // Build the bindings if this is a structured binding declaration.
13208   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13209     CheckCompleteDecompositionDeclaration(DD);
13210 }
13211 
13212 /// Determines if a variable's alignment is dependent.
13213 static bool hasDependentAlignment(VarDecl *VD) {
13214   if (VD->getType()->isDependentType())
13215     return true;
13216   for (auto *I : VD->specific_attrs<AlignedAttr>())
13217     if (I->isAlignmentDependent())
13218       return true;
13219   return false;
13220 }
13221 
13222 /// Check if VD needs to be dllexport/dllimport due to being in a
13223 /// dllexport/import function.
13224 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13225   assert(VD->isStaticLocal());
13226 
13227   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13228 
13229   // Find outermost function when VD is in lambda function.
13230   while (FD && !getDLLAttr(FD) &&
13231          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13232          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13233     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13234   }
13235 
13236   if (!FD)
13237     return;
13238 
13239   // Static locals inherit dll attributes from their function.
13240   if (Attr *A = getDLLAttr(FD)) {
13241     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13242     NewAttr->setInherited(true);
13243     VD->addAttr(NewAttr);
13244   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13245     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13246     NewAttr->setInherited(true);
13247     VD->addAttr(NewAttr);
13248 
13249     // Export this function to enforce exporting this static variable even
13250     // if it is not used in this compilation unit.
13251     if (!FD->hasAttr<DLLExportAttr>())
13252       FD->addAttr(NewAttr);
13253 
13254   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13255     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13256     NewAttr->setInherited(true);
13257     VD->addAttr(NewAttr);
13258   }
13259 }
13260 
13261 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13262 /// any semantic actions necessary after any initializer has been attached.
13263 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13264   // Note that we are no longer parsing the initializer for this declaration.
13265   ParsingInitForAutoVars.erase(ThisDecl);
13266 
13267   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13268   if (!VD)
13269     return;
13270 
13271   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13272   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13273       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13274     if (PragmaClangBSSSection.Valid)
13275       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13276           Context, PragmaClangBSSSection.SectionName,
13277           PragmaClangBSSSection.PragmaLocation,
13278           AttributeCommonInfo::AS_Pragma));
13279     if (PragmaClangDataSection.Valid)
13280       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13281           Context, PragmaClangDataSection.SectionName,
13282           PragmaClangDataSection.PragmaLocation,
13283           AttributeCommonInfo::AS_Pragma));
13284     if (PragmaClangRodataSection.Valid)
13285       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13286           Context, PragmaClangRodataSection.SectionName,
13287           PragmaClangRodataSection.PragmaLocation,
13288           AttributeCommonInfo::AS_Pragma));
13289     if (PragmaClangRelroSection.Valid)
13290       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13291           Context, PragmaClangRelroSection.SectionName,
13292           PragmaClangRelroSection.PragmaLocation,
13293           AttributeCommonInfo::AS_Pragma));
13294   }
13295 
13296   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13297     for (auto *BD : DD->bindings()) {
13298       FinalizeDeclaration(BD);
13299     }
13300   }
13301 
13302   checkAttributesAfterMerging(*this, *VD);
13303 
13304   // Perform TLS alignment check here after attributes attached to the variable
13305   // which may affect the alignment have been processed. Only perform the check
13306   // if the target has a maximum TLS alignment (zero means no constraints).
13307   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13308     // Protect the check so that it's not performed on dependent types and
13309     // dependent alignments (we can't determine the alignment in that case).
13310     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13311         !VD->isInvalidDecl()) {
13312       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13313       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13314         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13315           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13316           << (unsigned)MaxAlignChars.getQuantity();
13317       }
13318     }
13319   }
13320 
13321   if (VD->isStaticLocal())
13322     CheckStaticLocalForDllExport(VD);
13323 
13324   // Perform check for initializers of device-side global variables.
13325   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13326   // 7.5). We must also apply the same checks to all __shared__
13327   // variables whether they are local or not. CUDA also allows
13328   // constant initializers for __constant__ and __device__ variables.
13329   if (getLangOpts().CUDA)
13330     checkAllowedCUDAInitializer(VD);
13331 
13332   // Grab the dllimport or dllexport attribute off of the VarDecl.
13333   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13334 
13335   // Imported static data members cannot be defined out-of-line.
13336   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13337     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13338         VD->isThisDeclarationADefinition()) {
13339       // We allow definitions of dllimport class template static data members
13340       // with a warning.
13341       CXXRecordDecl *Context =
13342         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13343       bool IsClassTemplateMember =
13344           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13345           Context->getDescribedClassTemplate();
13346 
13347       Diag(VD->getLocation(),
13348            IsClassTemplateMember
13349                ? diag::warn_attribute_dllimport_static_field_definition
13350                : diag::err_attribute_dllimport_static_field_definition);
13351       Diag(IA->getLocation(), diag::note_attribute);
13352       if (!IsClassTemplateMember)
13353         VD->setInvalidDecl();
13354     }
13355   }
13356 
13357   // dllimport/dllexport variables cannot be thread local, their TLS index
13358   // isn't exported with the variable.
13359   if (DLLAttr && VD->getTLSKind()) {
13360     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13361     if (F && getDLLAttr(F)) {
13362       assert(VD->isStaticLocal());
13363       // But if this is a static local in a dlimport/dllexport function, the
13364       // function will never be inlined, which means the var would never be
13365       // imported, so having it marked import/export is safe.
13366     } else {
13367       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13368                                                                     << DLLAttr;
13369       VD->setInvalidDecl();
13370     }
13371   }
13372 
13373   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13374     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13375       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13376           << Attr;
13377       VD->dropAttr<UsedAttr>();
13378     }
13379   }
13380   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13381     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13382       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13383           << Attr;
13384       VD->dropAttr<RetainAttr>();
13385     }
13386   }
13387 
13388   const DeclContext *DC = VD->getDeclContext();
13389   // If there's a #pragma GCC visibility in scope, and this isn't a class
13390   // member, set the visibility of this variable.
13391   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13392     AddPushedVisibilityAttribute(VD);
13393 
13394   // FIXME: Warn on unused var template partial specializations.
13395   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13396     MarkUnusedFileScopedDecl(VD);
13397 
13398   // Now we have parsed the initializer and can update the table of magic
13399   // tag values.
13400   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13401       !VD->getType()->isIntegralOrEnumerationType())
13402     return;
13403 
13404   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13405     const Expr *MagicValueExpr = VD->getInit();
13406     if (!MagicValueExpr) {
13407       continue;
13408     }
13409     Optional<llvm::APSInt> MagicValueInt;
13410     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13411       Diag(I->getRange().getBegin(),
13412            diag::err_type_tag_for_datatype_not_ice)
13413         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13414       continue;
13415     }
13416     if (MagicValueInt->getActiveBits() > 64) {
13417       Diag(I->getRange().getBegin(),
13418            diag::err_type_tag_for_datatype_too_large)
13419         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13420       continue;
13421     }
13422     uint64_t MagicValue = MagicValueInt->getZExtValue();
13423     RegisterTypeTagForDatatype(I->getArgumentKind(),
13424                                MagicValue,
13425                                I->getMatchingCType(),
13426                                I->getLayoutCompatible(),
13427                                I->getMustBeNull());
13428   }
13429 }
13430 
13431 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13432   auto *VD = dyn_cast<VarDecl>(DD);
13433   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13434 }
13435 
13436 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13437                                                    ArrayRef<Decl *> Group) {
13438   SmallVector<Decl*, 8> Decls;
13439 
13440   if (DS.isTypeSpecOwned())
13441     Decls.push_back(DS.getRepAsDecl());
13442 
13443   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13444   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13445   bool DiagnosedMultipleDecomps = false;
13446   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13447   bool DiagnosedNonDeducedAuto = false;
13448 
13449   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13450     if (Decl *D = Group[i]) {
13451       // For declarators, there are some additional syntactic-ish checks we need
13452       // to perform.
13453       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13454         if (!FirstDeclaratorInGroup)
13455           FirstDeclaratorInGroup = DD;
13456         if (!FirstDecompDeclaratorInGroup)
13457           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13458         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13459             !hasDeducedAuto(DD))
13460           FirstNonDeducedAutoInGroup = DD;
13461 
13462         if (FirstDeclaratorInGroup != DD) {
13463           // A decomposition declaration cannot be combined with any other
13464           // declaration in the same group.
13465           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13466             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13467                  diag::err_decomp_decl_not_alone)
13468                 << FirstDeclaratorInGroup->getSourceRange()
13469                 << DD->getSourceRange();
13470             DiagnosedMultipleDecomps = true;
13471           }
13472 
13473           // A declarator that uses 'auto' in any way other than to declare a
13474           // variable with a deduced type cannot be combined with any other
13475           // declarator in the same group.
13476           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13477             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13478                  diag::err_auto_non_deduced_not_alone)
13479                 << FirstNonDeducedAutoInGroup->getType()
13480                        ->hasAutoForTrailingReturnType()
13481                 << FirstDeclaratorInGroup->getSourceRange()
13482                 << DD->getSourceRange();
13483             DiagnosedNonDeducedAuto = true;
13484           }
13485         }
13486       }
13487 
13488       Decls.push_back(D);
13489     }
13490   }
13491 
13492   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13493     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13494       handleTagNumbering(Tag, S);
13495       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13496           getLangOpts().CPlusPlus)
13497         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13498     }
13499   }
13500 
13501   return BuildDeclaratorGroup(Decls);
13502 }
13503 
13504 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13505 /// group, performing any necessary semantic checking.
13506 Sema::DeclGroupPtrTy
13507 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13508   // C++14 [dcl.spec.auto]p7: (DR1347)
13509   //   If the type that replaces the placeholder type is not the same in each
13510   //   deduction, the program is ill-formed.
13511   if (Group.size() > 1) {
13512     QualType Deduced;
13513     VarDecl *DeducedDecl = nullptr;
13514     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13515       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13516       if (!D || D->isInvalidDecl())
13517         break;
13518       DeducedType *DT = D->getType()->getContainedDeducedType();
13519       if (!DT || DT->getDeducedType().isNull())
13520         continue;
13521       if (Deduced.isNull()) {
13522         Deduced = DT->getDeducedType();
13523         DeducedDecl = D;
13524       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13525         auto *AT = dyn_cast<AutoType>(DT);
13526         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13527                         diag::err_auto_different_deductions)
13528                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13529                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13530                    << D->getDeclName();
13531         if (DeducedDecl->hasInit())
13532           Dia << DeducedDecl->getInit()->getSourceRange();
13533         if (D->getInit())
13534           Dia << D->getInit()->getSourceRange();
13535         D->setInvalidDecl();
13536         break;
13537       }
13538     }
13539   }
13540 
13541   ActOnDocumentableDecls(Group);
13542 
13543   return DeclGroupPtrTy::make(
13544       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13545 }
13546 
13547 void Sema::ActOnDocumentableDecl(Decl *D) {
13548   ActOnDocumentableDecls(D);
13549 }
13550 
13551 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13552   // Don't parse the comment if Doxygen diagnostics are ignored.
13553   if (Group.empty() || !Group[0])
13554     return;
13555 
13556   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13557                       Group[0]->getLocation()) &&
13558       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13559                       Group[0]->getLocation()))
13560     return;
13561 
13562   if (Group.size() >= 2) {
13563     // This is a decl group.  Normally it will contain only declarations
13564     // produced from declarator list.  But in case we have any definitions or
13565     // additional declaration references:
13566     //   'typedef struct S {} S;'
13567     //   'typedef struct S *S;'
13568     //   'struct S *pS;'
13569     // FinalizeDeclaratorGroup adds these as separate declarations.
13570     Decl *MaybeTagDecl = Group[0];
13571     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13572       Group = Group.slice(1);
13573     }
13574   }
13575 
13576   // FIMXE: We assume every Decl in the group is in the same file.
13577   // This is false when preprocessor constructs the group from decls in
13578   // different files (e. g. macros or #include).
13579   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13580 }
13581 
13582 /// Common checks for a parameter-declaration that should apply to both function
13583 /// parameters and non-type template parameters.
13584 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13585   // Check that there are no default arguments inside the type of this
13586   // parameter.
13587   if (getLangOpts().CPlusPlus)
13588     CheckExtraCXXDefaultArguments(D);
13589 
13590   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13591   if (D.getCXXScopeSpec().isSet()) {
13592     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13593       << D.getCXXScopeSpec().getRange();
13594   }
13595 
13596   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13597   // simple identifier except [...irrelevant cases...].
13598   switch (D.getName().getKind()) {
13599   case UnqualifiedIdKind::IK_Identifier:
13600     break;
13601 
13602   case UnqualifiedIdKind::IK_OperatorFunctionId:
13603   case UnqualifiedIdKind::IK_ConversionFunctionId:
13604   case UnqualifiedIdKind::IK_LiteralOperatorId:
13605   case UnqualifiedIdKind::IK_ConstructorName:
13606   case UnqualifiedIdKind::IK_DestructorName:
13607   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13608   case UnqualifiedIdKind::IK_DeductionGuideName:
13609     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13610       << GetNameForDeclarator(D).getName();
13611     break;
13612 
13613   case UnqualifiedIdKind::IK_TemplateId:
13614   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13615     // GetNameForDeclarator would not produce a useful name in this case.
13616     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13617     break;
13618   }
13619 }
13620 
13621 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13622 /// to introduce parameters into function prototype scope.
13623 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13624   const DeclSpec &DS = D.getDeclSpec();
13625 
13626   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13627 
13628   // C++03 [dcl.stc]p2 also permits 'auto'.
13629   StorageClass SC = SC_None;
13630   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13631     SC = SC_Register;
13632     // In C++11, the 'register' storage class specifier is deprecated.
13633     // In C++17, it is not allowed, but we tolerate it as an extension.
13634     if (getLangOpts().CPlusPlus11) {
13635       Diag(DS.getStorageClassSpecLoc(),
13636            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13637                                      : diag::warn_deprecated_register)
13638         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13639     }
13640   } else if (getLangOpts().CPlusPlus &&
13641              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13642     SC = SC_Auto;
13643   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13644     Diag(DS.getStorageClassSpecLoc(),
13645          diag::err_invalid_storage_class_in_func_decl);
13646     D.getMutableDeclSpec().ClearStorageClassSpecs();
13647   }
13648 
13649   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13650     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13651       << DeclSpec::getSpecifierName(TSCS);
13652   if (DS.isInlineSpecified())
13653     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13654         << getLangOpts().CPlusPlus17;
13655   if (DS.hasConstexprSpecifier())
13656     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13657         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13658 
13659   DiagnoseFunctionSpecifiers(DS);
13660 
13661   CheckFunctionOrTemplateParamDeclarator(S, D);
13662 
13663   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13664   QualType parmDeclType = TInfo->getType();
13665 
13666   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13667   IdentifierInfo *II = D.getIdentifier();
13668   if (II) {
13669     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13670                    ForVisibleRedeclaration);
13671     LookupName(R, S);
13672     if (R.isSingleResult()) {
13673       NamedDecl *PrevDecl = R.getFoundDecl();
13674       if (PrevDecl->isTemplateParameter()) {
13675         // Maybe we will complain about the shadowed template parameter.
13676         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13677         // Just pretend that we didn't see the previous declaration.
13678         PrevDecl = nullptr;
13679       } else if (S->isDeclScope(PrevDecl)) {
13680         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13681         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13682 
13683         // Recover by removing the name
13684         II = nullptr;
13685         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13686         D.setInvalidType(true);
13687       }
13688     }
13689   }
13690 
13691   // Temporarily put parameter variables in the translation unit, not
13692   // the enclosing context.  This prevents them from accidentally
13693   // looking like class members in C++.
13694   ParmVarDecl *New =
13695       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13696                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13697 
13698   if (D.isInvalidType())
13699     New->setInvalidDecl();
13700 
13701   assert(S->isFunctionPrototypeScope());
13702   assert(S->getFunctionPrototypeDepth() >= 1);
13703   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13704                     S->getNextFunctionPrototypeIndex());
13705 
13706   // Add the parameter declaration into this scope.
13707   S->AddDecl(New);
13708   if (II)
13709     IdResolver.AddDecl(New);
13710 
13711   ProcessDeclAttributes(S, New, D);
13712 
13713   if (D.getDeclSpec().isModulePrivateSpecified())
13714     Diag(New->getLocation(), diag::err_module_private_local)
13715         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13716         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13717 
13718   if (New->hasAttr<BlocksAttr>()) {
13719     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13720   }
13721 
13722   if (getLangOpts().OpenCL)
13723     deduceOpenCLAddressSpace(New);
13724 
13725   return New;
13726 }
13727 
13728 /// Synthesizes a variable for a parameter arising from a
13729 /// typedef.
13730 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13731                                               SourceLocation Loc,
13732                                               QualType T) {
13733   /* FIXME: setting StartLoc == Loc.
13734      Would it be worth to modify callers so as to provide proper source
13735      location for the unnamed parameters, embedding the parameter's type? */
13736   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13737                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13738                                            SC_None, nullptr);
13739   Param->setImplicit();
13740   return Param;
13741 }
13742 
13743 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13744   // Don't diagnose unused-parameter errors in template instantiations; we
13745   // will already have done so in the template itself.
13746   if (inTemplateInstantiation())
13747     return;
13748 
13749   for (const ParmVarDecl *Parameter : Parameters) {
13750     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13751         !Parameter->hasAttr<UnusedAttr>()) {
13752       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13753         << Parameter->getDeclName();
13754     }
13755   }
13756 }
13757 
13758 using AllUsesSetsPtrSet = llvm::SmallPtrSet<const NamedDecl *, 16>;
13759 
13760 namespace {
13761 
13762 struct AllUsesAreSetsVisitor : RecursiveASTVisitor<AllUsesAreSetsVisitor> {
13763   AllUsesSetsPtrSet &S;
13764 
13765   AllUsesAreSetsVisitor(AllUsesSetsPtrSet &Set) : S(Set) {}
13766 
13767   bool TraverseBinaryOperator(const BinaryOperator *BO) {
13768     auto *LHS = BO->getLHS();
13769     auto *DRE = dyn_cast<DeclRefExpr>(LHS);
13770     if (!BO->isAssignmentOp() || !DRE || !S.count(DRE->getFoundDecl())) {
13771       // This is not an assignment to one of our NamedDecls.
13772       if (!TraverseStmt(LHS))
13773         return false;
13774     }
13775     return TraverseStmt(BO->getRHS());
13776   }
13777 
13778   bool VisitDeclRefExpr(const DeclRefExpr *DRE) {
13779     // If we remove all Decls, no need to keep searching.
13780     return !S.erase(DRE->getFoundDecl()) || S.size();
13781   }
13782 
13783   bool OverloadedTraverse(Stmt *S) { return TraverseStmt(S); }
13784 
13785   bool OverloadedTraverse(Decl *D) { return TraverseDecl(D); }
13786 };
13787 
13788 } // end anonymous namespace
13789 
13790 /// For any NamedDecl in Decls that is not used in any way other than the LHS of
13791 /// an assignment, diagnose with the given DiagId.
13792 template <typename R, typename T>
13793 static void DiagnoseUnusedButSetDecls(Sema *Se, T *Parent, R Decls,
13794                                       unsigned DiagID) {
13795   // Put the Decls in a set so we only have to traverse the body once for all of
13796   // them.
13797   AllUsesSetsPtrSet AllUsesAreSets;
13798 
13799   for (const NamedDecl *ND : Decls) {
13800     AllUsesAreSets.insert(ND);
13801   }
13802 
13803   if (!AllUsesAreSets.size())
13804     return;
13805 
13806   AllUsesAreSetsVisitor Visitor(AllUsesAreSets);
13807   Visitor.OverloadedTraverse(Parent);
13808 
13809   for (const NamedDecl *ND : AllUsesAreSets) {
13810     Se->Diag(ND->getLocation(), DiagID) << ND->getDeclName();
13811   }
13812 }
13813 
13814 void Sema::DiagnoseUnusedButSetParameters(ArrayRef<ParmVarDecl *> Parameters) {
13815   // Don't diagnose unused-but-set-parameter errors in template instantiations;
13816   // we will already have done so in the template itself.
13817   if (inTemplateInstantiation())
13818     return;
13819 
13820   bool CPlusPlus = getLangOpts().CPlusPlus;
13821 
13822   auto IsCandidate = [&](const ParmVarDecl *P) {
13823     // Check for Ignored here, because if we have no candidates we can avoid
13824     // walking the AST.
13825     if (Diags.getDiagnosticLevel(diag::warn_unused_but_set_parameter,
13826                                  P->getLocation()) ==
13827         DiagnosticsEngine::Ignored)
13828       return false;
13829     if (!P->isReferenced() || !P->getDeclName() || P->hasAttr<UnusedAttr>())
13830       return false;
13831     // Mimic gcc's behavior regarding nonscalar types.
13832     if (CPlusPlus && !P->getType()->isScalarType())
13833       return false;
13834     return true;
13835   };
13836 
13837   auto Candidates = llvm::make_filter_range(Parameters, IsCandidate);
13838 
13839   if (Parameters.empty())
13840     return;
13841 
13842   // Traverse the Decl, not just the body; otherwise we'd miss things like
13843   // CXXCtorInitializer.
13844   if (Decl *D =
13845           Decl::castFromDeclContext((*Parameters.begin())->getDeclContext()))
13846     DiagnoseUnusedButSetDecls(this, D, Candidates,
13847                               diag::warn_unused_but_set_parameter);
13848 }
13849 
13850 void Sema::DiagnoseUnusedButSetVariables(CompoundStmt *CS) {
13851   bool CPlusPlus = getLangOpts().CPlusPlus;
13852 
13853   auto IsCandidate = [&](const Stmt *S) {
13854     const DeclStmt *SD = dyn_cast<DeclStmt>(S);
13855     if (!SD || !SD->isSingleDecl())
13856       return false;
13857     const VarDecl *VD = dyn_cast<VarDecl>(SD->getSingleDecl());
13858     // Check for Ignored here, because if we have no candidates we can avoid
13859     // walking the AST.
13860     if (!VD || Diags.getDiagnosticLevel(diag::warn_unused_but_set_variable,
13861                                         VD->getLocation()) ==
13862                    DiagnosticsEngine::Ignored)
13863       return false;
13864     if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
13865       return false;
13866     // Declarations which are const or constexpr can't be assigned to after
13867     // initialization anyway, and avoiding these cases will prevent false
13868     // positives when uses of a constexpr don't appear in the AST.
13869     if (VD->isConstexpr() || VD->getType().isConstQualified())
13870       return false;
13871     // Mimic gcc's behavior regarding nonscalar types.
13872     if (CPlusPlus && !VD->getType()->isScalarType())
13873       return false;
13874     return true;
13875   };
13876 
13877   auto Candidates = llvm::make_filter_range(CS->body(), IsCandidate);
13878 
13879   auto ToNamedDecl = [](const Stmt *S) {
13880     const DeclStmt *SD = dyn_cast<const DeclStmt>(S);
13881     return dyn_cast<const NamedDecl>(SD->getSingleDecl());
13882   };
13883 
13884   auto CandidateDecls = llvm::map_range(Candidates, ToNamedDecl);
13885 
13886   DiagnoseUnusedButSetDecls(this, CS, CandidateDecls,
13887                             diag::warn_unused_but_set_variable);
13888 }
13889 
13890 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13891     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13892   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13893     return;
13894 
13895   // Warn if the return value is pass-by-value and larger than the specified
13896   // threshold.
13897   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13898     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13899     if (Size > LangOpts.NumLargeByValueCopy)
13900       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13901   }
13902 
13903   // Warn if any parameter is pass-by-value and larger than the specified
13904   // threshold.
13905   for (const ParmVarDecl *Parameter : Parameters) {
13906     QualType T = Parameter->getType();
13907     if (T->isDependentType() || !T.isPODType(Context))
13908       continue;
13909     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13910     if (Size > LangOpts.NumLargeByValueCopy)
13911       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13912           << Parameter << Size;
13913   }
13914 }
13915 
13916 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13917                                   SourceLocation NameLoc, IdentifierInfo *Name,
13918                                   QualType T, TypeSourceInfo *TSInfo,
13919                                   StorageClass SC) {
13920   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13921   if (getLangOpts().ObjCAutoRefCount &&
13922       T.getObjCLifetime() == Qualifiers::OCL_None &&
13923       T->isObjCLifetimeType()) {
13924 
13925     Qualifiers::ObjCLifetime lifetime;
13926 
13927     // Special cases for arrays:
13928     //   - if it's const, use __unsafe_unretained
13929     //   - otherwise, it's an error
13930     if (T->isArrayType()) {
13931       if (!T.isConstQualified()) {
13932         if (DelayedDiagnostics.shouldDelayDiagnostics())
13933           DelayedDiagnostics.add(
13934               sema::DelayedDiagnostic::makeForbiddenType(
13935               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13936         else
13937           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13938               << TSInfo->getTypeLoc().getSourceRange();
13939       }
13940       lifetime = Qualifiers::OCL_ExplicitNone;
13941     } else {
13942       lifetime = T->getObjCARCImplicitLifetime();
13943     }
13944     T = Context.getLifetimeQualifiedType(T, lifetime);
13945   }
13946 
13947   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13948                                          Context.getAdjustedParameterType(T),
13949                                          TSInfo, SC, nullptr);
13950 
13951   // Make a note if we created a new pack in the scope of a lambda, so that
13952   // we know that references to that pack must also be expanded within the
13953   // lambda scope.
13954   if (New->isParameterPack())
13955     if (auto *LSI = getEnclosingLambda())
13956       LSI->LocalPacks.push_back(New);
13957 
13958   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13959       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13960     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13961                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13962 
13963   // Parameters can not be abstract class types.
13964   // For record types, this is done by the AbstractClassUsageDiagnoser once
13965   // the class has been completely parsed.
13966   if (!CurContext->isRecord() &&
13967       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13968                              AbstractParamType))
13969     New->setInvalidDecl();
13970 
13971   // Parameter declarators cannot be interface types. All ObjC objects are
13972   // passed by reference.
13973   if (T->isObjCObjectType()) {
13974     SourceLocation TypeEndLoc =
13975         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13976     Diag(NameLoc,
13977          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13978       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13979     T = Context.getObjCObjectPointerType(T);
13980     New->setType(T);
13981   }
13982 
13983   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13984   // duration shall not be qualified by an address-space qualifier."
13985   // Since all parameters have automatic store duration, they can not have
13986   // an address space.
13987   if (T.getAddressSpace() != LangAS::Default &&
13988       // OpenCL allows function arguments declared to be an array of a type
13989       // to be qualified with an address space.
13990       !(getLangOpts().OpenCL &&
13991         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13992     Diag(NameLoc, diag::err_arg_with_address_space);
13993     New->setInvalidDecl();
13994   }
13995 
13996   // PPC MMA non-pointer types are not allowed as function argument types.
13997   if (Context.getTargetInfo().getTriple().isPPC64() &&
13998       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13999     New->setInvalidDecl();
14000   }
14001 
14002   return New;
14003 }
14004 
14005 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14006                                            SourceLocation LocAfterDecls) {
14007   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14008 
14009   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14010   // for a K&R function.
14011   if (!FTI.hasPrototype) {
14012     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14013       --i;
14014       if (FTI.Params[i].Param == nullptr) {
14015         SmallString<256> Code;
14016         llvm::raw_svector_ostream(Code)
14017             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14018         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14019             << FTI.Params[i].Ident
14020             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14021 
14022         // Implicitly declare the argument as type 'int' for lack of a better
14023         // type.
14024         AttributeFactory attrs;
14025         DeclSpec DS(attrs);
14026         const char* PrevSpec; // unused
14027         unsigned DiagID; // unused
14028         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14029                            DiagID, Context.getPrintingPolicy());
14030         // Use the identifier location for the type source range.
14031         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14032         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14033         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14034         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14035         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14036       }
14037     }
14038   }
14039 }
14040 
14041 Decl *
14042 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14043                               MultiTemplateParamsArg TemplateParameterLists,
14044                               SkipBodyInfo *SkipBody) {
14045   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14046   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14047   Scope *ParentScope = FnBodyScope->getParent();
14048 
14049   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14050   // we define a non-templated function definition, we will create a declaration
14051   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14052   // The base function declaration will have the equivalent of an `omp declare
14053   // variant` annotation which specifies the mangled definition as a
14054   // specialization function under the OpenMP context defined as part of the
14055   // `omp begin declare variant`.
14056   SmallVector<FunctionDecl *, 4> Bases;
14057   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14058     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14059         ParentScope, D, TemplateParameterLists, Bases);
14060 
14061   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14062   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14063   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14064 
14065   if (!Bases.empty())
14066     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14067 
14068   return Dcl;
14069 }
14070 
14071 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14072   Consumer.HandleInlineFunctionDefinition(D);
14073 }
14074 
14075 static bool
14076 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14077                                 const FunctionDecl *&PossiblePrototype) {
14078   // Don't warn about invalid declarations.
14079   if (FD->isInvalidDecl())
14080     return false;
14081 
14082   // Or declarations that aren't global.
14083   if (!FD->isGlobal())
14084     return false;
14085 
14086   // Don't warn about C++ member functions.
14087   if (isa<CXXMethodDecl>(FD))
14088     return false;
14089 
14090   // Don't warn about 'main'.
14091   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14092     if (IdentifierInfo *II = FD->getIdentifier())
14093       if (II->isStr("main") || II->isStr("efi_main"))
14094         return false;
14095 
14096   // Don't warn about inline functions.
14097   if (FD->isInlined())
14098     return false;
14099 
14100   // Don't warn about function templates.
14101   if (FD->getDescribedFunctionTemplate())
14102     return false;
14103 
14104   // Don't warn about function template specializations.
14105   if (FD->isFunctionTemplateSpecialization())
14106     return false;
14107 
14108   // Don't warn for OpenCL kernels.
14109   if (FD->hasAttr<OpenCLKernelAttr>())
14110     return false;
14111 
14112   // Don't warn on explicitly deleted functions.
14113   if (FD->isDeleted())
14114     return false;
14115 
14116   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14117        Prev; Prev = Prev->getPreviousDecl()) {
14118     // Ignore any declarations that occur in function or method
14119     // scope, because they aren't visible from the header.
14120     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14121       continue;
14122 
14123     PossiblePrototype = Prev;
14124     return Prev->getType()->isFunctionNoProtoType();
14125   }
14126 
14127   return true;
14128 }
14129 
14130 void
14131 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14132                                    const FunctionDecl *EffectiveDefinition,
14133                                    SkipBodyInfo *SkipBody) {
14134   const FunctionDecl *Definition = EffectiveDefinition;
14135   if (!Definition &&
14136       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14137     return;
14138 
14139   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14140     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14141       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14142         // A merged copy of the same function, instantiated as a member of
14143         // the same class, is OK.
14144         if (declaresSameEntity(OrigFD, OrigDef) &&
14145             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14146                                cast<Decl>(FD->getLexicalDeclContext())))
14147           return;
14148       }
14149     }
14150   }
14151 
14152   if (canRedefineFunction(Definition, getLangOpts()))
14153     return;
14154 
14155   // Don't emit an error when this is redefinition of a typo-corrected
14156   // definition.
14157   if (TypoCorrectedFunctionDefinitions.count(Definition))
14158     return;
14159 
14160   // If we don't have a visible definition of the function, and it's inline or
14161   // a template, skip the new definition.
14162   if (SkipBody && !hasVisibleDefinition(Definition) &&
14163       (Definition->getFormalLinkage() == InternalLinkage ||
14164        Definition->isInlined() ||
14165        Definition->getDescribedFunctionTemplate() ||
14166        Definition->getNumTemplateParameterLists())) {
14167     SkipBody->ShouldSkip = true;
14168     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14169     if (auto *TD = Definition->getDescribedFunctionTemplate())
14170       makeMergedDefinitionVisible(TD);
14171     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14172     return;
14173   }
14174 
14175   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14176       Definition->getStorageClass() == SC_Extern)
14177     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14178         << FD << getLangOpts().CPlusPlus;
14179   else
14180     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14181 
14182   Diag(Definition->getLocation(), diag::note_previous_definition);
14183   FD->setInvalidDecl();
14184 }
14185 
14186 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14187                                    Sema &S) {
14188   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14189 
14190   LambdaScopeInfo *LSI = S.PushLambdaScope();
14191   LSI->CallOperator = CallOperator;
14192   LSI->Lambda = LambdaClass;
14193   LSI->ReturnType = CallOperator->getReturnType();
14194   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14195 
14196   if (LCD == LCD_None)
14197     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14198   else if (LCD == LCD_ByCopy)
14199     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14200   else if (LCD == LCD_ByRef)
14201     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14202   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14203 
14204   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14205   LSI->Mutable = !CallOperator->isConst();
14206 
14207   // Add the captures to the LSI so they can be noted as already
14208   // captured within tryCaptureVar.
14209   auto I = LambdaClass->field_begin();
14210   for (const auto &C : LambdaClass->captures()) {
14211     if (C.capturesVariable()) {
14212       VarDecl *VD = C.getCapturedVar();
14213       if (VD->isInitCapture())
14214         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14215       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14216       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14217           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14218           /*EllipsisLoc*/C.isPackExpansion()
14219                          ? C.getEllipsisLoc() : SourceLocation(),
14220           I->getType(), /*Invalid*/false);
14221 
14222     } else if (C.capturesThis()) {
14223       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14224                           C.getCaptureKind() == LCK_StarThis);
14225     } else {
14226       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14227                              I->getType());
14228     }
14229     ++I;
14230   }
14231 }
14232 
14233 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14234                                     SkipBodyInfo *SkipBody) {
14235   if (!D) {
14236     // Parsing the function declaration failed in some way. Push on a fake scope
14237     // anyway so we can try to parse the function body.
14238     PushFunctionScope();
14239     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14240     return D;
14241   }
14242 
14243   FunctionDecl *FD = nullptr;
14244 
14245   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14246     FD = FunTmpl->getTemplatedDecl();
14247   else
14248     FD = cast<FunctionDecl>(D);
14249 
14250   // Do not push if it is a lambda because one is already pushed when building
14251   // the lambda in ActOnStartOfLambdaDefinition().
14252   if (!isLambdaCallOperator(FD))
14253     PushExpressionEvaluationContext(
14254         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14255                           : ExprEvalContexts.back().Context);
14256 
14257   // Check for defining attributes before the check for redefinition.
14258   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14259     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14260     FD->dropAttr<AliasAttr>();
14261     FD->setInvalidDecl();
14262   }
14263   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14264     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14265     FD->dropAttr<IFuncAttr>();
14266     FD->setInvalidDecl();
14267   }
14268 
14269   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14270     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14271         Ctor->isDefaultConstructor() &&
14272         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14273       // If this is an MS ABI dllexport default constructor, instantiate any
14274       // default arguments.
14275       InstantiateDefaultCtorDefaultArgs(Ctor);
14276     }
14277   }
14278 
14279   // See if this is a redefinition. If 'will have body' (or similar) is already
14280   // set, then these checks were already performed when it was set.
14281   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14282       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14283     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14284 
14285     // If we're skipping the body, we're done. Don't enter the scope.
14286     if (SkipBody && SkipBody->ShouldSkip)
14287       return D;
14288   }
14289 
14290   // Mark this function as "will have a body eventually".  This lets users to
14291   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14292   // this function.
14293   FD->setWillHaveBody();
14294 
14295   // If we are instantiating a generic lambda call operator, push
14296   // a LambdaScopeInfo onto the function stack.  But use the information
14297   // that's already been calculated (ActOnLambdaExpr) to prime the current
14298   // LambdaScopeInfo.
14299   // When the template operator is being specialized, the LambdaScopeInfo,
14300   // has to be properly restored so that tryCaptureVariable doesn't try
14301   // and capture any new variables. In addition when calculating potential
14302   // captures during transformation of nested lambdas, it is necessary to
14303   // have the LSI properly restored.
14304   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14305     assert(inTemplateInstantiation() &&
14306            "There should be an active template instantiation on the stack "
14307            "when instantiating a generic lambda!");
14308     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14309   } else {
14310     // Enter a new function scope
14311     PushFunctionScope();
14312   }
14313 
14314   // Builtin functions cannot be defined.
14315   if (unsigned BuiltinID = FD->getBuiltinID()) {
14316     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14317         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14318       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14319       FD->setInvalidDecl();
14320     }
14321   }
14322 
14323   // The return type of a function definition must be complete
14324   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14325   QualType ResultType = FD->getReturnType();
14326   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14327       !FD->isInvalidDecl() &&
14328       RequireCompleteType(FD->getLocation(), ResultType,
14329                           diag::err_func_def_incomplete_result))
14330     FD->setInvalidDecl();
14331 
14332   if (FnBodyScope)
14333     PushDeclContext(FnBodyScope, FD);
14334 
14335   // Check the validity of our function parameters
14336   CheckParmsForFunctionDef(FD->parameters(),
14337                            /*CheckParameterNames=*/true);
14338 
14339   // Add non-parameter declarations already in the function to the current
14340   // scope.
14341   if (FnBodyScope) {
14342     for (Decl *NPD : FD->decls()) {
14343       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14344       if (!NonParmDecl)
14345         continue;
14346       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14347              "parameters should not be in newly created FD yet");
14348 
14349       // If the decl has a name, make it accessible in the current scope.
14350       if (NonParmDecl->getDeclName())
14351         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14352 
14353       // Similarly, dive into enums and fish their constants out, making them
14354       // accessible in this scope.
14355       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14356         for (auto *EI : ED->enumerators())
14357           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14358       }
14359     }
14360   }
14361 
14362   // Introduce our parameters into the function scope
14363   for (auto Param : FD->parameters()) {
14364     Param->setOwningFunction(FD);
14365 
14366     // If this has an identifier, add it to the scope stack.
14367     if (Param->getIdentifier() && FnBodyScope) {
14368       CheckShadow(FnBodyScope, Param);
14369 
14370       PushOnScopeChains(Param, FnBodyScope);
14371     }
14372   }
14373 
14374   // Ensure that the function's exception specification is instantiated.
14375   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14376     ResolveExceptionSpec(D->getLocation(), FPT);
14377 
14378   // dllimport cannot be applied to non-inline function definitions.
14379   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14380       !FD->isTemplateInstantiation()) {
14381     assert(!FD->hasAttr<DLLExportAttr>());
14382     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14383     FD->setInvalidDecl();
14384     return D;
14385   }
14386   // We want to attach documentation to original Decl (which might be
14387   // a function template).
14388   ActOnDocumentableDecl(D);
14389   if (getCurLexicalContext()->isObjCContainer() &&
14390       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14391       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14392     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14393 
14394   return D;
14395 }
14396 
14397 /// Given the set of return statements within a function body,
14398 /// compute the variables that are subject to the named return value
14399 /// optimization.
14400 ///
14401 /// Each of the variables that is subject to the named return value
14402 /// optimization will be marked as NRVO variables in the AST, and any
14403 /// return statement that has a marked NRVO variable as its NRVO candidate can
14404 /// use the named return value optimization.
14405 ///
14406 /// This function applies a very simplistic algorithm for NRVO: if every return
14407 /// statement in the scope of a variable has the same NRVO candidate, that
14408 /// candidate is an NRVO variable.
14409 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14410   ReturnStmt **Returns = Scope->Returns.data();
14411 
14412   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14413     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14414       if (!NRVOCandidate->isNRVOVariable())
14415         Returns[I]->setNRVOCandidate(nullptr);
14416     }
14417   }
14418 }
14419 
14420 bool Sema::canDelayFunctionBody(const Declarator &D) {
14421   // We can't delay parsing the body of a constexpr function template (yet).
14422   if (D.getDeclSpec().hasConstexprSpecifier())
14423     return false;
14424 
14425   // We can't delay parsing the body of a function template with a deduced
14426   // return type (yet).
14427   if (D.getDeclSpec().hasAutoTypeSpec()) {
14428     // If the placeholder introduces a non-deduced trailing return type,
14429     // we can still delay parsing it.
14430     if (D.getNumTypeObjects()) {
14431       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14432       if (Outer.Kind == DeclaratorChunk::Function &&
14433           Outer.Fun.hasTrailingReturnType()) {
14434         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14435         return Ty.isNull() || !Ty->isUndeducedType();
14436       }
14437     }
14438     return false;
14439   }
14440 
14441   return true;
14442 }
14443 
14444 bool Sema::canSkipFunctionBody(Decl *D) {
14445   // We cannot skip the body of a function (or function template) which is
14446   // constexpr, since we may need to evaluate its body in order to parse the
14447   // rest of the file.
14448   // We cannot skip the body of a function with an undeduced return type,
14449   // because any callers of that function need to know the type.
14450   if (const FunctionDecl *FD = D->getAsFunction()) {
14451     if (FD->isConstexpr())
14452       return false;
14453     // We can't simply call Type::isUndeducedType here, because inside template
14454     // auto can be deduced to a dependent type, which is not considered
14455     // "undeduced".
14456     if (FD->getReturnType()->getContainedDeducedType())
14457       return false;
14458   }
14459   return Consumer.shouldSkipFunctionBody(D);
14460 }
14461 
14462 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14463   if (!Decl)
14464     return nullptr;
14465   if (FunctionDecl *FD = Decl->getAsFunction())
14466     FD->setHasSkippedBody();
14467   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14468     MD->setHasSkippedBody();
14469   return Decl;
14470 }
14471 
14472 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14473   return ActOnFinishFunctionBody(D, BodyArg, false);
14474 }
14475 
14476 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14477 /// body.
14478 class ExitFunctionBodyRAII {
14479 public:
14480   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14481   ~ExitFunctionBodyRAII() {
14482     if (!IsLambda)
14483       S.PopExpressionEvaluationContext();
14484   }
14485 
14486 private:
14487   Sema &S;
14488   bool IsLambda = false;
14489 };
14490 
14491 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14492   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14493 
14494   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14495     if (EscapeInfo.count(BD))
14496       return EscapeInfo[BD];
14497 
14498     bool R = false;
14499     const BlockDecl *CurBD = BD;
14500 
14501     do {
14502       R = !CurBD->doesNotEscape();
14503       if (R)
14504         break;
14505       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14506     } while (CurBD);
14507 
14508     return EscapeInfo[BD] = R;
14509   };
14510 
14511   // If the location where 'self' is implicitly retained is inside a escaping
14512   // block, emit a diagnostic.
14513   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14514        S.ImplicitlyRetainedSelfLocs)
14515     if (IsOrNestedInEscapingBlock(P.second))
14516       S.Diag(P.first, diag::warn_implicitly_retains_self)
14517           << FixItHint::CreateInsertion(P.first, "self->");
14518 }
14519 
14520 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14521                                     bool IsInstantiation) {
14522   FunctionScopeInfo *FSI = getCurFunction();
14523   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14524 
14525   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14526     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14527 
14528   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14529   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14530 
14531   if (getLangOpts().Coroutines && FSI->isCoroutine())
14532     CheckCompletedCoroutineBody(FD, Body);
14533 
14534   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14535   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14536   // meant to pop the context added in ActOnStartOfFunctionDef().
14537   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14538 
14539   if (FD) {
14540     FD->setBody(Body);
14541     FD->setWillHaveBody(false);
14542 
14543     if (getLangOpts().CPlusPlus14) {
14544       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14545           FD->getReturnType()->isUndeducedType()) {
14546         // If the function has a deduced result type but contains no 'return'
14547         // statements, the result type as written must be exactly 'auto', and
14548         // the deduced result type is 'void'.
14549         if (!FD->getReturnType()->getAs<AutoType>()) {
14550           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14551               << FD->getReturnType();
14552           FD->setInvalidDecl();
14553         } else {
14554           // Substitute 'void' for the 'auto' in the type.
14555           TypeLoc ResultType = getReturnTypeLoc(FD);
14556           Context.adjustDeducedFunctionResultType(
14557               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14558         }
14559       }
14560     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14561       // In C++11, we don't use 'auto' deduction rules for lambda call
14562       // operators because we don't support return type deduction.
14563       auto *LSI = getCurLambda();
14564       if (LSI->HasImplicitReturnType) {
14565         deduceClosureReturnType(*LSI);
14566 
14567         // C++11 [expr.prim.lambda]p4:
14568         //   [...] if there are no return statements in the compound-statement
14569         //   [the deduced type is] the type void
14570         QualType RetType =
14571             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14572 
14573         // Update the return type to the deduced type.
14574         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14575         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14576                                             Proto->getExtProtoInfo()));
14577       }
14578     }
14579 
14580     // If the function implicitly returns zero (like 'main') or is naked,
14581     // don't complain about missing return statements.
14582     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14583       WP.disableCheckFallThrough();
14584 
14585     // MSVC permits the use of pure specifier (=0) on function definition,
14586     // defined at class scope, warn about this non-standard construct.
14587     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14588       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14589 
14590     if (!FD->isInvalidDecl()) {
14591       // Don't diagnose unused parameters of defaulted or deleted functions.
14592       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) {
14593         DiagnoseUnusedParameters(FD->parameters());
14594         DiagnoseUnusedButSetParameters(FD->parameters());
14595       }
14596       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14597                                              FD->getReturnType(), FD);
14598 
14599       // If this is a structor, we need a vtable.
14600       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14601         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14602       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14603         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14604 
14605       // Try to apply the named return value optimization. We have to check
14606       // if we can do this here because lambdas keep return statements around
14607       // to deduce an implicit return type.
14608       if (FD->getReturnType()->isRecordType() &&
14609           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14610         computeNRVO(Body, FSI);
14611     }
14612 
14613     // GNU warning -Wmissing-prototypes:
14614     //   Warn if a global function is defined without a previous
14615     //   prototype declaration. This warning is issued even if the
14616     //   definition itself provides a prototype. The aim is to detect
14617     //   global functions that fail to be declared in header files.
14618     const FunctionDecl *PossiblePrototype = nullptr;
14619     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14620       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14621 
14622       if (PossiblePrototype) {
14623         // We found a declaration that is not a prototype,
14624         // but that could be a zero-parameter prototype
14625         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14626           TypeLoc TL = TI->getTypeLoc();
14627           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14628             Diag(PossiblePrototype->getLocation(),
14629                  diag::note_declaration_not_a_prototype)
14630                 << (FD->getNumParams() != 0)
14631                 << (FD->getNumParams() == 0
14632                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14633                         : FixItHint{});
14634         }
14635       } else {
14636         // Returns true if the token beginning at this Loc is `const`.
14637         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14638                                 const LangOptions &LangOpts) {
14639           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14640           if (LocInfo.first.isInvalid())
14641             return false;
14642 
14643           bool Invalid = false;
14644           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14645           if (Invalid)
14646             return false;
14647 
14648           if (LocInfo.second > Buffer.size())
14649             return false;
14650 
14651           const char *LexStart = Buffer.data() + LocInfo.second;
14652           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14653 
14654           return StartTok.consume_front("const") &&
14655                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14656                   StartTok.startswith("/*") || StartTok.startswith("//"));
14657         };
14658 
14659         auto findBeginLoc = [&]() {
14660           // If the return type has `const` qualifier, we want to insert
14661           // `static` before `const` (and not before the typename).
14662           if ((FD->getReturnType()->isAnyPointerType() &&
14663                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14664               FD->getReturnType().isConstQualified()) {
14665             // But only do this if we can determine where the `const` is.
14666 
14667             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14668                              getLangOpts()))
14669 
14670               return FD->getBeginLoc();
14671           }
14672           return FD->getTypeSpecStartLoc();
14673         };
14674         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14675             << /* function */ 1
14676             << (FD->getStorageClass() == SC_None
14677                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14678                     : FixItHint{});
14679       }
14680 
14681       // GNU warning -Wstrict-prototypes
14682       //   Warn if K&R function is defined without a previous declaration.
14683       //   This warning is issued only if the definition itself does not provide
14684       //   a prototype. Only K&R definitions do not provide a prototype.
14685       if (!FD->hasWrittenPrototype()) {
14686         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14687         TypeLoc TL = TI->getTypeLoc();
14688         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14689         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14690       }
14691     }
14692 
14693     // Warn on CPUDispatch with an actual body.
14694     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14695       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14696         if (!CmpndBody->body_empty())
14697           Diag(CmpndBody->body_front()->getBeginLoc(),
14698                diag::warn_dispatch_body_ignored);
14699 
14700     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14701       const CXXMethodDecl *KeyFunction;
14702       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14703           MD->isVirtual() &&
14704           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14705           MD == KeyFunction->getCanonicalDecl()) {
14706         // Update the key-function state if necessary for this ABI.
14707         if (FD->isInlined() &&
14708             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14709           Context.setNonKeyFunction(MD);
14710 
14711           // If the newly-chosen key function is already defined, then we
14712           // need to mark the vtable as used retroactively.
14713           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14714           const FunctionDecl *Definition;
14715           if (KeyFunction && KeyFunction->isDefined(Definition))
14716             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14717         } else {
14718           // We just defined they key function; mark the vtable as used.
14719           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14720         }
14721       }
14722     }
14723 
14724     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14725            "Function parsing confused");
14726   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14727     assert(MD == getCurMethodDecl() && "Method parsing confused");
14728     MD->setBody(Body);
14729     if (!MD->isInvalidDecl()) {
14730       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14731                                              MD->getReturnType(), MD);
14732 
14733       if (Body)
14734         computeNRVO(Body, FSI);
14735     }
14736     if (FSI->ObjCShouldCallSuper) {
14737       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14738           << MD->getSelector().getAsString();
14739       FSI->ObjCShouldCallSuper = false;
14740     }
14741     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14742       const ObjCMethodDecl *InitMethod = nullptr;
14743       bool isDesignated =
14744           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14745       assert(isDesignated && InitMethod);
14746       (void)isDesignated;
14747 
14748       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14749         auto IFace = MD->getClassInterface();
14750         if (!IFace)
14751           return false;
14752         auto SuperD = IFace->getSuperClass();
14753         if (!SuperD)
14754           return false;
14755         return SuperD->getIdentifier() ==
14756             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14757       };
14758       // Don't issue this warning for unavailable inits or direct subclasses
14759       // of NSObject.
14760       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14761         Diag(MD->getLocation(),
14762              diag::warn_objc_designated_init_missing_super_call);
14763         Diag(InitMethod->getLocation(),
14764              diag::note_objc_designated_init_marked_here);
14765       }
14766       FSI->ObjCWarnForNoDesignatedInitChain = false;
14767     }
14768     if (FSI->ObjCWarnForNoInitDelegation) {
14769       // Don't issue this warning for unavaialable inits.
14770       if (!MD->isUnavailable())
14771         Diag(MD->getLocation(),
14772              diag::warn_objc_secondary_init_missing_init_call);
14773       FSI->ObjCWarnForNoInitDelegation = false;
14774     }
14775 
14776     diagnoseImplicitlyRetainedSelf(*this);
14777   } else {
14778     // Parsing the function declaration failed in some way. Pop the fake scope
14779     // we pushed on.
14780     PopFunctionScopeInfo(ActivePolicy, dcl);
14781     return nullptr;
14782   }
14783 
14784   if (Body && FSI->HasPotentialAvailabilityViolations)
14785     DiagnoseUnguardedAvailabilityViolations(dcl);
14786 
14787   assert(!FSI->ObjCShouldCallSuper &&
14788          "This should only be set for ObjC methods, which should have been "
14789          "handled in the block above.");
14790 
14791   // Verify and clean out per-function state.
14792   if (Body && (!FD || !FD->isDefaulted())) {
14793     // C++ constructors that have function-try-blocks can't have return
14794     // statements in the handlers of that block. (C++ [except.handle]p14)
14795     // Verify this.
14796     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14797       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14798 
14799     // Verify that gotos and switch cases don't jump into scopes illegally.
14800     if (FSI->NeedsScopeChecking() &&
14801         !PP.isCodeCompletionEnabled())
14802       DiagnoseInvalidJumps(Body);
14803 
14804     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14805       if (!Destructor->getParent()->isDependentType())
14806         CheckDestructor(Destructor);
14807 
14808       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14809                                              Destructor->getParent());
14810     }
14811 
14812     // If any errors have occurred, clear out any temporaries that may have
14813     // been leftover. This ensures that these temporaries won't be picked up for
14814     // deletion in some later function.
14815     if (hasUncompilableErrorOccurred() ||
14816         getDiagnostics().getSuppressAllDiagnostics()) {
14817       DiscardCleanupsInEvaluationContext();
14818     }
14819     if (!hasUncompilableErrorOccurred() &&
14820         !isa<FunctionTemplateDecl>(dcl)) {
14821       // Since the body is valid, issue any analysis-based warnings that are
14822       // enabled.
14823       ActivePolicy = &WP;
14824     }
14825 
14826     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14827         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14828       FD->setInvalidDecl();
14829 
14830     if (FD && FD->hasAttr<NakedAttr>()) {
14831       for (const Stmt *S : Body->children()) {
14832         // Allow local register variables without initializer as they don't
14833         // require prologue.
14834         bool RegisterVariables = false;
14835         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14836           for (const auto *Decl : DS->decls()) {
14837             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14838               RegisterVariables =
14839                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14840               if (!RegisterVariables)
14841                 break;
14842             }
14843           }
14844         }
14845         if (RegisterVariables)
14846           continue;
14847         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14848           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14849           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14850           FD->setInvalidDecl();
14851           break;
14852         }
14853       }
14854     }
14855 
14856     assert(ExprCleanupObjects.size() ==
14857                ExprEvalContexts.back().NumCleanupObjects &&
14858            "Leftover temporaries in function");
14859     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14860     assert(MaybeODRUseExprs.empty() &&
14861            "Leftover expressions for odr-use checking");
14862   }
14863 
14864   if (!IsInstantiation)
14865     PopDeclContext();
14866 
14867   PopFunctionScopeInfo(ActivePolicy, dcl);
14868   // If any errors have occurred, clear out any temporaries that may have
14869   // been leftover. This ensures that these temporaries won't be picked up for
14870   // deletion in some later function.
14871   if (hasUncompilableErrorOccurred()) {
14872     DiscardCleanupsInEvaluationContext();
14873   }
14874 
14875   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14876     auto ES = getEmissionStatus(FD);
14877     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14878         ES == Sema::FunctionEmissionStatus::Unknown)
14879       DeclsToCheckForDeferredDiags.push_back(FD);
14880   }
14881 
14882   return dcl;
14883 }
14884 
14885 /// When we finish delayed parsing of an attribute, we must attach it to the
14886 /// relevant Decl.
14887 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14888                                        ParsedAttributes &Attrs) {
14889   // Always attach attributes to the underlying decl.
14890   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14891     D = TD->getTemplatedDecl();
14892   ProcessDeclAttributeList(S, D, Attrs);
14893 
14894   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14895     if (Method->isStatic())
14896       checkThisInStaticMemberFunctionAttributes(Method);
14897 }
14898 
14899 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14900 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14901 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14902                                           IdentifierInfo &II, Scope *S) {
14903   // Find the scope in which the identifier is injected and the corresponding
14904   // DeclContext.
14905   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14906   // In that case, we inject the declaration into the translation unit scope
14907   // instead.
14908   Scope *BlockScope = S;
14909   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14910     BlockScope = BlockScope->getParent();
14911 
14912   Scope *ContextScope = BlockScope;
14913   while (!ContextScope->getEntity())
14914     ContextScope = ContextScope->getParent();
14915   ContextRAII SavedContext(*this, ContextScope->getEntity());
14916 
14917   // Before we produce a declaration for an implicitly defined
14918   // function, see whether there was a locally-scoped declaration of
14919   // this name as a function or variable. If so, use that
14920   // (non-visible) declaration, and complain about it.
14921   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14922   if (ExternCPrev) {
14923     // We still need to inject the function into the enclosing block scope so
14924     // that later (non-call) uses can see it.
14925     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14926 
14927     // C89 footnote 38:
14928     //   If in fact it is not defined as having type "function returning int",
14929     //   the behavior is undefined.
14930     if (!isa<FunctionDecl>(ExternCPrev) ||
14931         !Context.typesAreCompatible(
14932             cast<FunctionDecl>(ExternCPrev)->getType(),
14933             Context.getFunctionNoProtoType(Context.IntTy))) {
14934       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14935           << ExternCPrev << !getLangOpts().C99;
14936       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14937       return ExternCPrev;
14938     }
14939   }
14940 
14941   // Extension in C99.  Legal in C90, but warn about it.
14942   unsigned diag_id;
14943   if (II.getName().startswith("__builtin_"))
14944     diag_id = diag::warn_builtin_unknown;
14945   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14946   else if (getLangOpts().OpenCL)
14947     diag_id = diag::err_opencl_implicit_function_decl;
14948   else if (getLangOpts().C99)
14949     diag_id = diag::ext_implicit_function_decl;
14950   else
14951     diag_id = diag::warn_implicit_function_decl;
14952   Diag(Loc, diag_id) << &II;
14953 
14954   // If we found a prior declaration of this function, don't bother building
14955   // another one. We've already pushed that one into scope, so there's nothing
14956   // more to do.
14957   if (ExternCPrev)
14958     return ExternCPrev;
14959 
14960   // Because typo correction is expensive, only do it if the implicit
14961   // function declaration is going to be treated as an error.
14962   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14963     TypoCorrection Corrected;
14964     DeclFilterCCC<FunctionDecl> CCC{};
14965     if (S && (Corrected =
14966                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14967                               S, nullptr, CCC, CTK_NonError)))
14968       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14969                    /*ErrorRecovery*/false);
14970   }
14971 
14972   // Set a Declarator for the implicit definition: int foo();
14973   const char *Dummy;
14974   AttributeFactory attrFactory;
14975   DeclSpec DS(attrFactory);
14976   unsigned DiagID;
14977   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14978                                   Context.getPrintingPolicy());
14979   (void)Error; // Silence warning.
14980   assert(!Error && "Error setting up implicit decl!");
14981   SourceLocation NoLoc;
14982   Declarator D(DS, DeclaratorContext::Block);
14983   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14984                                              /*IsAmbiguous=*/false,
14985                                              /*LParenLoc=*/NoLoc,
14986                                              /*Params=*/nullptr,
14987                                              /*NumParams=*/0,
14988                                              /*EllipsisLoc=*/NoLoc,
14989                                              /*RParenLoc=*/NoLoc,
14990                                              /*RefQualifierIsLvalueRef=*/true,
14991                                              /*RefQualifierLoc=*/NoLoc,
14992                                              /*MutableLoc=*/NoLoc, EST_None,
14993                                              /*ESpecRange=*/SourceRange(),
14994                                              /*Exceptions=*/nullptr,
14995                                              /*ExceptionRanges=*/nullptr,
14996                                              /*NumExceptions=*/0,
14997                                              /*NoexceptExpr=*/nullptr,
14998                                              /*ExceptionSpecTokens=*/nullptr,
14999                                              /*DeclsInPrototype=*/None, Loc,
15000                                              Loc, D),
15001                 std::move(DS.getAttributes()), SourceLocation());
15002   D.SetIdentifier(&II, Loc);
15003 
15004   // Insert this function into the enclosing block scope.
15005   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15006   FD->setImplicit();
15007 
15008   AddKnownFunctionAttributes(FD);
15009 
15010   return FD;
15011 }
15012 
15013 /// If this function is a C++ replaceable global allocation function
15014 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15015 /// adds any function attributes that we know a priori based on the standard.
15016 ///
15017 /// We need to check for duplicate attributes both here and where user-written
15018 /// attributes are applied to declarations.
15019 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15020     FunctionDecl *FD) {
15021   if (FD->isInvalidDecl())
15022     return;
15023 
15024   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15025       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15026     return;
15027 
15028   Optional<unsigned> AlignmentParam;
15029   bool IsNothrow = false;
15030   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15031     return;
15032 
15033   // C++2a [basic.stc.dynamic.allocation]p4:
15034   //   An allocation function that has a non-throwing exception specification
15035   //   indicates failure by returning a null pointer value. Any other allocation
15036   //   function never returns a null pointer value and indicates failure only by
15037   //   throwing an exception [...]
15038   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15039     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15040 
15041   // C++2a [basic.stc.dynamic.allocation]p2:
15042   //   An allocation function attempts to allocate the requested amount of
15043   //   storage. [...] If the request succeeds, the value returned by a
15044   //   replaceable allocation function is a [...] pointer value p0 different
15045   //   from any previously returned value p1 [...]
15046   //
15047   // However, this particular information is being added in codegen,
15048   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15049 
15050   // C++2a [basic.stc.dynamic.allocation]p2:
15051   //   An allocation function attempts to allocate the requested amount of
15052   //   storage. If it is successful, it returns the address of the start of a
15053   //   block of storage whose length in bytes is at least as large as the
15054   //   requested size.
15055   if (!FD->hasAttr<AllocSizeAttr>()) {
15056     FD->addAttr(AllocSizeAttr::CreateImplicit(
15057         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15058         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15059   }
15060 
15061   // C++2a [basic.stc.dynamic.allocation]p3:
15062   //   For an allocation function [...], the pointer returned on a successful
15063   //   call shall represent the address of storage that is aligned as follows:
15064   //   (3.1) If the allocation function takes an argument of type
15065   //         std​::​align_­val_­t, the storage will have the alignment
15066   //         specified by the value of this argument.
15067   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15068     FD->addAttr(AllocAlignAttr::CreateImplicit(
15069         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15070   }
15071 
15072   // FIXME:
15073   // C++2a [basic.stc.dynamic.allocation]p3:
15074   //   For an allocation function [...], the pointer returned on a successful
15075   //   call shall represent the address of storage that is aligned as follows:
15076   //   (3.2) Otherwise, if the allocation function is named operator new[],
15077   //         the storage is aligned for any object that does not have
15078   //         new-extended alignment ([basic.align]) and is no larger than the
15079   //         requested size.
15080   //   (3.3) Otherwise, the storage is aligned for any object that does not
15081   //         have new-extended alignment and is of the requested size.
15082 }
15083 
15084 /// Adds any function attributes that we know a priori based on
15085 /// the declaration of this function.
15086 ///
15087 /// These attributes can apply both to implicitly-declared builtins
15088 /// (like __builtin___printf_chk) or to library-declared functions
15089 /// like NSLog or printf.
15090 ///
15091 /// We need to check for duplicate attributes both here and where user-written
15092 /// attributes are applied to declarations.
15093 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15094   if (FD->isInvalidDecl())
15095     return;
15096 
15097   // If this is a built-in function, map its builtin attributes to
15098   // actual attributes.
15099   if (unsigned BuiltinID = FD->getBuiltinID()) {
15100     // Handle printf-formatting attributes.
15101     unsigned FormatIdx;
15102     bool HasVAListArg;
15103     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15104       if (!FD->hasAttr<FormatAttr>()) {
15105         const char *fmt = "printf";
15106         unsigned int NumParams = FD->getNumParams();
15107         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15108             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15109           fmt = "NSString";
15110         FD->addAttr(FormatAttr::CreateImplicit(Context,
15111                                                &Context.Idents.get(fmt),
15112                                                FormatIdx+1,
15113                                                HasVAListArg ? 0 : FormatIdx+2,
15114                                                FD->getLocation()));
15115       }
15116     }
15117     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15118                                              HasVAListArg)) {
15119      if (!FD->hasAttr<FormatAttr>())
15120        FD->addAttr(FormatAttr::CreateImplicit(Context,
15121                                               &Context.Idents.get("scanf"),
15122                                               FormatIdx+1,
15123                                               HasVAListArg ? 0 : FormatIdx+2,
15124                                               FD->getLocation()));
15125     }
15126 
15127     // Handle automatically recognized callbacks.
15128     SmallVector<int, 4> Encoding;
15129     if (!FD->hasAttr<CallbackAttr>() &&
15130         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15131       FD->addAttr(CallbackAttr::CreateImplicit(
15132           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15133 
15134     // Mark const if we don't care about errno and that is the only thing
15135     // preventing the function from being const. This allows IRgen to use LLVM
15136     // intrinsics for such functions.
15137     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15138         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15139       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15140 
15141     // We make "fma" on some platforms const because we know it does not set
15142     // errno in those environments even though it could set errno based on the
15143     // C standard.
15144     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15145     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15146         !FD->hasAttr<ConstAttr>()) {
15147       switch (BuiltinID) {
15148       case Builtin::BI__builtin_fma:
15149       case Builtin::BI__builtin_fmaf:
15150       case Builtin::BI__builtin_fmal:
15151       case Builtin::BIfma:
15152       case Builtin::BIfmaf:
15153       case Builtin::BIfmal:
15154         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15155         break;
15156       default:
15157         break;
15158       }
15159     }
15160 
15161     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15162         !FD->hasAttr<ReturnsTwiceAttr>())
15163       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15164                                          FD->getLocation()));
15165     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15166       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15167     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15168       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15169     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15170       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15171     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15172         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15173       // Add the appropriate attribute, depending on the CUDA compilation mode
15174       // and which target the builtin belongs to. For example, during host
15175       // compilation, aux builtins are __device__, while the rest are __host__.
15176       if (getLangOpts().CUDAIsDevice !=
15177           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15178         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15179       else
15180         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15181     }
15182   }
15183 
15184   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15185 
15186   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15187   // throw, add an implicit nothrow attribute to any extern "C" function we come
15188   // across.
15189   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15190       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15191     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15192     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15193       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15194   }
15195 
15196   IdentifierInfo *Name = FD->getIdentifier();
15197   if (!Name)
15198     return;
15199   if ((!getLangOpts().CPlusPlus &&
15200        FD->getDeclContext()->isTranslationUnit()) ||
15201       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15202        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15203        LinkageSpecDecl::lang_c)) {
15204     // Okay: this could be a libc/libm/Objective-C function we know
15205     // about.
15206   } else
15207     return;
15208 
15209   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15210     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15211     // target-specific builtins, perhaps?
15212     if (!FD->hasAttr<FormatAttr>())
15213       FD->addAttr(FormatAttr::CreateImplicit(Context,
15214                                              &Context.Idents.get("printf"), 2,
15215                                              Name->isStr("vasprintf") ? 0 : 3,
15216                                              FD->getLocation()));
15217   }
15218 
15219   if (Name->isStr("__CFStringMakeConstantString")) {
15220     // We already have a __builtin___CFStringMakeConstantString,
15221     // but builds that use -fno-constant-cfstrings don't go through that.
15222     if (!FD->hasAttr<FormatArgAttr>())
15223       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15224                                                 FD->getLocation()));
15225   }
15226 }
15227 
15228 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15229                                     TypeSourceInfo *TInfo) {
15230   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15231   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15232 
15233   if (!TInfo) {
15234     assert(D.isInvalidType() && "no declarator info for valid type");
15235     TInfo = Context.getTrivialTypeSourceInfo(T);
15236   }
15237 
15238   // Scope manipulation handled by caller.
15239   TypedefDecl *NewTD =
15240       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15241                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15242 
15243   // Bail out immediately if we have an invalid declaration.
15244   if (D.isInvalidType()) {
15245     NewTD->setInvalidDecl();
15246     return NewTD;
15247   }
15248 
15249   if (D.getDeclSpec().isModulePrivateSpecified()) {
15250     if (CurContext->isFunctionOrMethod())
15251       Diag(NewTD->getLocation(), diag::err_module_private_local)
15252           << 2 << NewTD
15253           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15254           << FixItHint::CreateRemoval(
15255                  D.getDeclSpec().getModulePrivateSpecLoc());
15256     else
15257       NewTD->setModulePrivate();
15258   }
15259 
15260   // C++ [dcl.typedef]p8:
15261   //   If the typedef declaration defines an unnamed class (or
15262   //   enum), the first typedef-name declared by the declaration
15263   //   to be that class type (or enum type) is used to denote the
15264   //   class type (or enum type) for linkage purposes only.
15265   // We need to check whether the type was declared in the declaration.
15266   switch (D.getDeclSpec().getTypeSpecType()) {
15267   case TST_enum:
15268   case TST_struct:
15269   case TST_interface:
15270   case TST_union:
15271   case TST_class: {
15272     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15273     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15274     break;
15275   }
15276 
15277   default:
15278     break;
15279   }
15280 
15281   return NewTD;
15282 }
15283 
15284 /// Check that this is a valid underlying type for an enum declaration.
15285 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15286   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15287   QualType T = TI->getType();
15288 
15289   if (T->isDependentType())
15290     return false;
15291 
15292   // This doesn't use 'isIntegralType' despite the error message mentioning
15293   // integral type because isIntegralType would also allow enum types in C.
15294   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15295     if (BT->isInteger())
15296       return false;
15297 
15298   if (T->isExtIntType())
15299     return false;
15300 
15301   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15302 }
15303 
15304 /// Check whether this is a valid redeclaration of a previous enumeration.
15305 /// \return true if the redeclaration was invalid.
15306 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15307                                   QualType EnumUnderlyingTy, bool IsFixed,
15308                                   const EnumDecl *Prev) {
15309   if (IsScoped != Prev->isScoped()) {
15310     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15311       << Prev->isScoped();
15312     Diag(Prev->getLocation(), diag::note_previous_declaration);
15313     return true;
15314   }
15315 
15316   if (IsFixed && Prev->isFixed()) {
15317     if (!EnumUnderlyingTy->isDependentType() &&
15318         !Prev->getIntegerType()->isDependentType() &&
15319         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15320                                         Prev->getIntegerType())) {
15321       // TODO: Highlight the underlying type of the redeclaration.
15322       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15323         << EnumUnderlyingTy << Prev->getIntegerType();
15324       Diag(Prev->getLocation(), diag::note_previous_declaration)
15325           << Prev->getIntegerTypeRange();
15326       return true;
15327     }
15328   } else if (IsFixed != Prev->isFixed()) {
15329     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15330       << Prev->isFixed();
15331     Diag(Prev->getLocation(), diag::note_previous_declaration);
15332     return true;
15333   }
15334 
15335   return false;
15336 }
15337 
15338 /// Get diagnostic %select index for tag kind for
15339 /// redeclaration diagnostic message.
15340 /// WARNING: Indexes apply to particular diagnostics only!
15341 ///
15342 /// \returns diagnostic %select index.
15343 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15344   switch (Tag) {
15345   case TTK_Struct: return 0;
15346   case TTK_Interface: return 1;
15347   case TTK_Class:  return 2;
15348   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15349   }
15350 }
15351 
15352 /// Determine if tag kind is a class-key compatible with
15353 /// class for redeclaration (class, struct, or __interface).
15354 ///
15355 /// \returns true iff the tag kind is compatible.
15356 static bool isClassCompatTagKind(TagTypeKind Tag)
15357 {
15358   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15359 }
15360 
15361 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15362                                              TagTypeKind TTK) {
15363   if (isa<TypedefDecl>(PrevDecl))
15364     return NTK_Typedef;
15365   else if (isa<TypeAliasDecl>(PrevDecl))
15366     return NTK_TypeAlias;
15367   else if (isa<ClassTemplateDecl>(PrevDecl))
15368     return NTK_Template;
15369   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15370     return NTK_TypeAliasTemplate;
15371   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15372     return NTK_TemplateTemplateArgument;
15373   switch (TTK) {
15374   case TTK_Struct:
15375   case TTK_Interface:
15376   case TTK_Class:
15377     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15378   case TTK_Union:
15379     return NTK_NonUnion;
15380   case TTK_Enum:
15381     return NTK_NonEnum;
15382   }
15383   llvm_unreachable("invalid TTK");
15384 }
15385 
15386 /// Determine whether a tag with a given kind is acceptable
15387 /// as a redeclaration of the given tag declaration.
15388 ///
15389 /// \returns true if the new tag kind is acceptable, false otherwise.
15390 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15391                                         TagTypeKind NewTag, bool isDefinition,
15392                                         SourceLocation NewTagLoc,
15393                                         const IdentifierInfo *Name) {
15394   // C++ [dcl.type.elab]p3:
15395   //   The class-key or enum keyword present in the
15396   //   elaborated-type-specifier shall agree in kind with the
15397   //   declaration to which the name in the elaborated-type-specifier
15398   //   refers. This rule also applies to the form of
15399   //   elaborated-type-specifier that declares a class-name or
15400   //   friend class since it can be construed as referring to the
15401   //   definition of the class. Thus, in any
15402   //   elaborated-type-specifier, the enum keyword shall be used to
15403   //   refer to an enumeration (7.2), the union class-key shall be
15404   //   used to refer to a union (clause 9), and either the class or
15405   //   struct class-key shall be used to refer to a class (clause 9)
15406   //   declared using the class or struct class-key.
15407   TagTypeKind OldTag = Previous->getTagKind();
15408   if (OldTag != NewTag &&
15409       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15410     return false;
15411 
15412   // Tags are compatible, but we might still want to warn on mismatched tags.
15413   // Non-class tags can't be mismatched at this point.
15414   if (!isClassCompatTagKind(NewTag))
15415     return true;
15416 
15417   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15418   // by our warning analysis. We don't want to warn about mismatches with (eg)
15419   // declarations in system headers that are designed to be specialized, but if
15420   // a user asks us to warn, we should warn if their code contains mismatched
15421   // declarations.
15422   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15423     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15424                                       Loc);
15425   };
15426   if (IsIgnoredLoc(NewTagLoc))
15427     return true;
15428 
15429   auto IsIgnored = [&](const TagDecl *Tag) {
15430     return IsIgnoredLoc(Tag->getLocation());
15431   };
15432   while (IsIgnored(Previous)) {
15433     Previous = Previous->getPreviousDecl();
15434     if (!Previous)
15435       return true;
15436     OldTag = Previous->getTagKind();
15437   }
15438 
15439   bool isTemplate = false;
15440   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15441     isTemplate = Record->getDescribedClassTemplate();
15442 
15443   if (inTemplateInstantiation()) {
15444     if (OldTag != NewTag) {
15445       // In a template instantiation, do not offer fix-its for tag mismatches
15446       // since they usually mess up the template instead of fixing the problem.
15447       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15448         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15449         << getRedeclDiagFromTagKind(OldTag);
15450       // FIXME: Note previous location?
15451     }
15452     return true;
15453   }
15454 
15455   if (isDefinition) {
15456     // On definitions, check all previous tags and issue a fix-it for each
15457     // one that doesn't match the current tag.
15458     if (Previous->getDefinition()) {
15459       // Don't suggest fix-its for redefinitions.
15460       return true;
15461     }
15462 
15463     bool previousMismatch = false;
15464     for (const TagDecl *I : Previous->redecls()) {
15465       if (I->getTagKind() != NewTag) {
15466         // Ignore previous declarations for which the warning was disabled.
15467         if (IsIgnored(I))
15468           continue;
15469 
15470         if (!previousMismatch) {
15471           previousMismatch = true;
15472           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15473             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15474             << getRedeclDiagFromTagKind(I->getTagKind());
15475         }
15476         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15477           << getRedeclDiagFromTagKind(NewTag)
15478           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15479                TypeWithKeyword::getTagTypeKindName(NewTag));
15480       }
15481     }
15482     return true;
15483   }
15484 
15485   // Identify the prevailing tag kind: this is the kind of the definition (if
15486   // there is a non-ignored definition), or otherwise the kind of the prior
15487   // (non-ignored) declaration.
15488   const TagDecl *PrevDef = Previous->getDefinition();
15489   if (PrevDef && IsIgnored(PrevDef))
15490     PrevDef = nullptr;
15491   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15492   if (Redecl->getTagKind() != NewTag) {
15493     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15494       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15495       << getRedeclDiagFromTagKind(OldTag);
15496     Diag(Redecl->getLocation(), diag::note_previous_use);
15497 
15498     // If there is a previous definition, suggest a fix-it.
15499     if (PrevDef) {
15500       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15501         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15502         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15503              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15504     }
15505   }
15506 
15507   return true;
15508 }
15509 
15510 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15511 /// from an outer enclosing namespace or file scope inside a friend declaration.
15512 /// This should provide the commented out code in the following snippet:
15513 ///   namespace N {
15514 ///     struct X;
15515 ///     namespace M {
15516 ///       struct Y { friend struct /*N::*/ X; };
15517 ///     }
15518 ///   }
15519 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15520                                          SourceLocation NameLoc) {
15521   // While the decl is in a namespace, do repeated lookup of that name and see
15522   // if we get the same namespace back.  If we do not, continue until
15523   // translation unit scope, at which point we have a fully qualified NNS.
15524   SmallVector<IdentifierInfo *, 4> Namespaces;
15525   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15526   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15527     // This tag should be declared in a namespace, which can only be enclosed by
15528     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15529     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15530     if (!Namespace || Namespace->isAnonymousNamespace())
15531       return FixItHint();
15532     IdentifierInfo *II = Namespace->getIdentifier();
15533     Namespaces.push_back(II);
15534     NamedDecl *Lookup = SemaRef.LookupSingleName(
15535         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15536     if (Lookup == Namespace)
15537       break;
15538   }
15539 
15540   // Once we have all the namespaces, reverse them to go outermost first, and
15541   // build an NNS.
15542   SmallString<64> Insertion;
15543   llvm::raw_svector_ostream OS(Insertion);
15544   if (DC->isTranslationUnit())
15545     OS << "::";
15546   std::reverse(Namespaces.begin(), Namespaces.end());
15547   for (auto *II : Namespaces)
15548     OS << II->getName() << "::";
15549   return FixItHint::CreateInsertion(NameLoc, Insertion);
15550 }
15551 
15552 /// Determine whether a tag originally declared in context \p OldDC can
15553 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15554 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15555 /// using-declaration).
15556 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15557                                          DeclContext *NewDC) {
15558   OldDC = OldDC->getRedeclContext();
15559   NewDC = NewDC->getRedeclContext();
15560 
15561   if (OldDC->Equals(NewDC))
15562     return true;
15563 
15564   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15565   // encloses the other).
15566   if (S.getLangOpts().MSVCCompat &&
15567       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15568     return true;
15569 
15570   return false;
15571 }
15572 
15573 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15574 /// former case, Name will be non-null.  In the later case, Name will be null.
15575 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15576 /// reference/declaration/definition of a tag.
15577 ///
15578 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15579 /// trailing-type-specifier) other than one in an alias-declaration.
15580 ///
15581 /// \param SkipBody If non-null, will be set to indicate if the caller should
15582 /// skip the definition of this tag and treat it as if it were a declaration.
15583 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15584                      SourceLocation KWLoc, CXXScopeSpec &SS,
15585                      IdentifierInfo *Name, SourceLocation NameLoc,
15586                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15587                      SourceLocation ModulePrivateLoc,
15588                      MultiTemplateParamsArg TemplateParameterLists,
15589                      bool &OwnedDecl, bool &IsDependent,
15590                      SourceLocation ScopedEnumKWLoc,
15591                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15592                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15593                      SkipBodyInfo *SkipBody) {
15594   // If this is not a definition, it must have a name.
15595   IdentifierInfo *OrigName = Name;
15596   assert((Name != nullptr || TUK == TUK_Definition) &&
15597          "Nameless record must be a definition!");
15598   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15599 
15600   OwnedDecl = false;
15601   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15602   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15603 
15604   // FIXME: Check member specializations more carefully.
15605   bool isMemberSpecialization = false;
15606   bool Invalid = false;
15607 
15608   // We only need to do this matching if we have template parameters
15609   // or a scope specifier, which also conveniently avoids this work
15610   // for non-C++ cases.
15611   if (TemplateParameterLists.size() > 0 ||
15612       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15613     if (TemplateParameterList *TemplateParams =
15614             MatchTemplateParametersToScopeSpecifier(
15615                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15616                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15617       if (Kind == TTK_Enum) {
15618         Diag(KWLoc, diag::err_enum_template);
15619         return nullptr;
15620       }
15621 
15622       if (TemplateParams->size() > 0) {
15623         // This is a declaration or definition of a class template (which may
15624         // be a member of another template).
15625 
15626         if (Invalid)
15627           return nullptr;
15628 
15629         OwnedDecl = false;
15630         DeclResult Result = CheckClassTemplate(
15631             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15632             AS, ModulePrivateLoc,
15633             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15634             TemplateParameterLists.data(), SkipBody);
15635         return Result.get();
15636       } else {
15637         // The "template<>" header is extraneous.
15638         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15639           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15640         isMemberSpecialization = true;
15641       }
15642     }
15643 
15644     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15645         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15646       return nullptr;
15647   }
15648 
15649   // Figure out the underlying type if this a enum declaration. We need to do
15650   // this early, because it's needed to detect if this is an incompatible
15651   // redeclaration.
15652   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15653   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15654 
15655   if (Kind == TTK_Enum) {
15656     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15657       // No underlying type explicitly specified, or we failed to parse the
15658       // type, default to int.
15659       EnumUnderlying = Context.IntTy.getTypePtr();
15660     } else if (UnderlyingType.get()) {
15661       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15662       // integral type; any cv-qualification is ignored.
15663       TypeSourceInfo *TI = nullptr;
15664       GetTypeFromParser(UnderlyingType.get(), &TI);
15665       EnumUnderlying = TI;
15666 
15667       if (CheckEnumUnderlyingType(TI))
15668         // Recover by falling back to int.
15669         EnumUnderlying = Context.IntTy.getTypePtr();
15670 
15671       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15672                                           UPPC_FixedUnderlyingType))
15673         EnumUnderlying = Context.IntTy.getTypePtr();
15674 
15675     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15676       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15677       // of 'int'. However, if this is an unfixed forward declaration, don't set
15678       // the underlying type unless the user enables -fms-compatibility. This
15679       // makes unfixed forward declared enums incomplete and is more conforming.
15680       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15681         EnumUnderlying = Context.IntTy.getTypePtr();
15682     }
15683   }
15684 
15685   DeclContext *SearchDC = CurContext;
15686   DeclContext *DC = CurContext;
15687   bool isStdBadAlloc = false;
15688   bool isStdAlignValT = false;
15689 
15690   RedeclarationKind Redecl = forRedeclarationInCurContext();
15691   if (TUK == TUK_Friend || TUK == TUK_Reference)
15692     Redecl = NotForRedeclaration;
15693 
15694   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15695   /// implemented asks for structural equivalence checking, the returned decl
15696   /// here is passed back to the parser, allowing the tag body to be parsed.
15697   auto createTagFromNewDecl = [&]() -> TagDecl * {
15698     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15699     // If there is an identifier, use the location of the identifier as the
15700     // location of the decl, otherwise use the location of the struct/union
15701     // keyword.
15702     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15703     TagDecl *New = nullptr;
15704 
15705     if (Kind == TTK_Enum) {
15706       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15707                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15708       // If this is an undefined enum, bail.
15709       if (TUK != TUK_Definition && !Invalid)
15710         return nullptr;
15711       if (EnumUnderlying) {
15712         EnumDecl *ED = cast<EnumDecl>(New);
15713         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15714           ED->setIntegerTypeSourceInfo(TI);
15715         else
15716           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15717         ED->setPromotionType(ED->getIntegerType());
15718       }
15719     } else { // struct/union
15720       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15721                                nullptr);
15722     }
15723 
15724     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15725       // Add alignment attributes if necessary; these attributes are checked
15726       // when the ASTContext lays out the structure.
15727       //
15728       // It is important for implementing the correct semantics that this
15729       // happen here (in ActOnTag). The #pragma pack stack is
15730       // maintained as a result of parser callbacks which can occur at
15731       // many points during the parsing of a struct declaration (because
15732       // the #pragma tokens are effectively skipped over during the
15733       // parsing of the struct).
15734       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15735         AddAlignmentAttributesForRecord(RD);
15736         AddMsStructLayoutForRecord(RD);
15737       }
15738     }
15739     New->setLexicalDeclContext(CurContext);
15740     return New;
15741   };
15742 
15743   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15744   if (Name && SS.isNotEmpty()) {
15745     // We have a nested-name tag ('struct foo::bar').
15746 
15747     // Check for invalid 'foo::'.
15748     if (SS.isInvalid()) {
15749       Name = nullptr;
15750       goto CreateNewDecl;
15751     }
15752 
15753     // If this is a friend or a reference to a class in a dependent
15754     // context, don't try to make a decl for it.
15755     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15756       DC = computeDeclContext(SS, false);
15757       if (!DC) {
15758         IsDependent = true;
15759         return nullptr;
15760       }
15761     } else {
15762       DC = computeDeclContext(SS, true);
15763       if (!DC) {
15764         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15765           << SS.getRange();
15766         return nullptr;
15767       }
15768     }
15769 
15770     if (RequireCompleteDeclContext(SS, DC))
15771       return nullptr;
15772 
15773     SearchDC = DC;
15774     // Look-up name inside 'foo::'.
15775     LookupQualifiedName(Previous, DC);
15776 
15777     if (Previous.isAmbiguous())
15778       return nullptr;
15779 
15780     if (Previous.empty()) {
15781       // Name lookup did not find anything. However, if the
15782       // nested-name-specifier refers to the current instantiation,
15783       // and that current instantiation has any dependent base
15784       // classes, we might find something at instantiation time: treat
15785       // this as a dependent elaborated-type-specifier.
15786       // But this only makes any sense for reference-like lookups.
15787       if (Previous.wasNotFoundInCurrentInstantiation() &&
15788           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15789         IsDependent = true;
15790         return nullptr;
15791       }
15792 
15793       // A tag 'foo::bar' must already exist.
15794       Diag(NameLoc, diag::err_not_tag_in_scope)
15795         << Kind << Name << DC << SS.getRange();
15796       Name = nullptr;
15797       Invalid = true;
15798       goto CreateNewDecl;
15799     }
15800   } else if (Name) {
15801     // C++14 [class.mem]p14:
15802     //   If T is the name of a class, then each of the following shall have a
15803     //   name different from T:
15804     //    -- every member of class T that is itself a type
15805     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15806         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15807       return nullptr;
15808 
15809     // If this is a named struct, check to see if there was a previous forward
15810     // declaration or definition.
15811     // FIXME: We're looking into outer scopes here, even when we
15812     // shouldn't be. Doing so can result in ambiguities that we
15813     // shouldn't be diagnosing.
15814     LookupName(Previous, S);
15815 
15816     // When declaring or defining a tag, ignore ambiguities introduced
15817     // by types using'ed into this scope.
15818     if (Previous.isAmbiguous() &&
15819         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15820       LookupResult::Filter F = Previous.makeFilter();
15821       while (F.hasNext()) {
15822         NamedDecl *ND = F.next();
15823         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15824                 SearchDC->getRedeclContext()))
15825           F.erase();
15826       }
15827       F.done();
15828     }
15829 
15830     // C++11 [namespace.memdef]p3:
15831     //   If the name in a friend declaration is neither qualified nor
15832     //   a template-id and the declaration is a function or an
15833     //   elaborated-type-specifier, the lookup to determine whether
15834     //   the entity has been previously declared shall not consider
15835     //   any scopes outside the innermost enclosing namespace.
15836     //
15837     // MSVC doesn't implement the above rule for types, so a friend tag
15838     // declaration may be a redeclaration of a type declared in an enclosing
15839     // scope.  They do implement this rule for friend functions.
15840     //
15841     // Does it matter that this should be by scope instead of by
15842     // semantic context?
15843     if (!Previous.empty() && TUK == TUK_Friend) {
15844       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15845       LookupResult::Filter F = Previous.makeFilter();
15846       bool FriendSawTagOutsideEnclosingNamespace = false;
15847       while (F.hasNext()) {
15848         NamedDecl *ND = F.next();
15849         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15850         if (DC->isFileContext() &&
15851             !EnclosingNS->Encloses(ND->getDeclContext())) {
15852           if (getLangOpts().MSVCCompat)
15853             FriendSawTagOutsideEnclosingNamespace = true;
15854           else
15855             F.erase();
15856         }
15857       }
15858       F.done();
15859 
15860       // Diagnose this MSVC extension in the easy case where lookup would have
15861       // unambiguously found something outside the enclosing namespace.
15862       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15863         NamedDecl *ND = Previous.getFoundDecl();
15864         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15865             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15866       }
15867     }
15868 
15869     // Note:  there used to be some attempt at recovery here.
15870     if (Previous.isAmbiguous())
15871       return nullptr;
15872 
15873     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15874       // FIXME: This makes sure that we ignore the contexts associated
15875       // with C structs, unions, and enums when looking for a matching
15876       // tag declaration or definition. See the similar lookup tweak
15877       // in Sema::LookupName; is there a better way to deal with this?
15878       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15879         SearchDC = SearchDC->getParent();
15880     }
15881   }
15882 
15883   if (Previous.isSingleResult() &&
15884       Previous.getFoundDecl()->isTemplateParameter()) {
15885     // Maybe we will complain about the shadowed template parameter.
15886     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15887     // Just pretend that we didn't see the previous declaration.
15888     Previous.clear();
15889   }
15890 
15891   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15892       DC->Equals(getStdNamespace())) {
15893     if (Name->isStr("bad_alloc")) {
15894       // This is a declaration of or a reference to "std::bad_alloc".
15895       isStdBadAlloc = true;
15896 
15897       // If std::bad_alloc has been implicitly declared (but made invisible to
15898       // name lookup), fill in this implicit declaration as the previous
15899       // declaration, so that the declarations get chained appropriately.
15900       if (Previous.empty() && StdBadAlloc)
15901         Previous.addDecl(getStdBadAlloc());
15902     } else if (Name->isStr("align_val_t")) {
15903       isStdAlignValT = true;
15904       if (Previous.empty() && StdAlignValT)
15905         Previous.addDecl(getStdAlignValT());
15906     }
15907   }
15908 
15909   // If we didn't find a previous declaration, and this is a reference
15910   // (or friend reference), move to the correct scope.  In C++, we
15911   // also need to do a redeclaration lookup there, just in case
15912   // there's a shadow friend decl.
15913   if (Name && Previous.empty() &&
15914       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15915     if (Invalid) goto CreateNewDecl;
15916     assert(SS.isEmpty());
15917 
15918     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15919       // C++ [basic.scope.pdecl]p5:
15920       //   -- for an elaborated-type-specifier of the form
15921       //
15922       //          class-key identifier
15923       //
15924       //      if the elaborated-type-specifier is used in the
15925       //      decl-specifier-seq or parameter-declaration-clause of a
15926       //      function defined in namespace scope, the identifier is
15927       //      declared as a class-name in the namespace that contains
15928       //      the declaration; otherwise, except as a friend
15929       //      declaration, the identifier is declared in the smallest
15930       //      non-class, non-function-prototype scope that contains the
15931       //      declaration.
15932       //
15933       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15934       // C structs and unions.
15935       //
15936       // It is an error in C++ to declare (rather than define) an enum
15937       // type, including via an elaborated type specifier.  We'll
15938       // diagnose that later; for now, declare the enum in the same
15939       // scope as we would have picked for any other tag type.
15940       //
15941       // GNU C also supports this behavior as part of its incomplete
15942       // enum types extension, while GNU C++ does not.
15943       //
15944       // Find the context where we'll be declaring the tag.
15945       // FIXME: We would like to maintain the current DeclContext as the
15946       // lexical context,
15947       SearchDC = getTagInjectionContext(SearchDC);
15948 
15949       // Find the scope where we'll be declaring the tag.
15950       S = getTagInjectionScope(S, getLangOpts());
15951     } else {
15952       assert(TUK == TUK_Friend);
15953       // C++ [namespace.memdef]p3:
15954       //   If a friend declaration in a non-local class first declares a
15955       //   class or function, the friend class or function is a member of
15956       //   the innermost enclosing namespace.
15957       SearchDC = SearchDC->getEnclosingNamespaceContext();
15958     }
15959 
15960     // In C++, we need to do a redeclaration lookup to properly
15961     // diagnose some problems.
15962     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15963     // hidden declaration so that we don't get ambiguity errors when using a
15964     // type declared by an elaborated-type-specifier.  In C that is not correct
15965     // and we should instead merge compatible types found by lookup.
15966     if (getLangOpts().CPlusPlus) {
15967       // FIXME: This can perform qualified lookups into function contexts,
15968       // which are meaningless.
15969       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15970       LookupQualifiedName(Previous, SearchDC);
15971     } else {
15972       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15973       LookupName(Previous, S);
15974     }
15975   }
15976 
15977   // If we have a known previous declaration to use, then use it.
15978   if (Previous.empty() && SkipBody && SkipBody->Previous)
15979     Previous.addDecl(SkipBody->Previous);
15980 
15981   if (!Previous.empty()) {
15982     NamedDecl *PrevDecl = Previous.getFoundDecl();
15983     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15984 
15985     // It's okay to have a tag decl in the same scope as a typedef
15986     // which hides a tag decl in the same scope.  Finding this
15987     // insanity with a redeclaration lookup can only actually happen
15988     // in C++.
15989     //
15990     // This is also okay for elaborated-type-specifiers, which is
15991     // technically forbidden by the current standard but which is
15992     // okay according to the likely resolution of an open issue;
15993     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15994     if (getLangOpts().CPlusPlus) {
15995       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15996         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15997           TagDecl *Tag = TT->getDecl();
15998           if (Tag->getDeclName() == Name &&
15999               Tag->getDeclContext()->getRedeclContext()
16000                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16001             PrevDecl = Tag;
16002             Previous.clear();
16003             Previous.addDecl(Tag);
16004             Previous.resolveKind();
16005           }
16006         }
16007       }
16008     }
16009 
16010     // If this is a redeclaration of a using shadow declaration, it must
16011     // declare a tag in the same context. In MSVC mode, we allow a
16012     // redefinition if either context is within the other.
16013     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16014       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16015       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16016           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16017           !(OldTag && isAcceptableTagRedeclContext(
16018                           *this, OldTag->getDeclContext(), SearchDC))) {
16019         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16020         Diag(Shadow->getTargetDecl()->getLocation(),
16021              diag::note_using_decl_target);
16022         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
16023             << 0;
16024         // Recover by ignoring the old declaration.
16025         Previous.clear();
16026         goto CreateNewDecl;
16027       }
16028     }
16029 
16030     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16031       // If this is a use of a previous tag, or if the tag is already declared
16032       // in the same scope (so that the definition/declaration completes or
16033       // rementions the tag), reuse the decl.
16034       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16035           isDeclInScope(DirectPrevDecl, SearchDC, S,
16036                         SS.isNotEmpty() || isMemberSpecialization)) {
16037         // Make sure that this wasn't declared as an enum and now used as a
16038         // struct or something similar.
16039         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16040                                           TUK == TUK_Definition, KWLoc,
16041                                           Name)) {
16042           bool SafeToContinue
16043             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16044                Kind != TTK_Enum);
16045           if (SafeToContinue)
16046             Diag(KWLoc, diag::err_use_with_wrong_tag)
16047               << Name
16048               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16049                                               PrevTagDecl->getKindName());
16050           else
16051             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16052           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16053 
16054           if (SafeToContinue)
16055             Kind = PrevTagDecl->getTagKind();
16056           else {
16057             // Recover by making this an anonymous redefinition.
16058             Name = nullptr;
16059             Previous.clear();
16060             Invalid = true;
16061           }
16062         }
16063 
16064         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16065           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16066           if (TUK == TUK_Reference || TUK == TUK_Friend)
16067             return PrevTagDecl;
16068 
16069           QualType EnumUnderlyingTy;
16070           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16071             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16072           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16073             EnumUnderlyingTy = QualType(T, 0);
16074 
16075           // All conflicts with previous declarations are recovered by
16076           // returning the previous declaration, unless this is a definition,
16077           // in which case we want the caller to bail out.
16078           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16079                                      ScopedEnum, EnumUnderlyingTy,
16080                                      IsFixed, PrevEnum))
16081             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16082         }
16083 
16084         // C++11 [class.mem]p1:
16085         //   A member shall not be declared twice in the member-specification,
16086         //   except that a nested class or member class template can be declared
16087         //   and then later defined.
16088         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16089             S->isDeclScope(PrevDecl)) {
16090           Diag(NameLoc, diag::ext_member_redeclared);
16091           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16092         }
16093 
16094         if (!Invalid) {
16095           // If this is a use, just return the declaration we found, unless
16096           // we have attributes.
16097           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16098             if (!Attrs.empty()) {
16099               // FIXME: Diagnose these attributes. For now, we create a new
16100               // declaration to hold them.
16101             } else if (TUK == TUK_Reference &&
16102                        (PrevTagDecl->getFriendObjectKind() ==
16103                             Decl::FOK_Undeclared ||
16104                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16105                        SS.isEmpty()) {
16106               // This declaration is a reference to an existing entity, but
16107               // has different visibility from that entity: it either makes
16108               // a friend visible or it makes a type visible in a new module.
16109               // In either case, create a new declaration. We only do this if
16110               // the declaration would have meant the same thing if no prior
16111               // declaration were found, that is, if it was found in the same
16112               // scope where we would have injected a declaration.
16113               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16114                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16115                 return PrevTagDecl;
16116               // This is in the injected scope, create a new declaration in
16117               // that scope.
16118               S = getTagInjectionScope(S, getLangOpts());
16119             } else {
16120               return PrevTagDecl;
16121             }
16122           }
16123 
16124           // Diagnose attempts to redefine a tag.
16125           if (TUK == TUK_Definition) {
16126             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16127               // If we're defining a specialization and the previous definition
16128               // is from an implicit instantiation, don't emit an error
16129               // here; we'll catch this in the general case below.
16130               bool IsExplicitSpecializationAfterInstantiation = false;
16131               if (isMemberSpecialization) {
16132                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16133                   IsExplicitSpecializationAfterInstantiation =
16134                     RD->getTemplateSpecializationKind() !=
16135                     TSK_ExplicitSpecialization;
16136                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16137                   IsExplicitSpecializationAfterInstantiation =
16138                     ED->getTemplateSpecializationKind() !=
16139                     TSK_ExplicitSpecialization;
16140               }
16141 
16142               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16143               // not keep more that one definition around (merge them). However,
16144               // ensure the decl passes the structural compatibility check in
16145               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16146               NamedDecl *Hidden = nullptr;
16147               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16148                 // There is a definition of this tag, but it is not visible. We
16149                 // explicitly make use of C++'s one definition rule here, and
16150                 // assume that this definition is identical to the hidden one
16151                 // we already have. Make the existing definition visible and
16152                 // use it in place of this one.
16153                 if (!getLangOpts().CPlusPlus) {
16154                   // Postpone making the old definition visible until after we
16155                   // complete parsing the new one and do the structural
16156                   // comparison.
16157                   SkipBody->CheckSameAsPrevious = true;
16158                   SkipBody->New = createTagFromNewDecl();
16159                   SkipBody->Previous = Def;
16160                   return Def;
16161                 } else {
16162                   SkipBody->ShouldSkip = true;
16163                   SkipBody->Previous = Def;
16164                   makeMergedDefinitionVisible(Hidden);
16165                   // Carry on and handle it like a normal definition. We'll
16166                   // skip starting the definitiion later.
16167                 }
16168               } else if (!IsExplicitSpecializationAfterInstantiation) {
16169                 // A redeclaration in function prototype scope in C isn't
16170                 // visible elsewhere, so merely issue a warning.
16171                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16172                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16173                 else
16174                   Diag(NameLoc, diag::err_redefinition) << Name;
16175                 notePreviousDefinition(Def,
16176                                        NameLoc.isValid() ? NameLoc : KWLoc);
16177                 // If this is a redefinition, recover by making this
16178                 // struct be anonymous, which will make any later
16179                 // references get the previous definition.
16180                 Name = nullptr;
16181                 Previous.clear();
16182                 Invalid = true;
16183               }
16184             } else {
16185               // If the type is currently being defined, complain
16186               // about a nested redefinition.
16187               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16188               if (TD->isBeingDefined()) {
16189                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16190                 Diag(PrevTagDecl->getLocation(),
16191                      diag::note_previous_definition);
16192                 Name = nullptr;
16193                 Previous.clear();
16194                 Invalid = true;
16195               }
16196             }
16197 
16198             // Okay, this is definition of a previously declared or referenced
16199             // tag. We're going to create a new Decl for it.
16200           }
16201 
16202           // Okay, we're going to make a redeclaration.  If this is some kind
16203           // of reference, make sure we build the redeclaration in the same DC
16204           // as the original, and ignore the current access specifier.
16205           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16206             SearchDC = PrevTagDecl->getDeclContext();
16207             AS = AS_none;
16208           }
16209         }
16210         // If we get here we have (another) forward declaration or we
16211         // have a definition.  Just create a new decl.
16212 
16213       } else {
16214         // If we get here, this is a definition of a new tag type in a nested
16215         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16216         // new decl/type.  We set PrevDecl to NULL so that the entities
16217         // have distinct types.
16218         Previous.clear();
16219       }
16220       // If we get here, we're going to create a new Decl. If PrevDecl
16221       // is non-NULL, it's a definition of the tag declared by
16222       // PrevDecl. If it's NULL, we have a new definition.
16223 
16224     // Otherwise, PrevDecl is not a tag, but was found with tag
16225     // lookup.  This is only actually possible in C++, where a few
16226     // things like templates still live in the tag namespace.
16227     } else {
16228       // Use a better diagnostic if an elaborated-type-specifier
16229       // found the wrong kind of type on the first
16230       // (non-redeclaration) lookup.
16231       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16232           !Previous.isForRedeclaration()) {
16233         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16234         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16235                                                        << Kind;
16236         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16237         Invalid = true;
16238 
16239       // Otherwise, only diagnose if the declaration is in scope.
16240       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16241                                 SS.isNotEmpty() || isMemberSpecialization)) {
16242         // do nothing
16243 
16244       // Diagnose implicit declarations introduced by elaborated types.
16245       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16246         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16247         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16248         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16249         Invalid = true;
16250 
16251       // Otherwise it's a declaration.  Call out a particularly common
16252       // case here.
16253       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16254         unsigned Kind = 0;
16255         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16256         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16257           << Name << Kind << TND->getUnderlyingType();
16258         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16259         Invalid = true;
16260 
16261       // Otherwise, diagnose.
16262       } else {
16263         // The tag name clashes with something else in the target scope,
16264         // issue an error and recover by making this tag be anonymous.
16265         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16266         notePreviousDefinition(PrevDecl, NameLoc);
16267         Name = nullptr;
16268         Invalid = true;
16269       }
16270 
16271       // The existing declaration isn't relevant to us; we're in a
16272       // new scope, so clear out the previous declaration.
16273       Previous.clear();
16274     }
16275   }
16276 
16277 CreateNewDecl:
16278 
16279   TagDecl *PrevDecl = nullptr;
16280   if (Previous.isSingleResult())
16281     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16282 
16283   // If there is an identifier, use the location of the identifier as the
16284   // location of the decl, otherwise use the location of the struct/union
16285   // keyword.
16286   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16287 
16288   // Otherwise, create a new declaration. If there is a previous
16289   // declaration of the same entity, the two will be linked via
16290   // PrevDecl.
16291   TagDecl *New;
16292 
16293   if (Kind == TTK_Enum) {
16294     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16295     // enum X { A, B, C } D;    D should chain to X.
16296     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16297                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16298                            ScopedEnumUsesClassTag, IsFixed);
16299 
16300     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16301       StdAlignValT = cast<EnumDecl>(New);
16302 
16303     // If this is an undefined enum, warn.
16304     if (TUK != TUK_Definition && !Invalid) {
16305       TagDecl *Def;
16306       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16307         // C++0x: 7.2p2: opaque-enum-declaration.
16308         // Conflicts are diagnosed above. Do nothing.
16309       }
16310       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16311         Diag(Loc, diag::ext_forward_ref_enum_def)
16312           << New;
16313         Diag(Def->getLocation(), diag::note_previous_definition);
16314       } else {
16315         unsigned DiagID = diag::ext_forward_ref_enum;
16316         if (getLangOpts().MSVCCompat)
16317           DiagID = diag::ext_ms_forward_ref_enum;
16318         else if (getLangOpts().CPlusPlus)
16319           DiagID = diag::err_forward_ref_enum;
16320         Diag(Loc, DiagID);
16321       }
16322     }
16323 
16324     if (EnumUnderlying) {
16325       EnumDecl *ED = cast<EnumDecl>(New);
16326       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16327         ED->setIntegerTypeSourceInfo(TI);
16328       else
16329         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16330       ED->setPromotionType(ED->getIntegerType());
16331       assert(ED->isComplete() && "enum with type should be complete");
16332     }
16333   } else {
16334     // struct/union/class
16335 
16336     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16337     // struct X { int A; } D;    D should chain to X.
16338     if (getLangOpts().CPlusPlus) {
16339       // FIXME: Look for a way to use RecordDecl for simple structs.
16340       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16341                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16342 
16343       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16344         StdBadAlloc = cast<CXXRecordDecl>(New);
16345     } else
16346       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16347                                cast_or_null<RecordDecl>(PrevDecl));
16348   }
16349 
16350   // C++11 [dcl.type]p3:
16351   //   A type-specifier-seq shall not define a class or enumeration [...].
16352   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16353       TUK == TUK_Definition) {
16354     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16355       << Context.getTagDeclType(New);
16356     Invalid = true;
16357   }
16358 
16359   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16360       DC->getDeclKind() == Decl::Enum) {
16361     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16362       << Context.getTagDeclType(New);
16363     Invalid = true;
16364   }
16365 
16366   // Maybe add qualifier info.
16367   if (SS.isNotEmpty()) {
16368     if (SS.isSet()) {
16369       // If this is either a declaration or a definition, check the
16370       // nested-name-specifier against the current context.
16371       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16372           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16373                                        isMemberSpecialization))
16374         Invalid = true;
16375 
16376       New->setQualifierInfo(SS.getWithLocInContext(Context));
16377       if (TemplateParameterLists.size() > 0) {
16378         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16379       }
16380     }
16381     else
16382       Invalid = true;
16383   }
16384 
16385   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16386     // Add alignment attributes if necessary; these attributes are checked when
16387     // the ASTContext lays out the structure.
16388     //
16389     // It is important for implementing the correct semantics that this
16390     // happen here (in ActOnTag). The #pragma pack stack is
16391     // maintained as a result of parser callbacks which can occur at
16392     // many points during the parsing of a struct declaration (because
16393     // the #pragma tokens are effectively skipped over during the
16394     // parsing of the struct).
16395     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16396       AddAlignmentAttributesForRecord(RD);
16397       AddMsStructLayoutForRecord(RD);
16398     }
16399   }
16400 
16401   if (ModulePrivateLoc.isValid()) {
16402     if (isMemberSpecialization)
16403       Diag(New->getLocation(), diag::err_module_private_specialization)
16404         << 2
16405         << FixItHint::CreateRemoval(ModulePrivateLoc);
16406     // __module_private__ does not apply to local classes. However, we only
16407     // diagnose this as an error when the declaration specifiers are
16408     // freestanding. Here, we just ignore the __module_private__.
16409     else if (!SearchDC->isFunctionOrMethod())
16410       New->setModulePrivate();
16411   }
16412 
16413   // If this is a specialization of a member class (of a class template),
16414   // check the specialization.
16415   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16416     Invalid = true;
16417 
16418   // If we're declaring or defining a tag in function prototype scope in C,
16419   // note that this type can only be used within the function and add it to
16420   // the list of decls to inject into the function definition scope.
16421   if ((Name || Kind == TTK_Enum) &&
16422       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16423     if (getLangOpts().CPlusPlus) {
16424       // C++ [dcl.fct]p6:
16425       //   Types shall not be defined in return or parameter types.
16426       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16427         Diag(Loc, diag::err_type_defined_in_param_type)
16428             << Name;
16429         Invalid = true;
16430       }
16431     } else if (!PrevDecl) {
16432       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16433     }
16434   }
16435 
16436   if (Invalid)
16437     New->setInvalidDecl();
16438 
16439   // Set the lexical context. If the tag has a C++ scope specifier, the
16440   // lexical context will be different from the semantic context.
16441   New->setLexicalDeclContext(CurContext);
16442 
16443   // Mark this as a friend decl if applicable.
16444   // In Microsoft mode, a friend declaration also acts as a forward
16445   // declaration so we always pass true to setObjectOfFriendDecl to make
16446   // the tag name visible.
16447   if (TUK == TUK_Friend)
16448     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16449 
16450   // Set the access specifier.
16451   if (!Invalid && SearchDC->isRecord())
16452     SetMemberAccessSpecifier(New, PrevDecl, AS);
16453 
16454   if (PrevDecl)
16455     CheckRedeclarationModuleOwnership(New, PrevDecl);
16456 
16457   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16458     New->startDefinition();
16459 
16460   ProcessDeclAttributeList(S, New, Attrs);
16461   AddPragmaAttributes(S, New);
16462 
16463   // If this has an identifier, add it to the scope stack.
16464   if (TUK == TUK_Friend) {
16465     // We might be replacing an existing declaration in the lookup tables;
16466     // if so, borrow its access specifier.
16467     if (PrevDecl)
16468       New->setAccess(PrevDecl->getAccess());
16469 
16470     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16471     DC->makeDeclVisibleInContext(New);
16472     if (Name) // can be null along some error paths
16473       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16474         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16475   } else if (Name) {
16476     S = getNonFieldDeclScope(S);
16477     PushOnScopeChains(New, S, true);
16478   } else {
16479     CurContext->addDecl(New);
16480   }
16481 
16482   // If this is the C FILE type, notify the AST context.
16483   if (IdentifierInfo *II = New->getIdentifier())
16484     if (!New->isInvalidDecl() &&
16485         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16486         II->isStr("FILE"))
16487       Context.setFILEDecl(New);
16488 
16489   if (PrevDecl)
16490     mergeDeclAttributes(New, PrevDecl);
16491 
16492   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16493     inferGslOwnerPointerAttribute(CXXRD);
16494 
16495   // If there's a #pragma GCC visibility in scope, set the visibility of this
16496   // record.
16497   AddPushedVisibilityAttribute(New);
16498 
16499   if (isMemberSpecialization && !New->isInvalidDecl())
16500     CompleteMemberSpecialization(New, Previous);
16501 
16502   OwnedDecl = true;
16503   // In C++, don't return an invalid declaration. We can't recover well from
16504   // the cases where we make the type anonymous.
16505   if (Invalid && getLangOpts().CPlusPlus) {
16506     if (New->isBeingDefined())
16507       if (auto RD = dyn_cast<RecordDecl>(New))
16508         RD->completeDefinition();
16509     return nullptr;
16510   } else if (SkipBody && SkipBody->ShouldSkip) {
16511     return SkipBody->Previous;
16512   } else {
16513     return New;
16514   }
16515 }
16516 
16517 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16518   AdjustDeclIfTemplate(TagD);
16519   TagDecl *Tag = cast<TagDecl>(TagD);
16520 
16521   // Enter the tag context.
16522   PushDeclContext(S, Tag);
16523 
16524   ActOnDocumentableDecl(TagD);
16525 
16526   // If there's a #pragma GCC visibility in scope, set the visibility of this
16527   // record.
16528   AddPushedVisibilityAttribute(Tag);
16529 }
16530 
16531 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16532                                     SkipBodyInfo &SkipBody) {
16533   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16534     return false;
16535 
16536   // Make the previous decl visible.
16537   makeMergedDefinitionVisible(SkipBody.Previous);
16538   return true;
16539 }
16540 
16541 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16542   assert(isa<ObjCContainerDecl>(IDecl) &&
16543          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16544   DeclContext *OCD = cast<DeclContext>(IDecl);
16545   assert(OCD->getLexicalParent() == CurContext &&
16546       "The next DeclContext should be lexically contained in the current one.");
16547   CurContext = OCD;
16548   return IDecl;
16549 }
16550 
16551 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16552                                            SourceLocation FinalLoc,
16553                                            bool IsFinalSpelledSealed,
16554                                            SourceLocation LBraceLoc) {
16555   AdjustDeclIfTemplate(TagD);
16556   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16557 
16558   FieldCollector->StartClass();
16559 
16560   if (!Record->getIdentifier())
16561     return;
16562 
16563   if (FinalLoc.isValid())
16564     Record->addAttr(FinalAttr::Create(
16565         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16566         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16567 
16568   // C++ [class]p2:
16569   //   [...] The class-name is also inserted into the scope of the
16570   //   class itself; this is known as the injected-class-name. For
16571   //   purposes of access checking, the injected-class-name is treated
16572   //   as if it were a public member name.
16573   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16574       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16575       Record->getLocation(), Record->getIdentifier(),
16576       /*PrevDecl=*/nullptr,
16577       /*DelayTypeCreation=*/true);
16578   Context.getTypeDeclType(InjectedClassName, Record);
16579   InjectedClassName->setImplicit();
16580   InjectedClassName->setAccess(AS_public);
16581   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16582       InjectedClassName->setDescribedClassTemplate(Template);
16583   PushOnScopeChains(InjectedClassName, S);
16584   assert(InjectedClassName->isInjectedClassName() &&
16585          "Broken injected-class-name");
16586 }
16587 
16588 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16589                                     SourceRange BraceRange) {
16590   AdjustDeclIfTemplate(TagD);
16591   TagDecl *Tag = cast<TagDecl>(TagD);
16592   Tag->setBraceRange(BraceRange);
16593 
16594   // Make sure we "complete" the definition even it is invalid.
16595   if (Tag->isBeingDefined()) {
16596     assert(Tag->isInvalidDecl() && "We should already have completed it");
16597     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16598       RD->completeDefinition();
16599   }
16600 
16601   if (isa<CXXRecordDecl>(Tag)) {
16602     FieldCollector->FinishClass();
16603   }
16604 
16605   // Exit this scope of this tag's definition.
16606   PopDeclContext();
16607 
16608   if (getCurLexicalContext()->isObjCContainer() &&
16609       Tag->getDeclContext()->isFileContext())
16610     Tag->setTopLevelDeclInObjCContainer();
16611 
16612   // Notify the consumer that we've defined a tag.
16613   if (!Tag->isInvalidDecl())
16614     Consumer.HandleTagDeclDefinition(Tag);
16615 }
16616 
16617 void Sema::ActOnObjCContainerFinishDefinition() {
16618   // Exit this scope of this interface definition.
16619   PopDeclContext();
16620 }
16621 
16622 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16623   assert(DC == CurContext && "Mismatch of container contexts");
16624   OriginalLexicalContext = DC;
16625   ActOnObjCContainerFinishDefinition();
16626 }
16627 
16628 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16629   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16630   OriginalLexicalContext = nullptr;
16631 }
16632 
16633 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16634   AdjustDeclIfTemplate(TagD);
16635   TagDecl *Tag = cast<TagDecl>(TagD);
16636   Tag->setInvalidDecl();
16637 
16638   // Make sure we "complete" the definition even it is invalid.
16639   if (Tag->isBeingDefined()) {
16640     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16641       RD->completeDefinition();
16642   }
16643 
16644   // We're undoing ActOnTagStartDefinition here, not
16645   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16646   // the FieldCollector.
16647 
16648   PopDeclContext();
16649 }
16650 
16651 // Note that FieldName may be null for anonymous bitfields.
16652 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16653                                 IdentifierInfo *FieldName,
16654                                 QualType FieldTy, bool IsMsStruct,
16655                                 Expr *BitWidth, bool *ZeroWidth) {
16656   assert(BitWidth);
16657   if (BitWidth->containsErrors())
16658     return ExprError();
16659 
16660   // Default to true; that shouldn't confuse checks for emptiness
16661   if (ZeroWidth)
16662     *ZeroWidth = true;
16663 
16664   // C99 6.7.2.1p4 - verify the field type.
16665   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16666   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16667     // Handle incomplete and sizeless types with a specific error.
16668     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16669                                  diag::err_field_incomplete_or_sizeless))
16670       return ExprError();
16671     if (FieldName)
16672       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16673         << FieldName << FieldTy << BitWidth->getSourceRange();
16674     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16675       << FieldTy << BitWidth->getSourceRange();
16676   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16677                                              UPPC_BitFieldWidth))
16678     return ExprError();
16679 
16680   // If the bit-width is type- or value-dependent, don't try to check
16681   // it now.
16682   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16683     return BitWidth;
16684 
16685   llvm::APSInt Value;
16686   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16687   if (ICE.isInvalid())
16688     return ICE;
16689   BitWidth = ICE.get();
16690 
16691   if (Value != 0 && ZeroWidth)
16692     *ZeroWidth = false;
16693 
16694   // Zero-width bitfield is ok for anonymous field.
16695   if (Value == 0 && FieldName)
16696     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16697 
16698   if (Value.isSigned() && Value.isNegative()) {
16699     if (FieldName)
16700       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16701                << FieldName << Value.toString(10);
16702     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16703       << Value.toString(10);
16704   }
16705 
16706   // The size of the bit-field must not exceed our maximum permitted object
16707   // size.
16708   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16709     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16710            << !FieldName << FieldName << Value.toString(10);
16711   }
16712 
16713   if (!FieldTy->isDependentType()) {
16714     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16715     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16716     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16717 
16718     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16719     // ABI.
16720     bool CStdConstraintViolation =
16721         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16722     bool MSBitfieldViolation =
16723         Value.ugt(TypeStorageSize) &&
16724         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16725     if (CStdConstraintViolation || MSBitfieldViolation) {
16726       unsigned DiagWidth =
16727           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16728       if (FieldName)
16729         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16730                << FieldName << Value.toString(10)
16731                << !CStdConstraintViolation << DiagWidth;
16732 
16733       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16734              << Value.toString(10) << !CStdConstraintViolation
16735              << DiagWidth;
16736     }
16737 
16738     // Warn on types where the user might conceivably expect to get all
16739     // specified bits as value bits: that's all integral types other than
16740     // 'bool'.
16741     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16742       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16743           << FieldName << Value.toString(10)
16744           << (unsigned)TypeWidth;
16745     }
16746   }
16747 
16748   return BitWidth;
16749 }
16750 
16751 /// ActOnField - Each field of a C struct/union is passed into this in order
16752 /// to create a FieldDecl object for it.
16753 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16754                        Declarator &D, Expr *BitfieldWidth) {
16755   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16756                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16757                                /*InitStyle=*/ICIS_NoInit, AS_public);
16758   return Res;
16759 }
16760 
16761 /// HandleField - Analyze a field of a C struct or a C++ data member.
16762 ///
16763 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16764                              SourceLocation DeclStart,
16765                              Declarator &D, Expr *BitWidth,
16766                              InClassInitStyle InitStyle,
16767                              AccessSpecifier AS) {
16768   if (D.isDecompositionDeclarator()) {
16769     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16770     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16771       << Decomp.getSourceRange();
16772     return nullptr;
16773   }
16774 
16775   IdentifierInfo *II = D.getIdentifier();
16776   SourceLocation Loc = DeclStart;
16777   if (II) Loc = D.getIdentifierLoc();
16778 
16779   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16780   QualType T = TInfo->getType();
16781   if (getLangOpts().CPlusPlus) {
16782     CheckExtraCXXDefaultArguments(D);
16783 
16784     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16785                                         UPPC_DataMemberType)) {
16786       D.setInvalidType();
16787       T = Context.IntTy;
16788       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16789     }
16790   }
16791 
16792   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16793 
16794   if (D.getDeclSpec().isInlineSpecified())
16795     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16796         << getLangOpts().CPlusPlus17;
16797   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16798     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16799          diag::err_invalid_thread)
16800       << DeclSpec::getSpecifierName(TSCS);
16801 
16802   // Check to see if this name was declared as a member previously
16803   NamedDecl *PrevDecl = nullptr;
16804   LookupResult Previous(*this, II, Loc, LookupMemberName,
16805                         ForVisibleRedeclaration);
16806   LookupName(Previous, S);
16807   switch (Previous.getResultKind()) {
16808     case LookupResult::Found:
16809     case LookupResult::FoundUnresolvedValue:
16810       PrevDecl = Previous.getAsSingle<NamedDecl>();
16811       break;
16812 
16813     case LookupResult::FoundOverloaded:
16814       PrevDecl = Previous.getRepresentativeDecl();
16815       break;
16816 
16817     case LookupResult::NotFound:
16818     case LookupResult::NotFoundInCurrentInstantiation:
16819     case LookupResult::Ambiguous:
16820       break;
16821   }
16822   Previous.suppressDiagnostics();
16823 
16824   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16825     // Maybe we will complain about the shadowed template parameter.
16826     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16827     // Just pretend that we didn't see the previous declaration.
16828     PrevDecl = nullptr;
16829   }
16830 
16831   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16832     PrevDecl = nullptr;
16833 
16834   bool Mutable
16835     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16836   SourceLocation TSSL = D.getBeginLoc();
16837   FieldDecl *NewFD
16838     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16839                      TSSL, AS, PrevDecl, &D);
16840 
16841   if (NewFD->isInvalidDecl())
16842     Record->setInvalidDecl();
16843 
16844   if (D.getDeclSpec().isModulePrivateSpecified())
16845     NewFD->setModulePrivate();
16846 
16847   if (NewFD->isInvalidDecl() && PrevDecl) {
16848     // Don't introduce NewFD into scope; there's already something
16849     // with the same name in the same scope.
16850   } else if (II) {
16851     PushOnScopeChains(NewFD, S);
16852   } else
16853     Record->addDecl(NewFD);
16854 
16855   return NewFD;
16856 }
16857 
16858 /// Build a new FieldDecl and check its well-formedness.
16859 ///
16860 /// This routine builds a new FieldDecl given the fields name, type,
16861 /// record, etc. \p PrevDecl should refer to any previous declaration
16862 /// with the same name and in the same scope as the field to be
16863 /// created.
16864 ///
16865 /// \returns a new FieldDecl.
16866 ///
16867 /// \todo The Declarator argument is a hack. It will be removed once
16868 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16869                                 TypeSourceInfo *TInfo,
16870                                 RecordDecl *Record, SourceLocation Loc,
16871                                 bool Mutable, Expr *BitWidth,
16872                                 InClassInitStyle InitStyle,
16873                                 SourceLocation TSSL,
16874                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16875                                 Declarator *D) {
16876   IdentifierInfo *II = Name.getAsIdentifierInfo();
16877   bool InvalidDecl = false;
16878   if (D) InvalidDecl = D->isInvalidType();
16879 
16880   // If we receive a broken type, recover by assuming 'int' and
16881   // marking this declaration as invalid.
16882   if (T.isNull() || T->containsErrors()) {
16883     InvalidDecl = true;
16884     T = Context.IntTy;
16885   }
16886 
16887   QualType EltTy = Context.getBaseElementType(T);
16888   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16889     if (RequireCompleteSizedType(Loc, EltTy,
16890                                  diag::err_field_incomplete_or_sizeless)) {
16891       // Fields of incomplete type force their record to be invalid.
16892       Record->setInvalidDecl();
16893       InvalidDecl = true;
16894     } else {
16895       NamedDecl *Def;
16896       EltTy->isIncompleteType(&Def);
16897       if (Def && Def->isInvalidDecl()) {
16898         Record->setInvalidDecl();
16899         InvalidDecl = true;
16900       }
16901     }
16902   }
16903 
16904   // TR 18037 does not allow fields to be declared with address space
16905   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16906       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16907     Diag(Loc, diag::err_field_with_address_space);
16908     Record->setInvalidDecl();
16909     InvalidDecl = true;
16910   }
16911 
16912   if (LangOpts.OpenCL) {
16913     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16914     // used as structure or union field: image, sampler, event or block types.
16915     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16916         T->isBlockPointerType()) {
16917       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16918       Record->setInvalidDecl();
16919       InvalidDecl = true;
16920     }
16921     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16922     if (BitWidth) {
16923       Diag(Loc, diag::err_opencl_bitfields);
16924       InvalidDecl = true;
16925     }
16926   }
16927 
16928   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16929   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16930       T.hasQualifiers()) {
16931     InvalidDecl = true;
16932     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16933   }
16934 
16935   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16936   // than a variably modified type.
16937   if (!InvalidDecl && T->isVariablyModifiedType()) {
16938     if (!tryToFixVariablyModifiedVarType(
16939             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16940       InvalidDecl = true;
16941   }
16942 
16943   // Fields can not have abstract class types
16944   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16945                                              diag::err_abstract_type_in_decl,
16946                                              AbstractFieldType))
16947     InvalidDecl = true;
16948 
16949   bool ZeroWidth = false;
16950   if (InvalidDecl)
16951     BitWidth = nullptr;
16952   // If this is declared as a bit-field, check the bit-field.
16953   if (BitWidth) {
16954     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16955                               &ZeroWidth).get();
16956     if (!BitWidth) {
16957       InvalidDecl = true;
16958       BitWidth = nullptr;
16959       ZeroWidth = false;
16960     }
16961   }
16962 
16963   // Check that 'mutable' is consistent with the type of the declaration.
16964   if (!InvalidDecl && Mutable) {
16965     unsigned DiagID = 0;
16966     if (T->isReferenceType())
16967       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16968                                         : diag::err_mutable_reference;
16969     else if (T.isConstQualified())
16970       DiagID = diag::err_mutable_const;
16971 
16972     if (DiagID) {
16973       SourceLocation ErrLoc = Loc;
16974       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16975         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16976       Diag(ErrLoc, DiagID);
16977       if (DiagID != diag::ext_mutable_reference) {
16978         Mutable = false;
16979         InvalidDecl = true;
16980       }
16981     }
16982   }
16983 
16984   // C++11 [class.union]p8 (DR1460):
16985   //   At most one variant member of a union may have a
16986   //   brace-or-equal-initializer.
16987   if (InitStyle != ICIS_NoInit)
16988     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16989 
16990   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16991                                        BitWidth, Mutable, InitStyle);
16992   if (InvalidDecl)
16993     NewFD->setInvalidDecl();
16994 
16995   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16996     Diag(Loc, diag::err_duplicate_member) << II;
16997     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16998     NewFD->setInvalidDecl();
16999   }
17000 
17001   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17002     if (Record->isUnion()) {
17003       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17004         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17005         if (RDecl->getDefinition()) {
17006           // C++ [class.union]p1: An object of a class with a non-trivial
17007           // constructor, a non-trivial copy constructor, a non-trivial
17008           // destructor, or a non-trivial copy assignment operator
17009           // cannot be a member of a union, nor can an array of such
17010           // objects.
17011           if (CheckNontrivialField(NewFD))
17012             NewFD->setInvalidDecl();
17013         }
17014       }
17015 
17016       // C++ [class.union]p1: If a union contains a member of reference type,
17017       // the program is ill-formed, except when compiling with MSVC extensions
17018       // enabled.
17019       if (EltTy->isReferenceType()) {
17020         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17021                                     diag::ext_union_member_of_reference_type :
17022                                     diag::err_union_member_of_reference_type)
17023           << NewFD->getDeclName() << EltTy;
17024         if (!getLangOpts().MicrosoftExt)
17025           NewFD->setInvalidDecl();
17026       }
17027     }
17028   }
17029 
17030   // FIXME: We need to pass in the attributes given an AST
17031   // representation, not a parser representation.
17032   if (D) {
17033     // FIXME: The current scope is almost... but not entirely... correct here.
17034     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17035 
17036     if (NewFD->hasAttrs())
17037       CheckAlignasUnderalignment(NewFD);
17038   }
17039 
17040   // In auto-retain/release, infer strong retension for fields of
17041   // retainable type.
17042   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17043     NewFD->setInvalidDecl();
17044 
17045   if (T.isObjCGCWeak())
17046     Diag(Loc, diag::warn_attribute_weak_on_field);
17047 
17048   // PPC MMA non-pointer types are not allowed as field types.
17049   if (Context.getTargetInfo().getTriple().isPPC64() &&
17050       CheckPPCMMAType(T, NewFD->getLocation()))
17051     NewFD->setInvalidDecl();
17052 
17053   NewFD->setAccess(AS);
17054   return NewFD;
17055 }
17056 
17057 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17058   assert(FD);
17059   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17060 
17061   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17062     return false;
17063 
17064   QualType EltTy = Context.getBaseElementType(FD->getType());
17065   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17066     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17067     if (RDecl->getDefinition()) {
17068       // We check for copy constructors before constructors
17069       // because otherwise we'll never get complaints about
17070       // copy constructors.
17071 
17072       CXXSpecialMember member = CXXInvalid;
17073       // We're required to check for any non-trivial constructors. Since the
17074       // implicit default constructor is suppressed if there are any
17075       // user-declared constructors, we just need to check that there is a
17076       // trivial default constructor and a trivial copy constructor. (We don't
17077       // worry about move constructors here, since this is a C++98 check.)
17078       if (RDecl->hasNonTrivialCopyConstructor())
17079         member = CXXCopyConstructor;
17080       else if (!RDecl->hasTrivialDefaultConstructor())
17081         member = CXXDefaultConstructor;
17082       else if (RDecl->hasNonTrivialCopyAssignment())
17083         member = CXXCopyAssignment;
17084       else if (RDecl->hasNonTrivialDestructor())
17085         member = CXXDestructor;
17086 
17087       if (member != CXXInvalid) {
17088         if (!getLangOpts().CPlusPlus11 &&
17089             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17090           // Objective-C++ ARC: it is an error to have a non-trivial field of
17091           // a union. However, system headers in Objective-C programs
17092           // occasionally have Objective-C lifetime objects within unions,
17093           // and rather than cause the program to fail, we make those
17094           // members unavailable.
17095           SourceLocation Loc = FD->getLocation();
17096           if (getSourceManager().isInSystemHeader(Loc)) {
17097             if (!FD->hasAttr<UnavailableAttr>())
17098               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17099                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17100             return false;
17101           }
17102         }
17103 
17104         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17105                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17106                diag::err_illegal_union_or_anon_struct_member)
17107           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17108         DiagnoseNontrivial(RDecl, member);
17109         return !getLangOpts().CPlusPlus11;
17110       }
17111     }
17112   }
17113 
17114   return false;
17115 }
17116 
17117 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17118 ///  AST enum value.
17119 static ObjCIvarDecl::AccessControl
17120 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17121   switch (ivarVisibility) {
17122   default: llvm_unreachable("Unknown visitibility kind");
17123   case tok::objc_private: return ObjCIvarDecl::Private;
17124   case tok::objc_public: return ObjCIvarDecl::Public;
17125   case tok::objc_protected: return ObjCIvarDecl::Protected;
17126   case tok::objc_package: return ObjCIvarDecl::Package;
17127   }
17128 }
17129 
17130 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17131 /// in order to create an IvarDecl object for it.
17132 Decl *Sema::ActOnIvar(Scope *S,
17133                                 SourceLocation DeclStart,
17134                                 Declarator &D, Expr *BitfieldWidth,
17135                                 tok::ObjCKeywordKind Visibility) {
17136 
17137   IdentifierInfo *II = D.getIdentifier();
17138   Expr *BitWidth = (Expr*)BitfieldWidth;
17139   SourceLocation Loc = DeclStart;
17140   if (II) Loc = D.getIdentifierLoc();
17141 
17142   // FIXME: Unnamed fields can be handled in various different ways, for
17143   // example, unnamed unions inject all members into the struct namespace!
17144 
17145   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17146   QualType T = TInfo->getType();
17147 
17148   if (BitWidth) {
17149     // 6.7.2.1p3, 6.7.2.1p4
17150     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17151     if (!BitWidth)
17152       D.setInvalidType();
17153   } else {
17154     // Not a bitfield.
17155 
17156     // validate II.
17157 
17158   }
17159   if (T->isReferenceType()) {
17160     Diag(Loc, diag::err_ivar_reference_type);
17161     D.setInvalidType();
17162   }
17163   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17164   // than a variably modified type.
17165   else if (T->isVariablyModifiedType()) {
17166     if (!tryToFixVariablyModifiedVarType(
17167             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17168       D.setInvalidType();
17169   }
17170 
17171   // Get the visibility (access control) for this ivar.
17172   ObjCIvarDecl::AccessControl ac =
17173     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17174                                         : ObjCIvarDecl::None;
17175   // Must set ivar's DeclContext to its enclosing interface.
17176   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17177   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17178     return nullptr;
17179   ObjCContainerDecl *EnclosingContext;
17180   if (ObjCImplementationDecl *IMPDecl =
17181       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17182     if (LangOpts.ObjCRuntime.isFragile()) {
17183     // Case of ivar declared in an implementation. Context is that of its class.
17184       EnclosingContext = IMPDecl->getClassInterface();
17185       assert(EnclosingContext && "Implementation has no class interface!");
17186     }
17187     else
17188       EnclosingContext = EnclosingDecl;
17189   } else {
17190     if (ObjCCategoryDecl *CDecl =
17191         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17192       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17193         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17194         return nullptr;
17195       }
17196     }
17197     EnclosingContext = EnclosingDecl;
17198   }
17199 
17200   // Construct the decl.
17201   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17202                                              DeclStart, Loc, II, T,
17203                                              TInfo, ac, (Expr *)BitfieldWidth);
17204 
17205   if (II) {
17206     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17207                                            ForVisibleRedeclaration);
17208     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17209         && !isa<TagDecl>(PrevDecl)) {
17210       Diag(Loc, diag::err_duplicate_member) << II;
17211       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17212       NewID->setInvalidDecl();
17213     }
17214   }
17215 
17216   // Process attributes attached to the ivar.
17217   ProcessDeclAttributes(S, NewID, D);
17218 
17219   if (D.isInvalidType())
17220     NewID->setInvalidDecl();
17221 
17222   // In ARC, infer 'retaining' for ivars of retainable type.
17223   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17224     NewID->setInvalidDecl();
17225 
17226   if (D.getDeclSpec().isModulePrivateSpecified())
17227     NewID->setModulePrivate();
17228 
17229   if (II) {
17230     // FIXME: When interfaces are DeclContexts, we'll need to add
17231     // these to the interface.
17232     S->AddDecl(NewID);
17233     IdResolver.AddDecl(NewID);
17234   }
17235 
17236   if (LangOpts.ObjCRuntime.isNonFragile() &&
17237       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17238     Diag(Loc, diag::warn_ivars_in_interface);
17239 
17240   return NewID;
17241 }
17242 
17243 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17244 /// class and class extensions. For every class \@interface and class
17245 /// extension \@interface, if the last ivar is a bitfield of any type,
17246 /// then add an implicit `char :0` ivar to the end of that interface.
17247 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17248                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17249   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17250     return;
17251 
17252   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17253   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17254 
17255   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17256     return;
17257   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17258   if (!ID) {
17259     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17260       if (!CD->IsClassExtension())
17261         return;
17262     }
17263     // No need to add this to end of @implementation.
17264     else
17265       return;
17266   }
17267   // All conditions are met. Add a new bitfield to the tail end of ivars.
17268   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17269   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17270 
17271   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17272                               DeclLoc, DeclLoc, nullptr,
17273                               Context.CharTy,
17274                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17275                                                                DeclLoc),
17276                               ObjCIvarDecl::Private, BW,
17277                               true);
17278   AllIvarDecls.push_back(Ivar);
17279 }
17280 
17281 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17282                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17283                        SourceLocation RBrac,
17284                        const ParsedAttributesView &Attrs) {
17285   assert(EnclosingDecl && "missing record or interface decl");
17286 
17287   // If this is an Objective-C @implementation or category and we have
17288   // new fields here we should reset the layout of the interface since
17289   // it will now change.
17290   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17291     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17292     switch (DC->getKind()) {
17293     default: break;
17294     case Decl::ObjCCategory:
17295       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17296       break;
17297     case Decl::ObjCImplementation:
17298       Context.
17299         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17300       break;
17301     }
17302   }
17303 
17304   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17305   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17306 
17307   // Start counting up the number of named members; make sure to include
17308   // members of anonymous structs and unions in the total.
17309   unsigned NumNamedMembers = 0;
17310   if (Record) {
17311     for (const auto *I : Record->decls()) {
17312       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17313         if (IFD->getDeclName())
17314           ++NumNamedMembers;
17315     }
17316   }
17317 
17318   // Verify that all the fields are okay.
17319   SmallVector<FieldDecl*, 32> RecFields;
17320 
17321   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17322        i != end; ++i) {
17323     FieldDecl *FD = cast<FieldDecl>(*i);
17324 
17325     // Get the type for the field.
17326     const Type *FDTy = FD->getType().getTypePtr();
17327 
17328     if (!FD->isAnonymousStructOrUnion()) {
17329       // Remember all fields written by the user.
17330       RecFields.push_back(FD);
17331     }
17332 
17333     // If the field is already invalid for some reason, don't emit more
17334     // diagnostics about it.
17335     if (FD->isInvalidDecl()) {
17336       EnclosingDecl->setInvalidDecl();
17337       continue;
17338     }
17339 
17340     // C99 6.7.2.1p2:
17341     //   A structure or union shall not contain a member with
17342     //   incomplete or function type (hence, a structure shall not
17343     //   contain an instance of itself, but may contain a pointer to
17344     //   an instance of itself), except that the last member of a
17345     //   structure with more than one named member may have incomplete
17346     //   array type; such a structure (and any union containing,
17347     //   possibly recursively, a member that is such a structure)
17348     //   shall not be a member of a structure or an element of an
17349     //   array.
17350     bool IsLastField = (i + 1 == Fields.end());
17351     if (FDTy->isFunctionType()) {
17352       // Field declared as a function.
17353       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17354         << FD->getDeclName();
17355       FD->setInvalidDecl();
17356       EnclosingDecl->setInvalidDecl();
17357       continue;
17358     } else if (FDTy->isIncompleteArrayType() &&
17359                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17360       if (Record) {
17361         // Flexible array member.
17362         // Microsoft and g++ is more permissive regarding flexible array.
17363         // It will accept flexible array in union and also
17364         // as the sole element of a struct/class.
17365         unsigned DiagID = 0;
17366         if (!Record->isUnion() && !IsLastField) {
17367           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17368             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17369           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17370           FD->setInvalidDecl();
17371           EnclosingDecl->setInvalidDecl();
17372           continue;
17373         } else if (Record->isUnion())
17374           DiagID = getLangOpts().MicrosoftExt
17375                        ? diag::ext_flexible_array_union_ms
17376                        : getLangOpts().CPlusPlus
17377                              ? diag::ext_flexible_array_union_gnu
17378                              : diag::err_flexible_array_union;
17379         else if (NumNamedMembers < 1)
17380           DiagID = getLangOpts().MicrosoftExt
17381                        ? diag::ext_flexible_array_empty_aggregate_ms
17382                        : getLangOpts().CPlusPlus
17383                              ? diag::ext_flexible_array_empty_aggregate_gnu
17384                              : diag::err_flexible_array_empty_aggregate;
17385 
17386         if (DiagID)
17387           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17388                                           << Record->getTagKind();
17389         // While the layout of types that contain virtual bases is not specified
17390         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17391         // virtual bases after the derived members.  This would make a flexible
17392         // array member declared at the end of an object not adjacent to the end
17393         // of the type.
17394         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17395           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17396               << FD->getDeclName() << Record->getTagKind();
17397         if (!getLangOpts().C99)
17398           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17399             << FD->getDeclName() << Record->getTagKind();
17400 
17401         // If the element type has a non-trivial destructor, we would not
17402         // implicitly destroy the elements, so disallow it for now.
17403         //
17404         // FIXME: GCC allows this. We should probably either implicitly delete
17405         // the destructor of the containing class, or just allow this.
17406         QualType BaseElem = Context.getBaseElementType(FD->getType());
17407         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17408           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17409             << FD->getDeclName() << FD->getType();
17410           FD->setInvalidDecl();
17411           EnclosingDecl->setInvalidDecl();
17412           continue;
17413         }
17414         // Okay, we have a legal flexible array member at the end of the struct.
17415         Record->setHasFlexibleArrayMember(true);
17416       } else {
17417         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17418         // unless they are followed by another ivar. That check is done
17419         // elsewhere, after synthesized ivars are known.
17420       }
17421     } else if (!FDTy->isDependentType() &&
17422                RequireCompleteSizedType(
17423                    FD->getLocation(), FD->getType(),
17424                    diag::err_field_incomplete_or_sizeless)) {
17425       // Incomplete type
17426       FD->setInvalidDecl();
17427       EnclosingDecl->setInvalidDecl();
17428       continue;
17429     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17430       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17431         // A type which contains a flexible array member is considered to be a
17432         // flexible array member.
17433         Record->setHasFlexibleArrayMember(true);
17434         if (!Record->isUnion()) {
17435           // If this is a struct/class and this is not the last element, reject
17436           // it.  Note that GCC supports variable sized arrays in the middle of
17437           // structures.
17438           if (!IsLastField)
17439             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17440               << FD->getDeclName() << FD->getType();
17441           else {
17442             // We support flexible arrays at the end of structs in
17443             // other structs as an extension.
17444             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17445               << FD->getDeclName();
17446           }
17447         }
17448       }
17449       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17450           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17451                                  diag::err_abstract_type_in_decl,
17452                                  AbstractIvarType)) {
17453         // Ivars can not have abstract class types
17454         FD->setInvalidDecl();
17455       }
17456       if (Record && FDTTy->getDecl()->hasObjectMember())
17457         Record->setHasObjectMember(true);
17458       if (Record && FDTTy->getDecl()->hasVolatileMember())
17459         Record->setHasVolatileMember(true);
17460     } else if (FDTy->isObjCObjectType()) {
17461       /// A field cannot be an Objective-c object
17462       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17463         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17464       QualType T = Context.getObjCObjectPointerType(FD->getType());
17465       FD->setType(T);
17466     } else if (Record && Record->isUnion() &&
17467                FD->getType().hasNonTrivialObjCLifetime() &&
17468                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17469                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17470                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17471                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17472       // For backward compatibility, fields of C unions declared in system
17473       // headers that have non-trivial ObjC ownership qualifications are marked
17474       // as unavailable unless the qualifier is explicit and __strong. This can
17475       // break ABI compatibility between programs compiled with ARC and MRR, but
17476       // is a better option than rejecting programs using those unions under
17477       // ARC.
17478       FD->addAttr(UnavailableAttr::CreateImplicit(
17479           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17480           FD->getLocation()));
17481     } else if (getLangOpts().ObjC &&
17482                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17483                !Record->hasObjectMember()) {
17484       if (FD->getType()->isObjCObjectPointerType() ||
17485           FD->getType().isObjCGCStrong())
17486         Record->setHasObjectMember(true);
17487       else if (Context.getAsArrayType(FD->getType())) {
17488         QualType BaseType = Context.getBaseElementType(FD->getType());
17489         if (BaseType->isRecordType() &&
17490             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17491           Record->setHasObjectMember(true);
17492         else if (BaseType->isObjCObjectPointerType() ||
17493                  BaseType.isObjCGCStrong())
17494                Record->setHasObjectMember(true);
17495       }
17496     }
17497 
17498     if (Record && !getLangOpts().CPlusPlus &&
17499         !shouldIgnoreForRecordTriviality(FD)) {
17500       QualType FT = FD->getType();
17501       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17502         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17503         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17504             Record->isUnion())
17505           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17506       }
17507       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17508       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17509         Record->setNonTrivialToPrimitiveCopy(true);
17510         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17511           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17512       }
17513       if (FT.isDestructedType()) {
17514         Record->setNonTrivialToPrimitiveDestroy(true);
17515         Record->setParamDestroyedInCallee(true);
17516         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17517           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17518       }
17519 
17520       if (const auto *RT = FT->getAs<RecordType>()) {
17521         if (RT->getDecl()->getArgPassingRestrictions() ==
17522             RecordDecl::APK_CanNeverPassInRegs)
17523           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17524       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17525         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17526     }
17527 
17528     if (Record && FD->getType().isVolatileQualified())
17529       Record->setHasVolatileMember(true);
17530     // Keep track of the number of named members.
17531     if (FD->getIdentifier())
17532       ++NumNamedMembers;
17533   }
17534 
17535   // Okay, we successfully defined 'Record'.
17536   if (Record) {
17537     bool Completed = false;
17538     if (CXXRecord) {
17539       if (!CXXRecord->isInvalidDecl()) {
17540         // Set access bits correctly on the directly-declared conversions.
17541         for (CXXRecordDecl::conversion_iterator
17542                I = CXXRecord->conversion_begin(),
17543                E = CXXRecord->conversion_end(); I != E; ++I)
17544           I.setAccess((*I)->getAccess());
17545       }
17546 
17547       // Add any implicitly-declared members to this class.
17548       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17549 
17550       if (!CXXRecord->isDependentType()) {
17551         if (!CXXRecord->isInvalidDecl()) {
17552           // If we have virtual base classes, we may end up finding multiple
17553           // final overriders for a given virtual function. Check for this
17554           // problem now.
17555           if (CXXRecord->getNumVBases()) {
17556             CXXFinalOverriderMap FinalOverriders;
17557             CXXRecord->getFinalOverriders(FinalOverriders);
17558 
17559             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17560                                              MEnd = FinalOverriders.end();
17561                  M != MEnd; ++M) {
17562               for (OverridingMethods::iterator SO = M->second.begin(),
17563                                             SOEnd = M->second.end();
17564                    SO != SOEnd; ++SO) {
17565                 assert(SO->second.size() > 0 &&
17566                        "Virtual function without overriding functions?");
17567                 if (SO->second.size() == 1)
17568                   continue;
17569 
17570                 // C++ [class.virtual]p2:
17571                 //   In a derived class, if a virtual member function of a base
17572                 //   class subobject has more than one final overrider the
17573                 //   program is ill-formed.
17574                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17575                   << (const NamedDecl *)M->first << Record;
17576                 Diag(M->first->getLocation(),
17577                      diag::note_overridden_virtual_function);
17578                 for (OverridingMethods::overriding_iterator
17579                           OM = SO->second.begin(),
17580                        OMEnd = SO->second.end();
17581                      OM != OMEnd; ++OM)
17582                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17583                     << (const NamedDecl *)M->first << OM->Method->getParent();
17584 
17585                 Record->setInvalidDecl();
17586               }
17587             }
17588             CXXRecord->completeDefinition(&FinalOverriders);
17589             Completed = true;
17590           }
17591         }
17592       }
17593     }
17594 
17595     if (!Completed)
17596       Record->completeDefinition();
17597 
17598     // Handle attributes before checking the layout.
17599     ProcessDeclAttributeList(S, Record, Attrs);
17600 
17601     // We may have deferred checking for a deleted destructor. Check now.
17602     if (CXXRecord) {
17603       auto *Dtor = CXXRecord->getDestructor();
17604       if (Dtor && Dtor->isImplicit() &&
17605           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17606         CXXRecord->setImplicitDestructorIsDeleted();
17607         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17608       }
17609     }
17610 
17611     if (Record->hasAttrs()) {
17612       CheckAlignasUnderalignment(Record);
17613 
17614       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17615         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17616                                            IA->getRange(), IA->getBestCase(),
17617                                            IA->getInheritanceModel());
17618     }
17619 
17620     // Check if the structure/union declaration is a type that can have zero
17621     // size in C. For C this is a language extension, for C++ it may cause
17622     // compatibility problems.
17623     bool CheckForZeroSize;
17624     if (!getLangOpts().CPlusPlus) {
17625       CheckForZeroSize = true;
17626     } else {
17627       // For C++ filter out types that cannot be referenced in C code.
17628       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17629       CheckForZeroSize =
17630           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17631           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17632           CXXRecord->isCLike();
17633     }
17634     if (CheckForZeroSize) {
17635       bool ZeroSize = true;
17636       bool IsEmpty = true;
17637       unsigned NonBitFields = 0;
17638       for (RecordDecl::field_iterator I = Record->field_begin(),
17639                                       E = Record->field_end();
17640            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17641         IsEmpty = false;
17642         if (I->isUnnamedBitfield()) {
17643           if (!I->isZeroLengthBitField(Context))
17644             ZeroSize = false;
17645         } else {
17646           ++NonBitFields;
17647           QualType FieldType = I->getType();
17648           if (FieldType->isIncompleteType() ||
17649               !Context.getTypeSizeInChars(FieldType).isZero())
17650             ZeroSize = false;
17651         }
17652       }
17653 
17654       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17655       // allowed in C++, but warn if its declaration is inside
17656       // extern "C" block.
17657       if (ZeroSize) {
17658         Diag(RecLoc, getLangOpts().CPlusPlus ?
17659                          diag::warn_zero_size_struct_union_in_extern_c :
17660                          diag::warn_zero_size_struct_union_compat)
17661           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17662       }
17663 
17664       // Structs without named members are extension in C (C99 6.7.2.1p7),
17665       // but are accepted by GCC.
17666       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17667         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17668                                diag::ext_no_named_members_in_struct_union)
17669           << Record->isUnion();
17670       }
17671     }
17672   } else {
17673     ObjCIvarDecl **ClsFields =
17674       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17675     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17676       ID->setEndOfDefinitionLoc(RBrac);
17677       // Add ivar's to class's DeclContext.
17678       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17679         ClsFields[i]->setLexicalDeclContext(ID);
17680         ID->addDecl(ClsFields[i]);
17681       }
17682       // Must enforce the rule that ivars in the base classes may not be
17683       // duplicates.
17684       if (ID->getSuperClass())
17685         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17686     } else if (ObjCImplementationDecl *IMPDecl =
17687                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17688       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17689       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17690         // Ivar declared in @implementation never belongs to the implementation.
17691         // Only it is in implementation's lexical context.
17692         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17693       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17694       IMPDecl->setIvarLBraceLoc(LBrac);
17695       IMPDecl->setIvarRBraceLoc(RBrac);
17696     } else if (ObjCCategoryDecl *CDecl =
17697                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17698       // case of ivars in class extension; all other cases have been
17699       // reported as errors elsewhere.
17700       // FIXME. Class extension does not have a LocEnd field.
17701       // CDecl->setLocEnd(RBrac);
17702       // Add ivar's to class extension's DeclContext.
17703       // Diagnose redeclaration of private ivars.
17704       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17705       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17706         if (IDecl) {
17707           if (const ObjCIvarDecl *ClsIvar =
17708               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17709             Diag(ClsFields[i]->getLocation(),
17710                  diag::err_duplicate_ivar_declaration);
17711             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17712             continue;
17713           }
17714           for (const auto *Ext : IDecl->known_extensions()) {
17715             if (const ObjCIvarDecl *ClsExtIvar
17716                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17717               Diag(ClsFields[i]->getLocation(),
17718                    diag::err_duplicate_ivar_declaration);
17719               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17720               continue;
17721             }
17722           }
17723         }
17724         ClsFields[i]->setLexicalDeclContext(CDecl);
17725         CDecl->addDecl(ClsFields[i]);
17726       }
17727       CDecl->setIvarLBraceLoc(LBrac);
17728       CDecl->setIvarRBraceLoc(RBrac);
17729     }
17730   }
17731 }
17732 
17733 /// Determine whether the given integral value is representable within
17734 /// the given type T.
17735 static bool isRepresentableIntegerValue(ASTContext &Context,
17736                                         llvm::APSInt &Value,
17737                                         QualType T) {
17738   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17739          "Integral type required!");
17740   unsigned BitWidth = Context.getIntWidth(T);
17741 
17742   if (Value.isUnsigned() || Value.isNonNegative()) {
17743     if (T->isSignedIntegerOrEnumerationType())
17744       --BitWidth;
17745     return Value.getActiveBits() <= BitWidth;
17746   }
17747   return Value.getMinSignedBits() <= BitWidth;
17748 }
17749 
17750 // Given an integral type, return the next larger integral type
17751 // (or a NULL type of no such type exists).
17752 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17753   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17754   // enum checking below.
17755   assert((T->isIntegralType(Context) ||
17756          T->isEnumeralType()) && "Integral type required!");
17757   const unsigned NumTypes = 4;
17758   QualType SignedIntegralTypes[NumTypes] = {
17759     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17760   };
17761   QualType UnsignedIntegralTypes[NumTypes] = {
17762     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17763     Context.UnsignedLongLongTy
17764   };
17765 
17766   unsigned BitWidth = Context.getTypeSize(T);
17767   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17768                                                         : UnsignedIntegralTypes;
17769   for (unsigned I = 0; I != NumTypes; ++I)
17770     if (Context.getTypeSize(Types[I]) > BitWidth)
17771       return Types[I];
17772 
17773   return QualType();
17774 }
17775 
17776 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17777                                           EnumConstantDecl *LastEnumConst,
17778                                           SourceLocation IdLoc,
17779                                           IdentifierInfo *Id,
17780                                           Expr *Val) {
17781   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17782   llvm::APSInt EnumVal(IntWidth);
17783   QualType EltTy;
17784 
17785   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17786     Val = nullptr;
17787 
17788   if (Val)
17789     Val = DefaultLvalueConversion(Val).get();
17790 
17791   if (Val) {
17792     if (Enum->isDependentType() || Val->isTypeDependent())
17793       EltTy = Context.DependentTy;
17794     else {
17795       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17796       // underlying type, but do allow it in all other contexts.
17797       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17798         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17799         // constant-expression in the enumerator-definition shall be a converted
17800         // constant expression of the underlying type.
17801         EltTy = Enum->getIntegerType();
17802         ExprResult Converted =
17803           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17804                                            CCEK_Enumerator);
17805         if (Converted.isInvalid())
17806           Val = nullptr;
17807         else
17808           Val = Converted.get();
17809       } else if (!Val->isValueDependent() &&
17810                  !(Val =
17811                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17812                            .get())) {
17813         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17814       } else {
17815         if (Enum->isComplete()) {
17816           EltTy = Enum->getIntegerType();
17817 
17818           // In Obj-C and Microsoft mode, require the enumeration value to be
17819           // representable in the underlying type of the enumeration. In C++11,
17820           // we perform a non-narrowing conversion as part of converted constant
17821           // expression checking.
17822           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17823             if (Context.getTargetInfo()
17824                     .getTriple()
17825                     .isWindowsMSVCEnvironment()) {
17826               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17827             } else {
17828               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17829             }
17830           }
17831 
17832           // Cast to the underlying type.
17833           Val = ImpCastExprToType(Val, EltTy,
17834                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17835                                                          : CK_IntegralCast)
17836                     .get();
17837         } else if (getLangOpts().CPlusPlus) {
17838           // C++11 [dcl.enum]p5:
17839           //   If the underlying type is not fixed, the type of each enumerator
17840           //   is the type of its initializing value:
17841           //     - If an initializer is specified for an enumerator, the
17842           //       initializing value has the same type as the expression.
17843           EltTy = Val->getType();
17844         } else {
17845           // C99 6.7.2.2p2:
17846           //   The expression that defines the value of an enumeration constant
17847           //   shall be an integer constant expression that has a value
17848           //   representable as an int.
17849 
17850           // Complain if the value is not representable in an int.
17851           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17852             Diag(IdLoc, diag::ext_enum_value_not_int)
17853               << EnumVal.toString(10) << Val->getSourceRange()
17854               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17855           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17856             // Force the type of the expression to 'int'.
17857             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17858           }
17859           EltTy = Val->getType();
17860         }
17861       }
17862     }
17863   }
17864 
17865   if (!Val) {
17866     if (Enum->isDependentType())
17867       EltTy = Context.DependentTy;
17868     else if (!LastEnumConst) {
17869       // C++0x [dcl.enum]p5:
17870       //   If the underlying type is not fixed, the type of each enumerator
17871       //   is the type of its initializing value:
17872       //     - If no initializer is specified for the first enumerator, the
17873       //       initializing value has an unspecified integral type.
17874       //
17875       // GCC uses 'int' for its unspecified integral type, as does
17876       // C99 6.7.2.2p3.
17877       if (Enum->isFixed()) {
17878         EltTy = Enum->getIntegerType();
17879       }
17880       else {
17881         EltTy = Context.IntTy;
17882       }
17883     } else {
17884       // Assign the last value + 1.
17885       EnumVal = LastEnumConst->getInitVal();
17886       ++EnumVal;
17887       EltTy = LastEnumConst->getType();
17888 
17889       // Check for overflow on increment.
17890       if (EnumVal < LastEnumConst->getInitVal()) {
17891         // C++0x [dcl.enum]p5:
17892         //   If the underlying type is not fixed, the type of each enumerator
17893         //   is the type of its initializing value:
17894         //
17895         //     - Otherwise the type of the initializing value is the same as
17896         //       the type of the initializing value of the preceding enumerator
17897         //       unless the incremented value is not representable in that type,
17898         //       in which case the type is an unspecified integral type
17899         //       sufficient to contain the incremented value. If no such type
17900         //       exists, the program is ill-formed.
17901         QualType T = getNextLargerIntegralType(Context, EltTy);
17902         if (T.isNull() || Enum->isFixed()) {
17903           // There is no integral type larger enough to represent this
17904           // value. Complain, then allow the value to wrap around.
17905           EnumVal = LastEnumConst->getInitVal();
17906           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17907           ++EnumVal;
17908           if (Enum->isFixed())
17909             // When the underlying type is fixed, this is ill-formed.
17910             Diag(IdLoc, diag::err_enumerator_wrapped)
17911               << EnumVal.toString(10)
17912               << EltTy;
17913           else
17914             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17915               << EnumVal.toString(10);
17916         } else {
17917           EltTy = T;
17918         }
17919 
17920         // Retrieve the last enumerator's value, extent that type to the
17921         // type that is supposed to be large enough to represent the incremented
17922         // value, then increment.
17923         EnumVal = LastEnumConst->getInitVal();
17924         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17925         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17926         ++EnumVal;
17927 
17928         // If we're not in C++, diagnose the overflow of enumerator values,
17929         // which in C99 means that the enumerator value is not representable in
17930         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17931         // permits enumerator values that are representable in some larger
17932         // integral type.
17933         if (!getLangOpts().CPlusPlus && !T.isNull())
17934           Diag(IdLoc, diag::warn_enum_value_overflow);
17935       } else if (!getLangOpts().CPlusPlus &&
17936                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17937         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17938         Diag(IdLoc, diag::ext_enum_value_not_int)
17939           << EnumVal.toString(10) << 1;
17940       }
17941     }
17942   }
17943 
17944   if (!EltTy->isDependentType()) {
17945     // Make the enumerator value match the signedness and size of the
17946     // enumerator's type.
17947     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17948     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17949   }
17950 
17951   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17952                                   Val, EnumVal);
17953 }
17954 
17955 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17956                                                 SourceLocation IILoc) {
17957   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17958       !getLangOpts().CPlusPlus)
17959     return SkipBodyInfo();
17960 
17961   // We have an anonymous enum definition. Look up the first enumerator to
17962   // determine if we should merge the definition with an existing one and
17963   // skip the body.
17964   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17965                                          forRedeclarationInCurContext());
17966   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17967   if (!PrevECD)
17968     return SkipBodyInfo();
17969 
17970   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17971   NamedDecl *Hidden;
17972   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17973     SkipBodyInfo Skip;
17974     Skip.Previous = Hidden;
17975     return Skip;
17976   }
17977 
17978   return SkipBodyInfo();
17979 }
17980 
17981 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17982                               SourceLocation IdLoc, IdentifierInfo *Id,
17983                               const ParsedAttributesView &Attrs,
17984                               SourceLocation EqualLoc, Expr *Val) {
17985   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17986   EnumConstantDecl *LastEnumConst =
17987     cast_or_null<EnumConstantDecl>(lastEnumConst);
17988 
17989   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17990   // we find one that is.
17991   S = getNonFieldDeclScope(S);
17992 
17993   // Verify that there isn't already something declared with this name in this
17994   // scope.
17995   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17996   LookupName(R, S);
17997   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17998 
17999   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18000     // Maybe we will complain about the shadowed template parameter.
18001     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18002     // Just pretend that we didn't see the previous declaration.
18003     PrevDecl = nullptr;
18004   }
18005 
18006   // C++ [class.mem]p15:
18007   // If T is the name of a class, then each of the following shall have a name
18008   // different from T:
18009   // - every enumerator of every member of class T that is an unscoped
18010   // enumerated type
18011   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18012     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18013                             DeclarationNameInfo(Id, IdLoc));
18014 
18015   EnumConstantDecl *New =
18016     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18017   if (!New)
18018     return nullptr;
18019 
18020   if (PrevDecl) {
18021     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18022       // Check for other kinds of shadowing not already handled.
18023       CheckShadow(New, PrevDecl, R);
18024     }
18025 
18026     // When in C++, we may get a TagDecl with the same name; in this case the
18027     // enum constant will 'hide' the tag.
18028     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18029            "Received TagDecl when not in C++!");
18030     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18031       if (isa<EnumConstantDecl>(PrevDecl))
18032         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18033       else
18034         Diag(IdLoc, diag::err_redefinition) << Id;
18035       notePreviousDefinition(PrevDecl, IdLoc);
18036       return nullptr;
18037     }
18038   }
18039 
18040   // Process attributes.
18041   ProcessDeclAttributeList(S, New, Attrs);
18042   AddPragmaAttributes(S, New);
18043 
18044   // Register this decl in the current scope stack.
18045   New->setAccess(TheEnumDecl->getAccess());
18046   PushOnScopeChains(New, S);
18047 
18048   ActOnDocumentableDecl(New);
18049 
18050   return New;
18051 }
18052 
18053 // Returns true when the enum initial expression does not trigger the
18054 // duplicate enum warning.  A few common cases are exempted as follows:
18055 // Element2 = Element1
18056 // Element2 = Element1 + 1
18057 // Element2 = Element1 - 1
18058 // Where Element2 and Element1 are from the same enum.
18059 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18060   Expr *InitExpr = ECD->getInitExpr();
18061   if (!InitExpr)
18062     return true;
18063   InitExpr = InitExpr->IgnoreImpCasts();
18064 
18065   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18066     if (!BO->isAdditiveOp())
18067       return true;
18068     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18069     if (!IL)
18070       return true;
18071     if (IL->getValue() != 1)
18072       return true;
18073 
18074     InitExpr = BO->getLHS();
18075   }
18076 
18077   // This checks if the elements are from the same enum.
18078   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18079   if (!DRE)
18080     return true;
18081 
18082   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18083   if (!EnumConstant)
18084     return true;
18085 
18086   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18087       Enum)
18088     return true;
18089 
18090   return false;
18091 }
18092 
18093 // Emits a warning when an element is implicitly set a value that
18094 // a previous element has already been set to.
18095 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18096                                         EnumDecl *Enum, QualType EnumType) {
18097   // Avoid anonymous enums
18098   if (!Enum->getIdentifier())
18099     return;
18100 
18101   // Only check for small enums.
18102   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18103     return;
18104 
18105   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18106     return;
18107 
18108   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18109   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18110 
18111   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18112 
18113   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18114   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18115 
18116   // Use int64_t as a key to avoid needing special handling for map keys.
18117   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18118     llvm::APSInt Val = D->getInitVal();
18119     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18120   };
18121 
18122   DuplicatesVector DupVector;
18123   ValueToVectorMap EnumMap;
18124 
18125   // Populate the EnumMap with all values represented by enum constants without
18126   // an initializer.
18127   for (auto *Element : Elements) {
18128     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18129 
18130     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18131     // this constant.  Skip this enum since it may be ill-formed.
18132     if (!ECD) {
18133       return;
18134     }
18135 
18136     // Constants with initalizers are handled in the next loop.
18137     if (ECD->getInitExpr())
18138       continue;
18139 
18140     // Duplicate values are handled in the next loop.
18141     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18142   }
18143 
18144   if (EnumMap.size() == 0)
18145     return;
18146 
18147   // Create vectors for any values that has duplicates.
18148   for (auto *Element : Elements) {
18149     // The last loop returned if any constant was null.
18150     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18151     if (!ValidDuplicateEnum(ECD, Enum))
18152       continue;
18153 
18154     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18155     if (Iter == EnumMap.end())
18156       continue;
18157 
18158     DeclOrVector& Entry = Iter->second;
18159     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18160       // Ensure constants are different.
18161       if (D == ECD)
18162         continue;
18163 
18164       // Create new vector and push values onto it.
18165       auto Vec = std::make_unique<ECDVector>();
18166       Vec->push_back(D);
18167       Vec->push_back(ECD);
18168 
18169       // Update entry to point to the duplicates vector.
18170       Entry = Vec.get();
18171 
18172       // Store the vector somewhere we can consult later for quick emission of
18173       // diagnostics.
18174       DupVector.emplace_back(std::move(Vec));
18175       continue;
18176     }
18177 
18178     ECDVector *Vec = Entry.get<ECDVector*>();
18179     // Make sure constants are not added more than once.
18180     if (*Vec->begin() == ECD)
18181       continue;
18182 
18183     Vec->push_back(ECD);
18184   }
18185 
18186   // Emit diagnostics.
18187   for (const auto &Vec : DupVector) {
18188     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18189 
18190     // Emit warning for one enum constant.
18191     auto *FirstECD = Vec->front();
18192     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18193       << FirstECD << FirstECD->getInitVal().toString(10)
18194       << FirstECD->getSourceRange();
18195 
18196     // Emit one note for each of the remaining enum constants with
18197     // the same value.
18198     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18199       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18200         << ECD << ECD->getInitVal().toString(10)
18201         << ECD->getSourceRange();
18202   }
18203 }
18204 
18205 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18206                              bool AllowMask) const {
18207   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18208   assert(ED->isCompleteDefinition() && "expected enum definition");
18209 
18210   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18211   llvm::APInt &FlagBits = R.first->second;
18212 
18213   if (R.second) {
18214     for (auto *E : ED->enumerators()) {
18215       const auto &EVal = E->getInitVal();
18216       // Only single-bit enumerators introduce new flag values.
18217       if (EVal.isPowerOf2())
18218         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18219     }
18220   }
18221 
18222   // A value is in a flag enum if either its bits are a subset of the enum's
18223   // flag bits (the first condition) or we are allowing masks and the same is
18224   // true of its complement (the second condition). When masks are allowed, we
18225   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18226   //
18227   // While it's true that any value could be used as a mask, the assumption is
18228   // that a mask will have all of the insignificant bits set. Anything else is
18229   // likely a logic error.
18230   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18231   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18232 }
18233 
18234 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18235                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18236                          const ParsedAttributesView &Attrs) {
18237   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18238   QualType EnumType = Context.getTypeDeclType(Enum);
18239 
18240   ProcessDeclAttributeList(S, Enum, Attrs);
18241 
18242   if (Enum->isDependentType()) {
18243     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18244       EnumConstantDecl *ECD =
18245         cast_or_null<EnumConstantDecl>(Elements[i]);
18246       if (!ECD) continue;
18247 
18248       ECD->setType(EnumType);
18249     }
18250 
18251     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18252     return;
18253   }
18254 
18255   // TODO: If the result value doesn't fit in an int, it must be a long or long
18256   // long value.  ISO C does not support this, but GCC does as an extension,
18257   // emit a warning.
18258   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18259   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18260   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18261 
18262   // Verify that all the values are okay, compute the size of the values, and
18263   // reverse the list.
18264   unsigned NumNegativeBits = 0;
18265   unsigned NumPositiveBits = 0;
18266 
18267   // Keep track of whether all elements have type int.
18268   bool AllElementsInt = true;
18269 
18270   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18271     EnumConstantDecl *ECD =
18272       cast_or_null<EnumConstantDecl>(Elements[i]);
18273     if (!ECD) continue;  // Already issued a diagnostic.
18274 
18275     const llvm::APSInt &InitVal = ECD->getInitVal();
18276 
18277     // Keep track of the size of positive and negative values.
18278     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18279       NumPositiveBits = std::max(NumPositiveBits,
18280                                  (unsigned)InitVal.getActiveBits());
18281     else
18282       NumNegativeBits = std::max(NumNegativeBits,
18283                                  (unsigned)InitVal.getMinSignedBits());
18284 
18285     // Keep track of whether every enum element has type int (very common).
18286     if (AllElementsInt)
18287       AllElementsInt = ECD->getType() == Context.IntTy;
18288   }
18289 
18290   // Figure out the type that should be used for this enum.
18291   QualType BestType;
18292   unsigned BestWidth;
18293 
18294   // C++0x N3000 [conv.prom]p3:
18295   //   An rvalue of an unscoped enumeration type whose underlying
18296   //   type is not fixed can be converted to an rvalue of the first
18297   //   of the following types that can represent all the values of
18298   //   the enumeration: int, unsigned int, long int, unsigned long
18299   //   int, long long int, or unsigned long long int.
18300   // C99 6.4.4.3p2:
18301   //   An identifier declared as an enumeration constant has type int.
18302   // The C99 rule is modified by a gcc extension
18303   QualType BestPromotionType;
18304 
18305   bool Packed = Enum->hasAttr<PackedAttr>();
18306   // -fshort-enums is the equivalent to specifying the packed attribute on all
18307   // enum definitions.
18308   if (LangOpts.ShortEnums)
18309     Packed = true;
18310 
18311   // If the enum already has a type because it is fixed or dictated by the
18312   // target, promote that type instead of analyzing the enumerators.
18313   if (Enum->isComplete()) {
18314     BestType = Enum->getIntegerType();
18315     if (BestType->isPromotableIntegerType())
18316       BestPromotionType = Context.getPromotedIntegerType(BestType);
18317     else
18318       BestPromotionType = BestType;
18319 
18320     BestWidth = Context.getIntWidth(BestType);
18321   }
18322   else if (NumNegativeBits) {
18323     // If there is a negative value, figure out the smallest integer type (of
18324     // int/long/longlong) that fits.
18325     // If it's packed, check also if it fits a char or a short.
18326     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18327       BestType = Context.SignedCharTy;
18328       BestWidth = CharWidth;
18329     } else if (Packed && NumNegativeBits <= ShortWidth &&
18330                NumPositiveBits < ShortWidth) {
18331       BestType = Context.ShortTy;
18332       BestWidth = ShortWidth;
18333     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18334       BestType = Context.IntTy;
18335       BestWidth = IntWidth;
18336     } else {
18337       BestWidth = Context.getTargetInfo().getLongWidth();
18338 
18339       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18340         BestType = Context.LongTy;
18341       } else {
18342         BestWidth = Context.getTargetInfo().getLongLongWidth();
18343 
18344         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18345           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18346         BestType = Context.LongLongTy;
18347       }
18348     }
18349     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18350   } else {
18351     // If there is no negative value, figure out the smallest type that fits
18352     // all of the enumerator values.
18353     // If it's packed, check also if it fits a char or a short.
18354     if (Packed && NumPositiveBits <= CharWidth) {
18355       BestType = Context.UnsignedCharTy;
18356       BestPromotionType = Context.IntTy;
18357       BestWidth = CharWidth;
18358     } else if (Packed && NumPositiveBits <= ShortWidth) {
18359       BestType = Context.UnsignedShortTy;
18360       BestPromotionType = Context.IntTy;
18361       BestWidth = ShortWidth;
18362     } else if (NumPositiveBits <= IntWidth) {
18363       BestType = Context.UnsignedIntTy;
18364       BestWidth = IntWidth;
18365       BestPromotionType
18366         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18367                            ? Context.UnsignedIntTy : Context.IntTy;
18368     } else if (NumPositiveBits <=
18369                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18370       BestType = Context.UnsignedLongTy;
18371       BestPromotionType
18372         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18373                            ? Context.UnsignedLongTy : Context.LongTy;
18374     } else {
18375       BestWidth = Context.getTargetInfo().getLongLongWidth();
18376       assert(NumPositiveBits <= BestWidth &&
18377              "How could an initializer get larger than ULL?");
18378       BestType = Context.UnsignedLongLongTy;
18379       BestPromotionType
18380         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18381                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18382     }
18383   }
18384 
18385   // Loop over all of the enumerator constants, changing their types to match
18386   // the type of the enum if needed.
18387   for (auto *D : Elements) {
18388     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18389     if (!ECD) continue;  // Already issued a diagnostic.
18390 
18391     // Standard C says the enumerators have int type, but we allow, as an
18392     // extension, the enumerators to be larger than int size.  If each
18393     // enumerator value fits in an int, type it as an int, otherwise type it the
18394     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18395     // that X has type 'int', not 'unsigned'.
18396 
18397     // Determine whether the value fits into an int.
18398     llvm::APSInt InitVal = ECD->getInitVal();
18399 
18400     // If it fits into an integer type, force it.  Otherwise force it to match
18401     // the enum decl type.
18402     QualType NewTy;
18403     unsigned NewWidth;
18404     bool NewSign;
18405     if (!getLangOpts().CPlusPlus &&
18406         !Enum->isFixed() &&
18407         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18408       NewTy = Context.IntTy;
18409       NewWidth = IntWidth;
18410       NewSign = true;
18411     } else if (ECD->getType() == BestType) {
18412       // Already the right type!
18413       if (getLangOpts().CPlusPlus)
18414         // C++ [dcl.enum]p4: Following the closing brace of an
18415         // enum-specifier, each enumerator has the type of its
18416         // enumeration.
18417         ECD->setType(EnumType);
18418       continue;
18419     } else {
18420       NewTy = BestType;
18421       NewWidth = BestWidth;
18422       NewSign = BestType->isSignedIntegerOrEnumerationType();
18423     }
18424 
18425     // Adjust the APSInt value.
18426     InitVal = InitVal.extOrTrunc(NewWidth);
18427     InitVal.setIsSigned(NewSign);
18428     ECD->setInitVal(InitVal);
18429 
18430     // Adjust the Expr initializer and type.
18431     if (ECD->getInitExpr() &&
18432         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18433       ECD->setInitExpr(ImplicitCastExpr::Create(
18434           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18435           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18436     if (getLangOpts().CPlusPlus)
18437       // C++ [dcl.enum]p4: Following the closing brace of an
18438       // enum-specifier, each enumerator has the type of its
18439       // enumeration.
18440       ECD->setType(EnumType);
18441     else
18442       ECD->setType(NewTy);
18443   }
18444 
18445   Enum->completeDefinition(BestType, BestPromotionType,
18446                            NumPositiveBits, NumNegativeBits);
18447 
18448   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18449 
18450   if (Enum->isClosedFlag()) {
18451     for (Decl *D : Elements) {
18452       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18453       if (!ECD) continue;  // Already issued a diagnostic.
18454 
18455       llvm::APSInt InitVal = ECD->getInitVal();
18456       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18457           !IsValueInFlagEnum(Enum, InitVal, true))
18458         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18459           << ECD << Enum;
18460     }
18461   }
18462 
18463   // Now that the enum type is defined, ensure it's not been underaligned.
18464   if (Enum->hasAttrs())
18465     CheckAlignasUnderalignment(Enum);
18466 }
18467 
18468 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18469                                   SourceLocation StartLoc,
18470                                   SourceLocation EndLoc) {
18471   StringLiteral *AsmString = cast<StringLiteral>(expr);
18472 
18473   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18474                                                    AsmString, StartLoc,
18475                                                    EndLoc);
18476   CurContext->addDecl(New);
18477   return New;
18478 }
18479 
18480 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18481                                       IdentifierInfo* AliasName,
18482                                       SourceLocation PragmaLoc,
18483                                       SourceLocation NameLoc,
18484                                       SourceLocation AliasNameLoc) {
18485   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18486                                          LookupOrdinaryName);
18487   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18488                            AttributeCommonInfo::AS_Pragma);
18489   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18490       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18491 
18492   // If a declaration that:
18493   // 1) declares a function or a variable
18494   // 2) has external linkage
18495   // already exists, add a label attribute to it.
18496   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18497     if (isDeclExternC(PrevDecl))
18498       PrevDecl->addAttr(Attr);
18499     else
18500       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18501           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18502   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18503   } else
18504     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18505 }
18506 
18507 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18508                              SourceLocation PragmaLoc,
18509                              SourceLocation NameLoc) {
18510   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18511 
18512   if (PrevDecl) {
18513     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18514   } else {
18515     (void)WeakUndeclaredIdentifiers.insert(
18516       std::pair<IdentifierInfo*,WeakInfo>
18517         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18518   }
18519 }
18520 
18521 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18522                                 IdentifierInfo* AliasName,
18523                                 SourceLocation PragmaLoc,
18524                                 SourceLocation NameLoc,
18525                                 SourceLocation AliasNameLoc) {
18526   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18527                                     LookupOrdinaryName);
18528   WeakInfo W = WeakInfo(Name, NameLoc);
18529 
18530   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18531     if (!PrevDecl->hasAttr<AliasAttr>())
18532       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18533         DeclApplyPragmaWeak(TUScope, ND, W);
18534   } else {
18535     (void)WeakUndeclaredIdentifiers.insert(
18536       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18537   }
18538 }
18539 
18540 Decl *Sema::getObjCDeclContext() const {
18541   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18542 }
18543 
18544 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18545                                                      bool Final) {
18546   assert(FD && "Expected non-null FunctionDecl");
18547 
18548   // SYCL functions can be template, so we check if they have appropriate
18549   // attribute prior to checking if it is a template.
18550   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18551     return FunctionEmissionStatus::Emitted;
18552 
18553   // Templates are emitted when they're instantiated.
18554   if (FD->isDependentContext())
18555     return FunctionEmissionStatus::TemplateDiscarded;
18556 
18557   // Check whether this function is an externally visible definition.
18558   auto IsEmittedForExternalSymbol = [this, FD]() {
18559     // We have to check the GVA linkage of the function's *definition* -- if we
18560     // only have a declaration, we don't know whether or not the function will
18561     // be emitted, because (say) the definition could include "inline".
18562     FunctionDecl *Def = FD->getDefinition();
18563 
18564     return Def && !isDiscardableGVALinkage(
18565                       getASTContext().GetGVALinkageForFunction(Def));
18566   };
18567 
18568   if (LangOpts.OpenMPIsDevice) {
18569     // In OpenMP device mode we will not emit host only functions, or functions
18570     // we don't need due to their linkage.
18571     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18572         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18573     // DevTy may be changed later by
18574     //  #pragma omp declare target to(*) device_type(*).
18575     // Therefore DevTyhaving no value does not imply host. The emission status
18576     // will be checked again at the end of compilation unit with Final = true.
18577     if (DevTy.hasValue())
18578       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18579         return FunctionEmissionStatus::OMPDiscarded;
18580     // If we have an explicit value for the device type, or we are in a target
18581     // declare context, we need to emit all extern and used symbols.
18582     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18583       if (IsEmittedForExternalSymbol())
18584         return FunctionEmissionStatus::Emitted;
18585     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18586     // we'll omit it.
18587     if (Final)
18588       return FunctionEmissionStatus::OMPDiscarded;
18589   } else if (LangOpts.OpenMP > 45) {
18590     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18591     // function. In 5.0, no_host was introduced which might cause a function to
18592     // be ommitted.
18593     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18594         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18595     if (DevTy.hasValue())
18596       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18597         return FunctionEmissionStatus::OMPDiscarded;
18598   }
18599 
18600   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18601     return FunctionEmissionStatus::Emitted;
18602 
18603   if (LangOpts.CUDA) {
18604     // When compiling for device, host functions are never emitted.  Similarly,
18605     // when compiling for host, device and global functions are never emitted.
18606     // (Technically, we do emit a host-side stub for global functions, but this
18607     // doesn't count for our purposes here.)
18608     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18609     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18610       return FunctionEmissionStatus::CUDADiscarded;
18611     if (!LangOpts.CUDAIsDevice &&
18612         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18613       return FunctionEmissionStatus::CUDADiscarded;
18614 
18615     if (IsEmittedForExternalSymbol())
18616       return FunctionEmissionStatus::Emitted;
18617   }
18618 
18619   // Otherwise, the function is known-emitted if it's in our set of
18620   // known-emitted functions.
18621   return FunctionEmissionStatus::Unknown;
18622 }
18623 
18624 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18625   // Host-side references to a __global__ function refer to the stub, so the
18626   // function itself is never emitted and therefore should not be marked.
18627   // If we have host fn calls kernel fn calls host+device, the HD function
18628   // does not get instantiated on the host. We model this by omitting at the
18629   // call to the kernel from the callgraph. This ensures that, when compiling
18630   // for host, only HD functions actually called from the host get marked as
18631   // known-emitted.
18632   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18633          IdentifyCUDATarget(Callee) == CFT_Global;
18634 }
18635