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 /// Returns true if there hasn't been any invalid type diagnosed.
6730 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6731                                 DeclContext *DC, QualType R) {
6732   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6733   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6734   // argument.
6735   if (R->isImageType() || R->isPipeType()) {
6736     Se.Diag(D.getIdentifierLoc(),
6737             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6738         << R;
6739     D.setInvalidType();
6740     return false;
6741   }
6742 
6743   // OpenCL v1.2 s6.9.r:
6744   // The event type cannot be used to declare a program scope variable.
6745   // OpenCL v2.0 s6.9.q:
6746   // The clk_event_t and reserve_id_t types cannot be declared in program
6747   // scope.
6748   if (NULL == S->getParent()) {
6749     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6750       Se.Diag(D.getIdentifierLoc(),
6751               diag::err_invalid_type_for_program_scope_var)
6752           << R;
6753       D.setInvalidType();
6754       return false;
6755     }
6756   }
6757 
6758   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6759   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6760                                                Se.getLangOpts())) {
6761     QualType NR = R.getCanonicalType();
6762     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6763            NR->isReferenceType()) {
6764       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6765           NR->isFunctionReferenceType()) {
6766         Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer)
6767             << NR->isReferenceType();
6768         D.setInvalidType();
6769         return false;
6770       }
6771       NR = NR->getPointeeType();
6772     }
6773   }
6774 
6775   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6776                                                Se.getLangOpts())) {
6777     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6778     // half array type (unless the cl_khr_fp16 extension is enabled).
6779     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6780       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6781       D.setInvalidType();
6782       return false;
6783     }
6784   }
6785 
6786   // OpenCL v1.2 s6.9.r:
6787   // The event type cannot be used with the __local, __constant and __global
6788   // address space qualifiers.
6789   if (R->isEventT()) {
6790     if (R.getAddressSpace() != LangAS::opencl_private) {
6791       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6792       D.setInvalidType();
6793       return false;
6794     }
6795   }
6796 
6797   // C++ for OpenCL does not allow the thread_local storage qualifier.
6798   // OpenCL C does not support thread_local either, and
6799   // also reject all other thread storage class specifiers.
6800   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6801   if (TSC != TSCS_unspecified) {
6802     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6803     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6804             diag::err_opencl_unknown_type_specifier)
6805         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6806         << DeclSpec::getSpecifierName(TSC) << 1;
6807     D.setInvalidType();
6808     return false;
6809   }
6810 
6811   if (R->isSamplerT()) {
6812     // OpenCL v1.2 s6.9.b p4:
6813     // The sampler type cannot be used with the __local and __global address
6814     // space qualifiers.
6815     if (R.getAddressSpace() == LangAS::opencl_local ||
6816         R.getAddressSpace() == LangAS::opencl_global) {
6817       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6818       D.setInvalidType();
6819     }
6820 
6821     // OpenCL v1.2 s6.12.14.1:
6822     // A global sampler must be declared with either the constant address
6823     // space qualifier or with the const qualifier.
6824     if (DC->isTranslationUnit() &&
6825         !(R.getAddressSpace() == LangAS::opencl_constant ||
6826           R.isConstQualified())) {
6827       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6828       D.setInvalidType();
6829     }
6830     if (D.isInvalidType())
6831       return false;
6832   }
6833   return true;
6834 }
6835 
6836 template <typename AttrTy>
6837 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6838   const TypedefNameDecl *TND = TT->getDecl();
6839   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6840     AttrTy *Clone = Attribute->clone(S.Context);
6841     Clone->setInherited(true);
6842     D->addAttr(Clone);
6843   }
6844 }
6845 
6846 NamedDecl *Sema::ActOnVariableDeclarator(
6847     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6848     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6849     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6850   QualType R = TInfo->getType();
6851   DeclarationName Name = GetNameForDeclarator(D).getName();
6852 
6853   IdentifierInfo *II = Name.getAsIdentifierInfo();
6854 
6855   if (D.isDecompositionDeclarator()) {
6856     // Take the name of the first declarator as our name for diagnostic
6857     // purposes.
6858     auto &Decomp = D.getDecompositionDeclarator();
6859     if (!Decomp.bindings().empty()) {
6860       II = Decomp.bindings()[0].Name;
6861       Name = II;
6862     }
6863   } else if (!II) {
6864     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6865     return nullptr;
6866   }
6867 
6868 
6869   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6870   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6871 
6872   // dllimport globals without explicit storage class are treated as extern. We
6873   // have to change the storage class this early to get the right DeclContext.
6874   if (SC == SC_None && !DC->isRecord() &&
6875       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6876       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6877     SC = SC_Extern;
6878 
6879   DeclContext *OriginalDC = DC;
6880   bool IsLocalExternDecl = SC == SC_Extern &&
6881                            adjustContextForLocalExternDecl(DC);
6882 
6883   if (SCSpec == DeclSpec::SCS_mutable) {
6884     // mutable can only appear on non-static class members, so it's always
6885     // an error here
6886     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6887     D.setInvalidType();
6888     SC = SC_None;
6889   }
6890 
6891   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6892       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6893                               D.getDeclSpec().getStorageClassSpecLoc())) {
6894     // In C++11, the 'register' storage class specifier is deprecated.
6895     // Suppress the warning in system macros, it's used in macros in some
6896     // popular C system headers, such as in glibc's htonl() macro.
6897     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6898          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6899                                    : diag::warn_deprecated_register)
6900       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6901   }
6902 
6903   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6904 
6905   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6906     // C99 6.9p2: The storage-class specifiers auto and register shall not
6907     // appear in the declaration specifiers in an external declaration.
6908     // Global Register+Asm is a GNU extension we support.
6909     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6910       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6911       D.setInvalidType();
6912     }
6913   }
6914 
6915   // If this variable has a VLA type and an initializer, try to
6916   // fold to a constant-sized type. This is otherwise invalid.
6917   if (D.hasInitializer() && R->isVariableArrayType())
6918     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6919                                     /*DiagID=*/0);
6920 
6921   bool IsMemberSpecialization = false;
6922   bool IsVariableTemplateSpecialization = false;
6923   bool IsPartialSpecialization = false;
6924   bool IsVariableTemplate = false;
6925   VarDecl *NewVD = nullptr;
6926   VarTemplateDecl *NewTemplate = nullptr;
6927   TemplateParameterList *TemplateParams = nullptr;
6928   if (!getLangOpts().CPlusPlus) {
6929     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6930                             II, R, TInfo, SC);
6931 
6932     if (R->getContainedDeducedType())
6933       ParsingInitForAutoVars.insert(NewVD);
6934 
6935     if (D.isInvalidType())
6936       NewVD->setInvalidDecl();
6937 
6938     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6939         NewVD->hasLocalStorage())
6940       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6941                             NTCUC_AutoVar, NTCUK_Destruct);
6942   } else {
6943     bool Invalid = false;
6944 
6945     if (DC->isRecord() && !CurContext->isRecord()) {
6946       // This is an out-of-line definition of a static data member.
6947       switch (SC) {
6948       case SC_None:
6949         break;
6950       case SC_Static:
6951         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6952              diag::err_static_out_of_line)
6953           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6954         break;
6955       case SC_Auto:
6956       case SC_Register:
6957       case SC_Extern:
6958         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6959         // to names of variables declared in a block or to function parameters.
6960         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6961         // of class members
6962 
6963         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6964              diag::err_storage_class_for_static_member)
6965           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6966         break;
6967       case SC_PrivateExtern:
6968         llvm_unreachable("C storage class in c++!");
6969       }
6970     }
6971 
6972     if (SC == SC_Static && CurContext->isRecord()) {
6973       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6974         // Walk up the enclosing DeclContexts to check for any that are
6975         // incompatible with static data members.
6976         const DeclContext *FunctionOrMethod = nullptr;
6977         const CXXRecordDecl *AnonStruct = nullptr;
6978         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6979           if (Ctxt->isFunctionOrMethod()) {
6980             FunctionOrMethod = Ctxt;
6981             break;
6982           }
6983           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6984           if (ParentDecl && !ParentDecl->getDeclName()) {
6985             AnonStruct = ParentDecl;
6986             break;
6987           }
6988         }
6989         if (FunctionOrMethod) {
6990           // C++ [class.static.data]p5: A local class shall not have static data
6991           // members.
6992           Diag(D.getIdentifierLoc(),
6993                diag::err_static_data_member_not_allowed_in_local_class)
6994             << Name << RD->getDeclName() << RD->getTagKind();
6995         } else if (AnonStruct) {
6996           // C++ [class.static.data]p4: Unnamed classes and classes contained
6997           // directly or indirectly within unnamed classes shall not contain
6998           // static data members.
6999           Diag(D.getIdentifierLoc(),
7000                diag::err_static_data_member_not_allowed_in_anon_struct)
7001             << Name << AnonStruct->getTagKind();
7002           Invalid = true;
7003         } else if (RD->isUnion()) {
7004           // C++98 [class.union]p1: If a union contains a static data member,
7005           // the program is ill-formed. C++11 drops this restriction.
7006           Diag(D.getIdentifierLoc(),
7007                getLangOpts().CPlusPlus11
7008                  ? diag::warn_cxx98_compat_static_data_member_in_union
7009                  : diag::ext_static_data_member_in_union) << Name;
7010         }
7011       }
7012     }
7013 
7014     // Match up the template parameter lists with the scope specifier, then
7015     // determine whether we have a template or a template specialization.
7016     bool InvalidScope = false;
7017     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7018         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7019         D.getCXXScopeSpec(),
7020         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7021             ? D.getName().TemplateId
7022             : nullptr,
7023         TemplateParamLists,
7024         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7025     Invalid |= InvalidScope;
7026 
7027     if (TemplateParams) {
7028       if (!TemplateParams->size() &&
7029           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7030         // There is an extraneous 'template<>' for this variable. Complain
7031         // about it, but allow the declaration of the variable.
7032         Diag(TemplateParams->getTemplateLoc(),
7033              diag::err_template_variable_noparams)
7034           << II
7035           << SourceRange(TemplateParams->getTemplateLoc(),
7036                          TemplateParams->getRAngleLoc());
7037         TemplateParams = nullptr;
7038       } else {
7039         // Check that we can declare a template here.
7040         if (CheckTemplateDeclScope(S, TemplateParams))
7041           return nullptr;
7042 
7043         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7044           // This is an explicit specialization or a partial specialization.
7045           IsVariableTemplateSpecialization = true;
7046           IsPartialSpecialization = TemplateParams->size() > 0;
7047         } else { // if (TemplateParams->size() > 0)
7048           // This is a template declaration.
7049           IsVariableTemplate = true;
7050 
7051           // Only C++1y supports variable templates (N3651).
7052           Diag(D.getIdentifierLoc(),
7053                getLangOpts().CPlusPlus14
7054                    ? diag::warn_cxx11_compat_variable_template
7055                    : diag::ext_variable_template);
7056         }
7057       }
7058     } else {
7059       // Check that we can declare a member specialization here.
7060       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7061           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7062         return nullptr;
7063       assert((Invalid ||
7064               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7065              "should have a 'template<>' for this decl");
7066     }
7067 
7068     if (IsVariableTemplateSpecialization) {
7069       SourceLocation TemplateKWLoc =
7070           TemplateParamLists.size() > 0
7071               ? TemplateParamLists[0]->getTemplateLoc()
7072               : SourceLocation();
7073       DeclResult Res = ActOnVarTemplateSpecialization(
7074           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7075           IsPartialSpecialization);
7076       if (Res.isInvalid())
7077         return nullptr;
7078       NewVD = cast<VarDecl>(Res.get());
7079       AddToScope = false;
7080     } else if (D.isDecompositionDeclarator()) {
7081       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7082                                         D.getIdentifierLoc(), R, TInfo, SC,
7083                                         Bindings);
7084     } else
7085       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7086                               D.getIdentifierLoc(), II, R, TInfo, SC);
7087 
7088     // If this is supposed to be a variable template, create it as such.
7089     if (IsVariableTemplate) {
7090       NewTemplate =
7091           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7092                                   TemplateParams, NewVD);
7093       NewVD->setDescribedVarTemplate(NewTemplate);
7094     }
7095 
7096     // If this decl has an auto type in need of deduction, make a note of the
7097     // Decl so we can diagnose uses of it in its own initializer.
7098     if (R->getContainedDeducedType())
7099       ParsingInitForAutoVars.insert(NewVD);
7100 
7101     if (D.isInvalidType() || Invalid) {
7102       NewVD->setInvalidDecl();
7103       if (NewTemplate)
7104         NewTemplate->setInvalidDecl();
7105     }
7106 
7107     SetNestedNameSpecifier(*this, NewVD, D);
7108 
7109     // If we have any template parameter lists that don't directly belong to
7110     // the variable (matching the scope specifier), store them.
7111     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7112     if (TemplateParamLists.size() > VDTemplateParamLists)
7113       NewVD->setTemplateParameterListsInfo(
7114           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7115   }
7116 
7117   if (D.getDeclSpec().isInlineSpecified()) {
7118     if (!getLangOpts().CPlusPlus) {
7119       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7120           << 0;
7121     } else if (CurContext->isFunctionOrMethod()) {
7122       // 'inline' is not allowed on block scope variable declaration.
7123       Diag(D.getDeclSpec().getInlineSpecLoc(),
7124            diag::err_inline_declaration_block_scope) << Name
7125         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7126     } else {
7127       Diag(D.getDeclSpec().getInlineSpecLoc(),
7128            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7129                                      : diag::ext_inline_variable);
7130       NewVD->setInlineSpecified();
7131     }
7132   }
7133 
7134   // Set the lexical context. If the declarator has a C++ scope specifier, the
7135   // lexical context will be different from the semantic context.
7136   NewVD->setLexicalDeclContext(CurContext);
7137   if (NewTemplate)
7138     NewTemplate->setLexicalDeclContext(CurContext);
7139 
7140   if (IsLocalExternDecl) {
7141     if (D.isDecompositionDeclarator())
7142       for (auto *B : Bindings)
7143         B->setLocalExternDecl();
7144     else
7145       NewVD->setLocalExternDecl();
7146   }
7147 
7148   bool EmitTLSUnsupportedError = false;
7149   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7150     // C++11 [dcl.stc]p4:
7151     //   When thread_local is applied to a variable of block scope the
7152     //   storage-class-specifier static is implied if it does not appear
7153     //   explicitly.
7154     // Core issue: 'static' is not implied if the variable is declared
7155     //   'extern'.
7156     if (NewVD->hasLocalStorage() &&
7157         (SCSpec != DeclSpec::SCS_unspecified ||
7158          TSCS != DeclSpec::TSCS_thread_local ||
7159          !DC->isFunctionOrMethod()))
7160       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7161            diag::err_thread_non_global)
7162         << DeclSpec::getSpecifierName(TSCS);
7163     else if (!Context.getTargetInfo().isTLSSupported()) {
7164       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7165           getLangOpts().SYCLIsDevice) {
7166         // Postpone error emission until we've collected attributes required to
7167         // figure out whether it's a host or device variable and whether the
7168         // error should be ignored.
7169         EmitTLSUnsupportedError = true;
7170         // We still need to mark the variable as TLS so it shows up in AST with
7171         // proper storage class for other tools to use even if we're not going
7172         // to emit any code for it.
7173         NewVD->setTSCSpec(TSCS);
7174       } else
7175         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7176              diag::err_thread_unsupported);
7177     } else
7178       NewVD->setTSCSpec(TSCS);
7179   }
7180 
7181   switch (D.getDeclSpec().getConstexprSpecifier()) {
7182   case ConstexprSpecKind::Unspecified:
7183     break;
7184 
7185   case ConstexprSpecKind::Consteval:
7186     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7187          diag::err_constexpr_wrong_decl_kind)
7188         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7189     LLVM_FALLTHROUGH;
7190 
7191   case ConstexprSpecKind::Constexpr:
7192     NewVD->setConstexpr(true);
7193     MaybeAddCUDAConstantAttr(NewVD);
7194     // C++1z [dcl.spec.constexpr]p1:
7195     //   A static data member declared with the constexpr specifier is
7196     //   implicitly an inline variable.
7197     if (NewVD->isStaticDataMember() &&
7198         (getLangOpts().CPlusPlus17 ||
7199          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7200       NewVD->setImplicitlyInline();
7201     break;
7202 
7203   case ConstexprSpecKind::Constinit:
7204     if (!NewVD->hasGlobalStorage())
7205       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7206            diag::err_constinit_local_variable);
7207     else
7208       NewVD->addAttr(ConstInitAttr::Create(
7209           Context, D.getDeclSpec().getConstexprSpecLoc(),
7210           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7211     break;
7212   }
7213 
7214   // C99 6.7.4p3
7215   //   An inline definition of a function with external linkage shall
7216   //   not contain a definition of a modifiable object with static or
7217   //   thread storage duration...
7218   // We only apply this when the function is required to be defined
7219   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7220   // that a local variable with thread storage duration still has to
7221   // be marked 'static'.  Also note that it's possible to get these
7222   // semantics in C++ using __attribute__((gnu_inline)).
7223   if (SC == SC_Static && S->getFnParent() != nullptr &&
7224       !NewVD->getType().isConstQualified()) {
7225     FunctionDecl *CurFD = getCurFunctionDecl();
7226     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7227       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7228            diag::warn_static_local_in_extern_inline);
7229       MaybeSuggestAddingStaticToDecl(CurFD);
7230     }
7231   }
7232 
7233   if (D.getDeclSpec().isModulePrivateSpecified()) {
7234     if (IsVariableTemplateSpecialization)
7235       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7236           << (IsPartialSpecialization ? 1 : 0)
7237           << FixItHint::CreateRemoval(
7238                  D.getDeclSpec().getModulePrivateSpecLoc());
7239     else if (IsMemberSpecialization)
7240       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7241         << 2
7242         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7243     else if (NewVD->hasLocalStorage())
7244       Diag(NewVD->getLocation(), diag::err_module_private_local)
7245           << 0 << NewVD
7246           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7247           << FixItHint::CreateRemoval(
7248                  D.getDeclSpec().getModulePrivateSpecLoc());
7249     else {
7250       NewVD->setModulePrivate();
7251       if (NewTemplate)
7252         NewTemplate->setModulePrivate();
7253       for (auto *B : Bindings)
7254         B->setModulePrivate();
7255     }
7256   }
7257 
7258   if (getLangOpts().OpenCL) {
7259 
7260     deduceOpenCLAddressSpace(NewVD);
7261 
7262     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7263   }
7264 
7265   // Handle attributes prior to checking for duplicates in MergeVarDecl
7266   ProcessDeclAttributes(S, NewVD, D);
7267 
7268   // FIXME: This is probably the wrong location to be doing this and we should
7269   // probably be doing this for more attributes (especially for function
7270   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7271   // the code to copy attributes would be generated by TableGen.
7272   if (R->isFunctionPointerType())
7273     if (const auto *TT = R->getAs<TypedefType>())
7274       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7275 
7276   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7277       getLangOpts().SYCLIsDevice) {
7278     if (EmitTLSUnsupportedError &&
7279         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7280          (getLangOpts().OpenMPIsDevice &&
7281           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7282       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7283            diag::err_thread_unsupported);
7284 
7285     if (EmitTLSUnsupportedError &&
7286         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7287       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7288     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7289     // storage [duration]."
7290     if (SC == SC_None && S->getFnParent() != nullptr &&
7291         (NewVD->hasAttr<CUDASharedAttr>() ||
7292          NewVD->hasAttr<CUDAConstantAttr>())) {
7293       NewVD->setStorageClass(SC_Static);
7294     }
7295   }
7296 
7297   // Ensure that dllimport globals without explicit storage class are treated as
7298   // extern. The storage class is set above using parsed attributes. Now we can
7299   // check the VarDecl itself.
7300   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7301          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7302          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7303 
7304   // In auto-retain/release, infer strong retension for variables of
7305   // retainable type.
7306   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7307     NewVD->setInvalidDecl();
7308 
7309   // Handle GNU asm-label extension (encoded as an attribute).
7310   if (Expr *E = (Expr*)D.getAsmLabel()) {
7311     // The parser guarantees this is a string.
7312     StringLiteral *SE = cast<StringLiteral>(E);
7313     StringRef Label = SE->getString();
7314     if (S->getFnParent() != nullptr) {
7315       switch (SC) {
7316       case SC_None:
7317       case SC_Auto:
7318         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7319         break;
7320       case SC_Register:
7321         // Local Named register
7322         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7323             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7324           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7325         break;
7326       case SC_Static:
7327       case SC_Extern:
7328       case SC_PrivateExtern:
7329         break;
7330       }
7331     } else if (SC == SC_Register) {
7332       // Global Named register
7333       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7334         const auto &TI = Context.getTargetInfo();
7335         bool HasSizeMismatch;
7336 
7337         if (!TI.isValidGCCRegisterName(Label))
7338           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7339         else if (!TI.validateGlobalRegisterVariable(Label,
7340                                                     Context.getTypeSize(R),
7341                                                     HasSizeMismatch))
7342           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7343         else if (HasSizeMismatch)
7344           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7345       }
7346 
7347       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7348         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7349         NewVD->setInvalidDecl(true);
7350       }
7351     }
7352 
7353     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7354                                         /*IsLiteralLabel=*/true,
7355                                         SE->getStrTokenLoc(0)));
7356   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7357     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7358       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7359     if (I != ExtnameUndeclaredIdentifiers.end()) {
7360       if (isDeclExternC(NewVD)) {
7361         NewVD->addAttr(I->second);
7362         ExtnameUndeclaredIdentifiers.erase(I);
7363       } else
7364         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7365             << /*Variable*/1 << NewVD;
7366     }
7367   }
7368 
7369   // Find the shadowed declaration before filtering for scope.
7370   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7371                                 ? getShadowedDeclaration(NewVD, Previous)
7372                                 : nullptr;
7373 
7374   // Don't consider existing declarations that are in a different
7375   // scope and are out-of-semantic-context declarations (if the new
7376   // declaration has linkage).
7377   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7378                        D.getCXXScopeSpec().isNotEmpty() ||
7379                        IsMemberSpecialization ||
7380                        IsVariableTemplateSpecialization);
7381 
7382   // Check whether the previous declaration is in the same block scope. This
7383   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7384   if (getLangOpts().CPlusPlus &&
7385       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7386     NewVD->setPreviousDeclInSameBlockScope(
7387         Previous.isSingleResult() && !Previous.isShadowed() &&
7388         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7389 
7390   if (!getLangOpts().CPlusPlus) {
7391     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7392   } else {
7393     // If this is an explicit specialization of a static data member, check it.
7394     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7395         CheckMemberSpecialization(NewVD, Previous))
7396       NewVD->setInvalidDecl();
7397 
7398     // Merge the decl with the existing one if appropriate.
7399     if (!Previous.empty()) {
7400       if (Previous.isSingleResult() &&
7401           isa<FieldDecl>(Previous.getFoundDecl()) &&
7402           D.getCXXScopeSpec().isSet()) {
7403         // The user tried to define a non-static data member
7404         // out-of-line (C++ [dcl.meaning]p1).
7405         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7406           << D.getCXXScopeSpec().getRange();
7407         Previous.clear();
7408         NewVD->setInvalidDecl();
7409       }
7410     } else if (D.getCXXScopeSpec().isSet()) {
7411       // No previous declaration in the qualifying scope.
7412       Diag(D.getIdentifierLoc(), diag::err_no_member)
7413         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7414         << D.getCXXScopeSpec().getRange();
7415       NewVD->setInvalidDecl();
7416     }
7417 
7418     if (!IsVariableTemplateSpecialization)
7419       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7420 
7421     if (NewTemplate) {
7422       VarTemplateDecl *PrevVarTemplate =
7423           NewVD->getPreviousDecl()
7424               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7425               : nullptr;
7426 
7427       // Check the template parameter list of this declaration, possibly
7428       // merging in the template parameter list from the previous variable
7429       // template declaration.
7430       if (CheckTemplateParameterList(
7431               TemplateParams,
7432               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7433                               : nullptr,
7434               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7435                DC->isDependentContext())
7436                   ? TPC_ClassTemplateMember
7437                   : TPC_VarTemplate))
7438         NewVD->setInvalidDecl();
7439 
7440       // If we are providing an explicit specialization of a static variable
7441       // template, make a note of that.
7442       if (PrevVarTemplate &&
7443           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7444         PrevVarTemplate->setMemberSpecialization();
7445     }
7446   }
7447 
7448   // Diagnose shadowed variables iff this isn't a redeclaration.
7449   if (ShadowedDecl && !D.isRedeclaration())
7450     CheckShadow(NewVD, ShadowedDecl, Previous);
7451 
7452   ProcessPragmaWeak(S, NewVD);
7453 
7454   // If this is the first declaration of an extern C variable, update
7455   // the map of such variables.
7456   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7457       isIncompleteDeclExternC(*this, NewVD))
7458     RegisterLocallyScopedExternCDecl(NewVD, S);
7459 
7460   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7461     MangleNumberingContext *MCtx;
7462     Decl *ManglingContextDecl;
7463     std::tie(MCtx, ManglingContextDecl) =
7464         getCurrentMangleNumberContext(NewVD->getDeclContext());
7465     if (MCtx) {
7466       Context.setManglingNumber(
7467           NewVD, MCtx->getManglingNumber(
7468                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7469       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7470     }
7471   }
7472 
7473   // Special handling of variable named 'main'.
7474   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7475       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7476       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7477 
7478     // C++ [basic.start.main]p3
7479     // A program that declares a variable main at global scope is ill-formed.
7480     if (getLangOpts().CPlusPlus)
7481       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7482 
7483     // In C, and external-linkage variable named main results in undefined
7484     // behavior.
7485     else if (NewVD->hasExternalFormalLinkage())
7486       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7487   }
7488 
7489   if (D.isRedeclaration() && !Previous.empty()) {
7490     NamedDecl *Prev = Previous.getRepresentativeDecl();
7491     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7492                                    D.isFunctionDefinition());
7493   }
7494 
7495   if (NewTemplate) {
7496     if (NewVD->isInvalidDecl())
7497       NewTemplate->setInvalidDecl();
7498     ActOnDocumentableDecl(NewTemplate);
7499     return NewTemplate;
7500   }
7501 
7502   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7503     CompleteMemberSpecialization(NewVD, Previous);
7504 
7505   return NewVD;
7506 }
7507 
7508 /// Enum describing the %select options in diag::warn_decl_shadow.
7509 enum ShadowedDeclKind {
7510   SDK_Local,
7511   SDK_Global,
7512   SDK_StaticMember,
7513   SDK_Field,
7514   SDK_Typedef,
7515   SDK_Using,
7516   SDK_StructuredBinding
7517 };
7518 
7519 /// Determine what kind of declaration we're shadowing.
7520 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7521                                                 const DeclContext *OldDC) {
7522   if (isa<TypeAliasDecl>(ShadowedDecl))
7523     return SDK_Using;
7524   else if (isa<TypedefDecl>(ShadowedDecl))
7525     return SDK_Typedef;
7526   else if (isa<BindingDecl>(ShadowedDecl))
7527     return SDK_StructuredBinding;
7528   else if (isa<RecordDecl>(OldDC))
7529     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7530 
7531   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7532 }
7533 
7534 /// Return the location of the capture if the given lambda captures the given
7535 /// variable \p VD, or an invalid source location otherwise.
7536 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7537                                          const VarDecl *VD) {
7538   for (const Capture &Capture : LSI->Captures) {
7539     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7540       return Capture.getLocation();
7541   }
7542   return SourceLocation();
7543 }
7544 
7545 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7546                                      const LookupResult &R) {
7547   // Only diagnose if we're shadowing an unambiguous field or variable.
7548   if (R.getResultKind() != LookupResult::Found)
7549     return false;
7550 
7551   // Return false if warning is ignored.
7552   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7553 }
7554 
7555 /// Return the declaration shadowed by the given variable \p D, or null
7556 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7557 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7558                                         const LookupResult &R) {
7559   if (!shouldWarnIfShadowedDecl(Diags, R))
7560     return nullptr;
7561 
7562   // Don't diagnose declarations at file scope.
7563   if (D->hasGlobalStorage())
7564     return nullptr;
7565 
7566   NamedDecl *ShadowedDecl = R.getFoundDecl();
7567   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7568                                                             : nullptr;
7569 }
7570 
7571 /// Return the declaration shadowed by the given typedef \p D, or null
7572 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7573 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7574                                         const LookupResult &R) {
7575   // Don't warn if typedef declaration is part of a class
7576   if (D->getDeclContext()->isRecord())
7577     return nullptr;
7578 
7579   if (!shouldWarnIfShadowedDecl(Diags, R))
7580     return nullptr;
7581 
7582   NamedDecl *ShadowedDecl = R.getFoundDecl();
7583   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7584 }
7585 
7586 /// Return the declaration shadowed by the given variable \p D, or null
7587 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7588 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7589                                         const LookupResult &R) {
7590   if (!shouldWarnIfShadowedDecl(Diags, R))
7591     return nullptr;
7592 
7593   NamedDecl *ShadowedDecl = R.getFoundDecl();
7594   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7595                                                             : nullptr;
7596 }
7597 
7598 /// Diagnose variable or built-in function shadowing.  Implements
7599 /// -Wshadow.
7600 ///
7601 /// This method is called whenever a VarDecl is added to a "useful"
7602 /// scope.
7603 ///
7604 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7605 /// \param R the lookup of the name
7606 ///
7607 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7608                        const LookupResult &R) {
7609   DeclContext *NewDC = D->getDeclContext();
7610 
7611   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7612     // Fields are not shadowed by variables in C++ static methods.
7613     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7614       if (MD->isStatic())
7615         return;
7616 
7617     // Fields shadowed by constructor parameters are a special case. Usually
7618     // the constructor initializes the field with the parameter.
7619     if (isa<CXXConstructorDecl>(NewDC))
7620       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7621         // Remember that this was shadowed so we can either warn about its
7622         // modification or its existence depending on warning settings.
7623         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7624         return;
7625       }
7626   }
7627 
7628   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7629     if (shadowedVar->isExternC()) {
7630       // For shadowing external vars, make sure that we point to the global
7631       // declaration, not a locally scoped extern declaration.
7632       for (auto I : shadowedVar->redecls())
7633         if (I->isFileVarDecl()) {
7634           ShadowedDecl = I;
7635           break;
7636         }
7637     }
7638 
7639   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7640 
7641   unsigned WarningDiag = diag::warn_decl_shadow;
7642   SourceLocation CaptureLoc;
7643   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7644       isa<CXXMethodDecl>(NewDC)) {
7645     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7646       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7647         if (RD->getLambdaCaptureDefault() == LCD_None) {
7648           // Try to avoid warnings for lambdas with an explicit capture list.
7649           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7650           // Warn only when the lambda captures the shadowed decl explicitly.
7651           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7652           if (CaptureLoc.isInvalid())
7653             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7654         } else {
7655           // Remember that this was shadowed so we can avoid the warning if the
7656           // shadowed decl isn't captured and the warning settings allow it.
7657           cast<LambdaScopeInfo>(getCurFunction())
7658               ->ShadowingDecls.push_back(
7659                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7660           return;
7661         }
7662       }
7663 
7664       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7665         // A variable can't shadow a local variable in an enclosing scope, if
7666         // they are separated by a non-capturing declaration context.
7667         for (DeclContext *ParentDC = NewDC;
7668              ParentDC && !ParentDC->Equals(OldDC);
7669              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7670           // Only block literals, captured statements, and lambda expressions
7671           // can capture; other scopes don't.
7672           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7673               !isLambdaCallOperator(ParentDC)) {
7674             return;
7675           }
7676         }
7677       }
7678     }
7679   }
7680 
7681   // Only warn about certain kinds of shadowing for class members.
7682   if (NewDC && NewDC->isRecord()) {
7683     // In particular, don't warn about shadowing non-class members.
7684     if (!OldDC->isRecord())
7685       return;
7686 
7687     // TODO: should we warn about static data members shadowing
7688     // static data members from base classes?
7689 
7690     // TODO: don't diagnose for inaccessible shadowed members.
7691     // This is hard to do perfectly because we might friend the
7692     // shadowing context, but that's just a false negative.
7693   }
7694 
7695 
7696   DeclarationName Name = R.getLookupName();
7697 
7698   // Emit warning and note.
7699   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7700     return;
7701   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7702   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7703   if (!CaptureLoc.isInvalid())
7704     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7705         << Name << /*explicitly*/ 1;
7706   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7707 }
7708 
7709 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7710 /// when these variables are captured by the lambda.
7711 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7712   for (const auto &Shadow : LSI->ShadowingDecls) {
7713     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7714     // Try to avoid the warning when the shadowed decl isn't captured.
7715     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7716     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7717     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7718                                        ? diag::warn_decl_shadow_uncaptured_local
7719                                        : diag::warn_decl_shadow)
7720         << Shadow.VD->getDeclName()
7721         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7722     if (!CaptureLoc.isInvalid())
7723       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7724           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7725     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7726   }
7727 }
7728 
7729 /// Check -Wshadow without the advantage of a previous lookup.
7730 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7731   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7732     return;
7733 
7734   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7735                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7736   LookupName(R, S);
7737   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7738     CheckShadow(D, ShadowedDecl, R);
7739 }
7740 
7741 /// Check if 'E', which is an expression that is about to be modified, refers
7742 /// to a constructor parameter that shadows a field.
7743 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7744   // Quickly ignore expressions that can't be shadowing ctor parameters.
7745   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7746     return;
7747   E = E->IgnoreParenImpCasts();
7748   auto *DRE = dyn_cast<DeclRefExpr>(E);
7749   if (!DRE)
7750     return;
7751   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7752   auto I = ShadowingDecls.find(D);
7753   if (I == ShadowingDecls.end())
7754     return;
7755   const NamedDecl *ShadowedDecl = I->second;
7756   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7757   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7758   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7759   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7760 
7761   // Avoid issuing multiple warnings about the same decl.
7762   ShadowingDecls.erase(I);
7763 }
7764 
7765 /// Check for conflict between this global or extern "C" declaration and
7766 /// previous global or extern "C" declarations. This is only used in C++.
7767 template<typename T>
7768 static bool checkGlobalOrExternCConflict(
7769     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7770   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7771   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7772 
7773   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7774     // The common case: this global doesn't conflict with any extern "C"
7775     // declaration.
7776     return false;
7777   }
7778 
7779   if (Prev) {
7780     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7781       // Both the old and new declarations have C language linkage. This is a
7782       // redeclaration.
7783       Previous.clear();
7784       Previous.addDecl(Prev);
7785       return true;
7786     }
7787 
7788     // This is a global, non-extern "C" declaration, and there is a previous
7789     // non-global extern "C" declaration. Diagnose if this is a variable
7790     // declaration.
7791     if (!isa<VarDecl>(ND))
7792       return false;
7793   } else {
7794     // The declaration is extern "C". Check for any declaration in the
7795     // translation unit which might conflict.
7796     if (IsGlobal) {
7797       // We have already performed the lookup into the translation unit.
7798       IsGlobal = false;
7799       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7800            I != E; ++I) {
7801         if (isa<VarDecl>(*I)) {
7802           Prev = *I;
7803           break;
7804         }
7805       }
7806     } else {
7807       DeclContext::lookup_result R =
7808           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7809       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7810            I != E; ++I) {
7811         if (isa<VarDecl>(*I)) {
7812           Prev = *I;
7813           break;
7814         }
7815         // FIXME: If we have any other entity with this name in global scope,
7816         // the declaration is ill-formed, but that is a defect: it breaks the
7817         // 'stat' hack, for instance. Only variables can have mangled name
7818         // clashes with extern "C" declarations, so only they deserve a
7819         // diagnostic.
7820       }
7821     }
7822 
7823     if (!Prev)
7824       return false;
7825   }
7826 
7827   // Use the first declaration's location to ensure we point at something which
7828   // is lexically inside an extern "C" linkage-spec.
7829   assert(Prev && "should have found a previous declaration to diagnose");
7830   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7831     Prev = FD->getFirstDecl();
7832   else
7833     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7834 
7835   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7836     << IsGlobal << ND;
7837   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7838     << IsGlobal;
7839   return false;
7840 }
7841 
7842 /// Apply special rules for handling extern "C" declarations. Returns \c true
7843 /// if we have found that this is a redeclaration of some prior entity.
7844 ///
7845 /// Per C++ [dcl.link]p6:
7846 ///   Two declarations [for a function or variable] with C language linkage
7847 ///   with the same name that appear in different scopes refer to the same
7848 ///   [entity]. An entity with C language linkage shall not be declared with
7849 ///   the same name as an entity in global scope.
7850 template<typename T>
7851 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7852                                                   LookupResult &Previous) {
7853   if (!S.getLangOpts().CPlusPlus) {
7854     // In C, when declaring a global variable, look for a corresponding 'extern'
7855     // variable declared in function scope. We don't need this in C++, because
7856     // we find local extern decls in the surrounding file-scope DeclContext.
7857     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7858       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7859         Previous.clear();
7860         Previous.addDecl(Prev);
7861         return true;
7862       }
7863     }
7864     return false;
7865   }
7866 
7867   // A declaration in the translation unit can conflict with an extern "C"
7868   // declaration.
7869   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7870     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7871 
7872   // An extern "C" declaration can conflict with a declaration in the
7873   // translation unit or can be a redeclaration of an extern "C" declaration
7874   // in another scope.
7875   if (isIncompleteDeclExternC(S,ND))
7876     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7877 
7878   // Neither global nor extern "C": nothing to do.
7879   return false;
7880 }
7881 
7882 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7883   // If the decl is already known invalid, don't check it.
7884   if (NewVD->isInvalidDecl())
7885     return;
7886 
7887   QualType T = NewVD->getType();
7888 
7889   // Defer checking an 'auto' type until its initializer is attached.
7890   if (T->isUndeducedType())
7891     return;
7892 
7893   if (NewVD->hasAttrs())
7894     CheckAlignasUnderalignment(NewVD);
7895 
7896   if (T->isObjCObjectType()) {
7897     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7898       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7899     T = Context.getObjCObjectPointerType(T);
7900     NewVD->setType(T);
7901   }
7902 
7903   // Emit an error if an address space was applied to decl with local storage.
7904   // This includes arrays of objects with address space qualifiers, but not
7905   // automatic variables that point to other address spaces.
7906   // ISO/IEC TR 18037 S5.1.2
7907   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7908       T.getAddressSpace() != LangAS::Default) {
7909     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7910     NewVD->setInvalidDecl();
7911     return;
7912   }
7913 
7914   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7915   // scope.
7916   if (getLangOpts().OpenCLVersion == 120 &&
7917       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7918                                             getLangOpts()) &&
7919       NewVD->isStaticLocal()) {
7920     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7921     NewVD->setInvalidDecl();
7922     return;
7923   }
7924 
7925   if (getLangOpts().OpenCL) {
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     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7948     // __constant address space.
7949     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7950     // variables inside a function can also be declared in the global
7951     // address space.
7952     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7953     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7954     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7955         NewVD->hasExternalStorage()) {
7956       if (!T->isSamplerT() &&
7957           !T->isDependentType() &&
7958           !(T.getAddressSpace() == LangAS::opencl_constant ||
7959             (T.getAddressSpace() == LangAS::opencl_global &&
7960              (getLangOpts().OpenCLVersion == 200 ||
7961               getLangOpts().OpenCLCPlusPlus)))) {
7962         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7963         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7964           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7965               << Scope << "global or constant";
7966         else
7967           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7968               << Scope << "constant";
7969         NewVD->setInvalidDecl();
7970         return;
7971       }
7972     } else {
7973       if (T.getAddressSpace() == LangAS::opencl_global) {
7974         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7975             << 1 /*is any function*/ << "global";
7976         NewVD->setInvalidDecl();
7977         return;
7978       }
7979       if (T.getAddressSpace() == LangAS::opencl_constant ||
7980           T.getAddressSpace() == LangAS::opencl_local) {
7981         FunctionDecl *FD = getCurFunctionDecl();
7982         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7983         // in functions.
7984         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7985           if (T.getAddressSpace() == LangAS::opencl_constant)
7986             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7987                 << 0 /*non-kernel only*/ << "constant";
7988           else
7989             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7990                 << 0 /*non-kernel only*/ << "local";
7991           NewVD->setInvalidDecl();
7992           return;
7993         }
7994         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7995         // in the outermost scope of a kernel function.
7996         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7997           if (!getCurScope()->isFunctionScope()) {
7998             if (T.getAddressSpace() == LangAS::opencl_constant)
7999               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8000                   << "constant";
8001             else
8002               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8003                   << "local";
8004             NewVD->setInvalidDecl();
8005             return;
8006           }
8007         }
8008       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8009                  // If we are parsing a template we didn't deduce an addr
8010                  // space yet.
8011                  T.getAddressSpace() != LangAS::Default) {
8012         // Do not allow other address spaces on automatic variable.
8013         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8014         NewVD->setInvalidDecl();
8015         return;
8016       }
8017     }
8018   }
8019 
8020   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8021       && !NewVD->hasAttr<BlocksAttr>()) {
8022     if (getLangOpts().getGC() != LangOptions::NonGC)
8023       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8024     else {
8025       assert(!getLangOpts().ObjCAutoRefCount);
8026       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8027     }
8028   }
8029 
8030   bool isVM = T->isVariablyModifiedType();
8031   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8032       NewVD->hasAttr<BlocksAttr>())
8033     setFunctionHasBranchProtectedScope();
8034 
8035   if ((isVM && NewVD->hasLinkage()) ||
8036       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8037     bool SizeIsNegative;
8038     llvm::APSInt Oversized;
8039     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8040         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8041     QualType FixedT;
8042     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8043       FixedT = FixedTInfo->getType();
8044     else if (FixedTInfo) {
8045       // Type and type-as-written are canonically different. We need to fix up
8046       // both types separately.
8047       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8048                                                    Oversized);
8049     }
8050     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8051       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8052       // FIXME: This won't give the correct result for
8053       // int a[10][n];
8054       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8055 
8056       if (NewVD->isFileVarDecl())
8057         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8058         << SizeRange;
8059       else if (NewVD->isStaticLocal())
8060         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8061         << SizeRange;
8062       else
8063         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8064         << SizeRange;
8065       NewVD->setInvalidDecl();
8066       return;
8067     }
8068 
8069     if (!FixedTInfo) {
8070       if (NewVD->isFileVarDecl())
8071         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8072       else
8073         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8074       NewVD->setInvalidDecl();
8075       return;
8076     }
8077 
8078     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8079     NewVD->setType(FixedT);
8080     NewVD->setTypeSourceInfo(FixedTInfo);
8081   }
8082 
8083   if (T->isVoidType()) {
8084     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8085     //                    of objects and functions.
8086     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8087       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8088         << T;
8089       NewVD->setInvalidDecl();
8090       return;
8091     }
8092   }
8093 
8094   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8095     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8096     NewVD->setInvalidDecl();
8097     return;
8098   }
8099 
8100   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8101     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8102     NewVD->setInvalidDecl();
8103     return;
8104   }
8105 
8106   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8107     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8108     NewVD->setInvalidDecl();
8109     return;
8110   }
8111 
8112   if (NewVD->isConstexpr() && !T->isDependentType() &&
8113       RequireLiteralType(NewVD->getLocation(), T,
8114                          diag::err_constexpr_var_non_literal)) {
8115     NewVD->setInvalidDecl();
8116     return;
8117   }
8118 
8119   // PPC MMA non-pointer types are not allowed as non-local variable types.
8120   if (Context.getTargetInfo().getTriple().isPPC64() &&
8121       !NewVD->isLocalVarDecl() &&
8122       CheckPPCMMAType(T, NewVD->getLocation())) {
8123     NewVD->setInvalidDecl();
8124     return;
8125   }
8126 }
8127 
8128 /// Perform semantic checking on a newly-created variable
8129 /// declaration.
8130 ///
8131 /// This routine performs all of the type-checking required for a
8132 /// variable declaration once it has been built. It is used both to
8133 /// check variables after they have been parsed and their declarators
8134 /// have been translated into a declaration, and to check variables
8135 /// that have been instantiated from a template.
8136 ///
8137 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8138 ///
8139 /// Returns true if the variable declaration is a redeclaration.
8140 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8141   CheckVariableDeclarationType(NewVD);
8142 
8143   // If the decl is already known invalid, don't check it.
8144   if (NewVD->isInvalidDecl())
8145     return false;
8146 
8147   // If we did not find anything by this name, look for a non-visible
8148   // extern "C" declaration with the same name.
8149   if (Previous.empty() &&
8150       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8151     Previous.setShadowed();
8152 
8153   if (!Previous.empty()) {
8154     MergeVarDecl(NewVD, Previous);
8155     return true;
8156   }
8157   return false;
8158 }
8159 
8160 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8161 /// and if so, check that it's a valid override and remember it.
8162 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8163   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8164 
8165   // Look for methods in base classes that this method might override.
8166   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8167                      /*DetectVirtual=*/false);
8168   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8169     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8170     DeclarationName Name = MD->getDeclName();
8171 
8172     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8173       // We really want to find the base class destructor here.
8174       QualType T = Context.getTypeDeclType(BaseRecord);
8175       CanQualType CT = Context.getCanonicalType(T);
8176       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8177     }
8178 
8179     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8180       CXXMethodDecl *BaseMD =
8181           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8182       if (!BaseMD || !BaseMD->isVirtual() ||
8183           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8184                      /*ConsiderCudaAttrs=*/true,
8185                      // C++2a [class.virtual]p2 does not consider requires
8186                      // clauses when overriding.
8187                      /*ConsiderRequiresClauses=*/false))
8188         continue;
8189 
8190       if (Overridden.insert(BaseMD).second) {
8191         MD->addOverriddenMethod(BaseMD);
8192         CheckOverridingFunctionReturnType(MD, BaseMD);
8193         CheckOverridingFunctionAttributes(MD, BaseMD);
8194         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8195         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8196       }
8197 
8198       // A method can only override one function from each base class. We
8199       // don't track indirectly overridden methods from bases of bases.
8200       return true;
8201     }
8202 
8203     return false;
8204   };
8205 
8206   DC->lookupInBases(VisitBase, Paths);
8207   return !Overridden.empty();
8208 }
8209 
8210 namespace {
8211   // Struct for holding all of the extra arguments needed by
8212   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8213   struct ActOnFDArgs {
8214     Scope *S;
8215     Declarator &D;
8216     MultiTemplateParamsArg TemplateParamLists;
8217     bool AddToScope;
8218   };
8219 } // end anonymous namespace
8220 
8221 namespace {
8222 
8223 // Callback to only accept typo corrections that have a non-zero edit distance.
8224 // Also only accept corrections that have the same parent decl.
8225 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8226  public:
8227   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8228                             CXXRecordDecl *Parent)
8229       : Context(Context), OriginalFD(TypoFD),
8230         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8231 
8232   bool ValidateCandidate(const TypoCorrection &candidate) override {
8233     if (candidate.getEditDistance() == 0)
8234       return false;
8235 
8236     SmallVector<unsigned, 1> MismatchedParams;
8237     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8238                                           CDeclEnd = candidate.end();
8239          CDecl != CDeclEnd; ++CDecl) {
8240       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8241 
8242       if (FD && !FD->hasBody() &&
8243           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8244         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8245           CXXRecordDecl *Parent = MD->getParent();
8246           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8247             return true;
8248         } else if (!ExpectedParent) {
8249           return true;
8250         }
8251       }
8252     }
8253 
8254     return false;
8255   }
8256 
8257   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8258     return std::make_unique<DifferentNameValidatorCCC>(*this);
8259   }
8260 
8261  private:
8262   ASTContext &Context;
8263   FunctionDecl *OriginalFD;
8264   CXXRecordDecl *ExpectedParent;
8265 };
8266 
8267 } // end anonymous namespace
8268 
8269 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8270   TypoCorrectedFunctionDefinitions.insert(F);
8271 }
8272 
8273 /// Generate diagnostics for an invalid function redeclaration.
8274 ///
8275 /// This routine handles generating the diagnostic messages for an invalid
8276 /// function redeclaration, including finding possible similar declarations
8277 /// or performing typo correction if there are no previous declarations with
8278 /// the same name.
8279 ///
8280 /// Returns a NamedDecl iff typo correction was performed and substituting in
8281 /// the new declaration name does not cause new errors.
8282 static NamedDecl *DiagnoseInvalidRedeclaration(
8283     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8284     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8285   DeclarationName Name = NewFD->getDeclName();
8286   DeclContext *NewDC = NewFD->getDeclContext();
8287   SmallVector<unsigned, 1> MismatchedParams;
8288   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8289   TypoCorrection Correction;
8290   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8291   unsigned DiagMsg =
8292     IsLocalFriend ? diag::err_no_matching_local_friend :
8293     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8294     diag::err_member_decl_does_not_match;
8295   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8296                     IsLocalFriend ? Sema::LookupLocalFriendName
8297                                   : Sema::LookupOrdinaryName,
8298                     Sema::ForVisibleRedeclaration);
8299 
8300   NewFD->setInvalidDecl();
8301   if (IsLocalFriend)
8302     SemaRef.LookupName(Prev, S);
8303   else
8304     SemaRef.LookupQualifiedName(Prev, NewDC);
8305   assert(!Prev.isAmbiguous() &&
8306          "Cannot have an ambiguity in previous-declaration lookup");
8307   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8308   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8309                                 MD ? MD->getParent() : nullptr);
8310   if (!Prev.empty()) {
8311     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8312          Func != FuncEnd; ++Func) {
8313       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8314       if (FD &&
8315           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8316         // Add 1 to the index so that 0 can mean the mismatch didn't
8317         // involve a parameter
8318         unsigned ParamNum =
8319             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8320         NearMatches.push_back(std::make_pair(FD, ParamNum));
8321       }
8322     }
8323   // If the qualified name lookup yielded nothing, try typo correction
8324   } else if ((Correction = SemaRef.CorrectTypo(
8325                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8326                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8327                   IsLocalFriend ? nullptr : NewDC))) {
8328     // Set up everything for the call to ActOnFunctionDeclarator
8329     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8330                               ExtraArgs.D.getIdentifierLoc());
8331     Previous.clear();
8332     Previous.setLookupName(Correction.getCorrection());
8333     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8334                                     CDeclEnd = Correction.end();
8335          CDecl != CDeclEnd; ++CDecl) {
8336       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8337       if (FD && !FD->hasBody() &&
8338           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8339         Previous.addDecl(FD);
8340       }
8341     }
8342     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8343 
8344     NamedDecl *Result;
8345     // Retry building the function declaration with the new previous
8346     // declarations, and with errors suppressed.
8347     {
8348       // Trap errors.
8349       Sema::SFINAETrap Trap(SemaRef);
8350 
8351       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8352       // pieces need to verify the typo-corrected C++ declaration and hopefully
8353       // eliminate the need for the parameter pack ExtraArgs.
8354       Result = SemaRef.ActOnFunctionDeclarator(
8355           ExtraArgs.S, ExtraArgs.D,
8356           Correction.getCorrectionDecl()->getDeclContext(),
8357           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8358           ExtraArgs.AddToScope);
8359 
8360       if (Trap.hasErrorOccurred())
8361         Result = nullptr;
8362     }
8363 
8364     if (Result) {
8365       // Determine which correction we picked.
8366       Decl *Canonical = Result->getCanonicalDecl();
8367       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8368            I != E; ++I)
8369         if ((*I)->getCanonicalDecl() == Canonical)
8370           Correction.setCorrectionDecl(*I);
8371 
8372       // Let Sema know about the correction.
8373       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8374       SemaRef.diagnoseTypo(
8375           Correction,
8376           SemaRef.PDiag(IsLocalFriend
8377                           ? diag::err_no_matching_local_friend_suggest
8378                           : diag::err_member_decl_does_not_match_suggest)
8379             << Name << NewDC << IsDefinition);
8380       return Result;
8381     }
8382 
8383     // Pretend the typo correction never occurred
8384     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8385                               ExtraArgs.D.getIdentifierLoc());
8386     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8387     Previous.clear();
8388     Previous.setLookupName(Name);
8389   }
8390 
8391   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8392       << Name << NewDC << IsDefinition << NewFD->getLocation();
8393 
8394   bool NewFDisConst = false;
8395   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8396     NewFDisConst = NewMD->isConst();
8397 
8398   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8399        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8400        NearMatch != NearMatchEnd; ++NearMatch) {
8401     FunctionDecl *FD = NearMatch->first;
8402     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8403     bool FDisConst = MD && MD->isConst();
8404     bool IsMember = MD || !IsLocalFriend;
8405 
8406     // FIXME: These notes are poorly worded for the local friend case.
8407     if (unsigned Idx = NearMatch->second) {
8408       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8409       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8410       if (Loc.isInvalid()) Loc = FD->getLocation();
8411       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8412                                  : diag::note_local_decl_close_param_match)
8413         << Idx << FDParam->getType()
8414         << NewFD->getParamDecl(Idx - 1)->getType();
8415     } else if (FDisConst != NewFDisConst) {
8416       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8417           << NewFDisConst << FD->getSourceRange().getEnd();
8418     } else
8419       SemaRef.Diag(FD->getLocation(),
8420                    IsMember ? diag::note_member_def_close_match
8421                             : diag::note_local_decl_close_match);
8422   }
8423   return nullptr;
8424 }
8425 
8426 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8427   switch (D.getDeclSpec().getStorageClassSpec()) {
8428   default: llvm_unreachable("Unknown storage class!");
8429   case DeclSpec::SCS_auto:
8430   case DeclSpec::SCS_register:
8431   case DeclSpec::SCS_mutable:
8432     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8433                  diag::err_typecheck_sclass_func);
8434     D.getMutableDeclSpec().ClearStorageClassSpecs();
8435     D.setInvalidType();
8436     break;
8437   case DeclSpec::SCS_unspecified: break;
8438   case DeclSpec::SCS_extern:
8439     if (D.getDeclSpec().isExternInLinkageSpec())
8440       return SC_None;
8441     return SC_Extern;
8442   case DeclSpec::SCS_static: {
8443     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8444       // C99 6.7.1p5:
8445       //   The declaration of an identifier for a function that has
8446       //   block scope shall have no explicit storage-class specifier
8447       //   other than extern
8448       // See also (C++ [dcl.stc]p4).
8449       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8450                    diag::err_static_block_func);
8451       break;
8452     } else
8453       return SC_Static;
8454   }
8455   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8456   }
8457 
8458   // No explicit storage class has already been returned
8459   return SC_None;
8460 }
8461 
8462 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8463                                            DeclContext *DC, QualType &R,
8464                                            TypeSourceInfo *TInfo,
8465                                            StorageClass SC,
8466                                            bool &IsVirtualOkay) {
8467   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8468   DeclarationName Name = NameInfo.getName();
8469 
8470   FunctionDecl *NewFD = nullptr;
8471   bool isInline = D.getDeclSpec().isInlineSpecified();
8472 
8473   if (!SemaRef.getLangOpts().CPlusPlus) {
8474     // Determine whether the function was written with a
8475     // prototype. This true when:
8476     //   - there is a prototype in the declarator, or
8477     //   - the type R of the function is some kind of typedef or other non-
8478     //     attributed reference to a type name (which eventually refers to a
8479     //     function type).
8480     bool HasPrototype =
8481       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8482       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8483 
8484     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8485                                  R, TInfo, SC, isInline, HasPrototype,
8486                                  ConstexprSpecKind::Unspecified,
8487                                  /*TrailingRequiresClause=*/nullptr);
8488     if (D.isInvalidType())
8489       NewFD->setInvalidDecl();
8490 
8491     return NewFD;
8492   }
8493 
8494   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8495 
8496   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8497   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8498     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8499                  diag::err_constexpr_wrong_decl_kind)
8500         << static_cast<int>(ConstexprKind);
8501     ConstexprKind = ConstexprSpecKind::Unspecified;
8502     D.getMutableDeclSpec().ClearConstexprSpec();
8503   }
8504   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8505 
8506   // Check that the return type is not an abstract class type.
8507   // For record types, this is done by the AbstractClassUsageDiagnoser once
8508   // the class has been completely parsed.
8509   if (!DC->isRecord() &&
8510       SemaRef.RequireNonAbstractType(
8511           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8512           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8513     D.setInvalidType();
8514 
8515   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8516     // This is a C++ constructor declaration.
8517     assert(DC->isRecord() &&
8518            "Constructors can only be declared in a member context");
8519 
8520     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8521     return CXXConstructorDecl::Create(
8522         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8523         TInfo, ExplicitSpecifier, isInline,
8524         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8525         TrailingRequiresClause);
8526 
8527   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8528     // This is a C++ destructor declaration.
8529     if (DC->isRecord()) {
8530       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8531       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8532       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8533           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8534           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8535           TrailingRequiresClause);
8536 
8537       // If the destructor needs an implicit exception specification, set it
8538       // now. FIXME: It'd be nice to be able to create the right type to start
8539       // with, but the type needs to reference the destructor declaration.
8540       if (SemaRef.getLangOpts().CPlusPlus11)
8541         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8542 
8543       IsVirtualOkay = true;
8544       return NewDD;
8545 
8546     } else {
8547       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8548       D.setInvalidType();
8549 
8550       // Create a FunctionDecl to satisfy the function definition parsing
8551       // code path.
8552       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8553                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8554                                   isInline,
8555                                   /*hasPrototype=*/true, ConstexprKind,
8556                                   TrailingRequiresClause);
8557     }
8558 
8559   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8560     if (!DC->isRecord()) {
8561       SemaRef.Diag(D.getIdentifierLoc(),
8562            diag::err_conv_function_not_member);
8563       return nullptr;
8564     }
8565 
8566     SemaRef.CheckConversionDeclarator(D, R, SC);
8567     if (D.isInvalidType())
8568       return nullptr;
8569 
8570     IsVirtualOkay = true;
8571     return CXXConversionDecl::Create(
8572         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8573         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8574         TrailingRequiresClause);
8575 
8576   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8577     if (TrailingRequiresClause)
8578       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8579                    diag::err_trailing_requires_clause_on_deduction_guide)
8580           << TrailingRequiresClause->getSourceRange();
8581     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8582 
8583     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8584                                          ExplicitSpecifier, NameInfo, R, TInfo,
8585                                          D.getEndLoc());
8586   } else if (DC->isRecord()) {
8587     // If the name of the function is the same as the name of the record,
8588     // then this must be an invalid constructor that has a return type.
8589     // (The parser checks for a return type and makes the declarator a
8590     // constructor if it has no return type).
8591     if (Name.getAsIdentifierInfo() &&
8592         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8593       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8594         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8595         << SourceRange(D.getIdentifierLoc());
8596       return nullptr;
8597     }
8598 
8599     // This is a C++ method declaration.
8600     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8601         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8602         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8603         TrailingRequiresClause);
8604     IsVirtualOkay = !Ret->isStatic();
8605     return Ret;
8606   } else {
8607     bool isFriend =
8608         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8609     if (!isFriend && SemaRef.CurContext->isRecord())
8610       return nullptr;
8611 
8612     // Determine whether the function was written with a
8613     // prototype. This true when:
8614     //   - we're in C++ (where every function has a prototype),
8615     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8616                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8617                                 ConstexprKind, TrailingRequiresClause);
8618   }
8619 }
8620 
8621 enum OpenCLParamType {
8622   ValidKernelParam,
8623   PtrPtrKernelParam,
8624   PtrKernelParam,
8625   InvalidAddrSpacePtrKernelParam,
8626   InvalidKernelParam,
8627   RecordKernelParam
8628 };
8629 
8630 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8631   // Size dependent types are just typedefs to normal integer types
8632   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8633   // integers other than by their names.
8634   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8635 
8636   // Remove typedefs one by one until we reach a typedef
8637   // for a size dependent type.
8638   QualType DesugaredTy = Ty;
8639   do {
8640     ArrayRef<StringRef> Names(SizeTypeNames);
8641     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8642     if (Names.end() != Match)
8643       return true;
8644 
8645     Ty = DesugaredTy;
8646     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8647   } while (DesugaredTy != Ty);
8648 
8649   return false;
8650 }
8651 
8652 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8653   if (PT->isPointerType() || PT->isReferenceType()) {
8654     QualType PointeeType = PT->getPointeeType();
8655     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8656         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8657         PointeeType.getAddressSpace() == LangAS::Default)
8658       return InvalidAddrSpacePtrKernelParam;
8659 
8660     if (PointeeType->isPointerType()) {
8661       // This is a pointer to pointer parameter.
8662       // Recursively check inner type.
8663       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8664       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8665           ParamKind == InvalidKernelParam)
8666         return ParamKind;
8667 
8668       return PtrPtrKernelParam;
8669     }
8670 
8671     // C++ for OpenCL v1.0 s2.4:
8672     // Moreover the types used in parameters of the kernel functions must be:
8673     // Standard layout types for pointer parameters. The same applies to
8674     // reference if an implementation supports them in kernel parameters.
8675     if (S.getLangOpts().OpenCLCPlusPlus && !PointeeType->isAtomicType() &&
8676         !PointeeType->isVoidType() && !PointeeType->isStandardLayoutType())
8677       return InvalidKernelParam;
8678 
8679     return PtrKernelParam;
8680   }
8681 
8682   // OpenCL v1.2 s6.9.k:
8683   // Arguments to kernel functions in a program cannot be declared with the
8684   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8685   // uintptr_t or a struct and/or union that contain fields declared to be one
8686   // of these built-in scalar types.
8687   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8688     return InvalidKernelParam;
8689 
8690   if (PT->isImageType())
8691     return PtrKernelParam;
8692 
8693   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8694     return InvalidKernelParam;
8695 
8696   // OpenCL extension spec v1.2 s9.5:
8697   // This extension adds support for half scalar and vector types as built-in
8698   // types that can be used for arithmetic operations, conversions etc.
8699   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8700       PT->isHalfType())
8701     return InvalidKernelParam;
8702 
8703   // Look into an array argument to check if it has a forbidden type.
8704   if (PT->isArrayType()) {
8705     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8706     // Call ourself to check an underlying type of an array. Since the
8707     // getPointeeOrArrayElementType returns an innermost type which is not an
8708     // array, this recursive call only happens once.
8709     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8710   }
8711 
8712   // C++ for OpenCL v1.0 s2.4:
8713   // Moreover the types used in parameters of the kernel functions must be:
8714   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8715   // types) for parameters passed by value;
8716   if (S.getLangOpts().OpenCLCPlusPlus && !PT->isOpenCLSpecificType() &&
8717       !PT.isPODType(S.Context))
8718     return InvalidKernelParam;
8719 
8720   if (PT->isRecordType())
8721     return RecordKernelParam;
8722 
8723   return ValidKernelParam;
8724 }
8725 
8726 static void checkIsValidOpenCLKernelParameter(
8727   Sema &S,
8728   Declarator &D,
8729   ParmVarDecl *Param,
8730   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8731   QualType PT = Param->getType();
8732 
8733   // Cache the valid types we encounter to avoid rechecking structs that are
8734   // used again
8735   if (ValidTypes.count(PT.getTypePtr()))
8736     return;
8737 
8738   switch (getOpenCLKernelParameterType(S, PT)) {
8739   case PtrPtrKernelParam:
8740     // OpenCL v3.0 s6.11.a:
8741     // A kernel function argument cannot be declared as a pointer to a pointer
8742     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8743     if (S.getLangOpts().OpenCLVersion < 120 &&
8744         !S.getLangOpts().OpenCLCPlusPlus) {
8745       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8746       D.setInvalidType();
8747       return;
8748     }
8749 
8750     ValidTypes.insert(PT.getTypePtr());
8751     return;
8752 
8753   case InvalidAddrSpacePtrKernelParam:
8754     // OpenCL v1.0 s6.5:
8755     // __kernel function arguments declared to be a pointer of a type can point
8756     // to one of the following address spaces only : __global, __local or
8757     // __constant.
8758     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8759     D.setInvalidType();
8760     return;
8761 
8762     // OpenCL v1.2 s6.9.k:
8763     // Arguments to kernel functions in a program cannot be declared with the
8764     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8765     // uintptr_t or a struct and/or union that contain fields declared to be
8766     // one of these built-in scalar types.
8767 
8768   case InvalidKernelParam:
8769     // OpenCL v1.2 s6.8 n:
8770     // A kernel function argument cannot be declared
8771     // of event_t type.
8772     // Do not diagnose half type since it is diagnosed as invalid argument
8773     // type for any function elsewhere.
8774     if (!PT->isHalfType()) {
8775       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8776 
8777       // Explain what typedefs are involved.
8778       const TypedefType *Typedef = nullptr;
8779       while ((Typedef = PT->getAs<TypedefType>())) {
8780         SourceLocation Loc = Typedef->getDecl()->getLocation();
8781         // SourceLocation may be invalid for a built-in type.
8782         if (Loc.isValid())
8783           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8784         PT = Typedef->desugar();
8785       }
8786     }
8787 
8788     D.setInvalidType();
8789     return;
8790 
8791   case PtrKernelParam:
8792   case ValidKernelParam:
8793     ValidTypes.insert(PT.getTypePtr());
8794     return;
8795 
8796   case RecordKernelParam:
8797     break;
8798   }
8799 
8800   // Track nested structs we will inspect
8801   SmallVector<const Decl *, 4> VisitStack;
8802 
8803   // Track where we are in the nested structs. Items will migrate from
8804   // VisitStack to HistoryStack as we do the DFS for bad field.
8805   SmallVector<const FieldDecl *, 4> HistoryStack;
8806   HistoryStack.push_back(nullptr);
8807 
8808   // At this point we already handled everything except of a RecordType or
8809   // an ArrayType of a RecordType.
8810   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8811   const RecordType *RecTy =
8812       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8813   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8814 
8815   VisitStack.push_back(RecTy->getDecl());
8816   assert(VisitStack.back() && "First decl null?");
8817 
8818   do {
8819     const Decl *Next = VisitStack.pop_back_val();
8820     if (!Next) {
8821       assert(!HistoryStack.empty());
8822       // Found a marker, we have gone up a level
8823       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8824         ValidTypes.insert(Hist->getType().getTypePtr());
8825 
8826       continue;
8827     }
8828 
8829     // Adds everything except the original parameter declaration (which is not a
8830     // field itself) to the history stack.
8831     const RecordDecl *RD;
8832     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8833       HistoryStack.push_back(Field);
8834 
8835       QualType FieldTy = Field->getType();
8836       // Other field types (known to be valid or invalid) are handled while we
8837       // walk around RecordDecl::fields().
8838       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8839              "Unexpected type.");
8840       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8841 
8842       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8843     } else {
8844       RD = cast<RecordDecl>(Next);
8845     }
8846 
8847     // Add a null marker so we know when we've gone back up a level
8848     VisitStack.push_back(nullptr);
8849 
8850     for (const auto *FD : RD->fields()) {
8851       QualType QT = FD->getType();
8852 
8853       if (ValidTypes.count(QT.getTypePtr()))
8854         continue;
8855 
8856       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8857       if (ParamType == ValidKernelParam)
8858         continue;
8859 
8860       if (ParamType == RecordKernelParam) {
8861         VisitStack.push_back(FD);
8862         continue;
8863       }
8864 
8865       // OpenCL v1.2 s6.9.p:
8866       // Arguments to kernel functions that are declared to be a struct or union
8867       // do not allow OpenCL objects to be passed as elements of the struct or
8868       // union.
8869       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8870           ParamType == InvalidAddrSpacePtrKernelParam) {
8871         S.Diag(Param->getLocation(),
8872                diag::err_record_with_pointers_kernel_param)
8873           << PT->isUnionType()
8874           << PT;
8875       } else {
8876         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8877       }
8878 
8879       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8880           << OrigRecDecl->getDeclName();
8881 
8882       // We have an error, now let's go back up through history and show where
8883       // the offending field came from
8884       for (ArrayRef<const FieldDecl *>::const_iterator
8885                I = HistoryStack.begin() + 1,
8886                E = HistoryStack.end();
8887            I != E; ++I) {
8888         const FieldDecl *OuterField = *I;
8889         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8890           << OuterField->getType();
8891       }
8892 
8893       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8894         << QT->isPointerType()
8895         << QT;
8896       D.setInvalidType();
8897       return;
8898     }
8899   } while (!VisitStack.empty());
8900 }
8901 
8902 /// Find the DeclContext in which a tag is implicitly declared if we see an
8903 /// elaborated type specifier in the specified context, and lookup finds
8904 /// nothing.
8905 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8906   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8907     DC = DC->getParent();
8908   return DC;
8909 }
8910 
8911 /// Find the Scope in which a tag is implicitly declared if we see an
8912 /// elaborated type specifier in the specified context, and lookup finds
8913 /// nothing.
8914 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8915   while (S->isClassScope() ||
8916          (LangOpts.CPlusPlus &&
8917           S->isFunctionPrototypeScope()) ||
8918          ((S->getFlags() & Scope::DeclScope) == 0) ||
8919          (S->getEntity() && S->getEntity()->isTransparentContext()))
8920     S = S->getParent();
8921   return S;
8922 }
8923 
8924 NamedDecl*
8925 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8926                               TypeSourceInfo *TInfo, LookupResult &Previous,
8927                               MultiTemplateParamsArg TemplateParamListsRef,
8928                               bool &AddToScope) {
8929   QualType R = TInfo->getType();
8930 
8931   assert(R->isFunctionType());
8932   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8933     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8934 
8935   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8936   for (TemplateParameterList *TPL : TemplateParamListsRef)
8937     TemplateParamLists.push_back(TPL);
8938   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8939     if (!TemplateParamLists.empty() &&
8940         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8941       TemplateParamLists.back() = Invented;
8942     else
8943       TemplateParamLists.push_back(Invented);
8944   }
8945 
8946   // TODO: consider using NameInfo for diagnostic.
8947   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8948   DeclarationName Name = NameInfo.getName();
8949   StorageClass SC = getFunctionStorageClass(*this, D);
8950 
8951   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8952     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8953          diag::err_invalid_thread)
8954       << DeclSpec::getSpecifierName(TSCS);
8955 
8956   if (D.isFirstDeclarationOfMember())
8957     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8958                            D.getIdentifierLoc());
8959 
8960   bool isFriend = false;
8961   FunctionTemplateDecl *FunctionTemplate = nullptr;
8962   bool isMemberSpecialization = false;
8963   bool isFunctionTemplateSpecialization = false;
8964 
8965   bool isDependentClassScopeExplicitSpecialization = false;
8966   bool HasExplicitTemplateArgs = false;
8967   TemplateArgumentListInfo TemplateArgs;
8968 
8969   bool isVirtualOkay = false;
8970 
8971   DeclContext *OriginalDC = DC;
8972   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8973 
8974   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8975                                               isVirtualOkay);
8976   if (!NewFD) return nullptr;
8977 
8978   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8979     NewFD->setTopLevelDeclInObjCContainer();
8980 
8981   // Set the lexical context. If this is a function-scope declaration, or has a
8982   // C++ scope specifier, or is the object of a friend declaration, the lexical
8983   // context will be different from the semantic context.
8984   NewFD->setLexicalDeclContext(CurContext);
8985 
8986   if (IsLocalExternDecl)
8987     NewFD->setLocalExternDecl();
8988 
8989   if (getLangOpts().CPlusPlus) {
8990     bool isInline = D.getDeclSpec().isInlineSpecified();
8991     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8992     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8993     isFriend = D.getDeclSpec().isFriendSpecified();
8994     if (isFriend && !isInline && D.isFunctionDefinition()) {
8995       // C++ [class.friend]p5
8996       //   A function can be defined in a friend declaration of a
8997       //   class . . . . Such a function is implicitly inline.
8998       NewFD->setImplicitlyInline();
8999     }
9000 
9001     // If this is a method defined in an __interface, and is not a constructor
9002     // or an overloaded operator, then set the pure flag (isVirtual will already
9003     // return true).
9004     if (const CXXRecordDecl *Parent =
9005           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9006       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9007         NewFD->setPure(true);
9008 
9009       // C++ [class.union]p2
9010       //   A union can have member functions, but not virtual functions.
9011       if (isVirtual && Parent->isUnion())
9012         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9013     }
9014 
9015     SetNestedNameSpecifier(*this, NewFD, D);
9016     isMemberSpecialization = false;
9017     isFunctionTemplateSpecialization = false;
9018     if (D.isInvalidType())
9019       NewFD->setInvalidDecl();
9020 
9021     // Match up the template parameter lists with the scope specifier, then
9022     // determine whether we have a template or a template specialization.
9023     bool Invalid = false;
9024     TemplateParameterList *TemplateParams =
9025         MatchTemplateParametersToScopeSpecifier(
9026             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9027             D.getCXXScopeSpec(),
9028             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9029                 ? D.getName().TemplateId
9030                 : nullptr,
9031             TemplateParamLists, isFriend, isMemberSpecialization,
9032             Invalid);
9033     if (TemplateParams) {
9034       // Check that we can declare a template here.
9035       if (CheckTemplateDeclScope(S, TemplateParams))
9036         NewFD->setInvalidDecl();
9037 
9038       if (TemplateParams->size() > 0) {
9039         // This is a function template
9040 
9041         // A destructor cannot be a template.
9042         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9043           Diag(NewFD->getLocation(), diag::err_destructor_template);
9044           NewFD->setInvalidDecl();
9045         }
9046 
9047         // If we're adding a template to a dependent context, we may need to
9048         // rebuilding some of the types used within the template parameter list,
9049         // now that we know what the current instantiation is.
9050         if (DC->isDependentContext()) {
9051           ContextRAII SavedContext(*this, DC);
9052           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9053             Invalid = true;
9054         }
9055 
9056         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9057                                                         NewFD->getLocation(),
9058                                                         Name, TemplateParams,
9059                                                         NewFD);
9060         FunctionTemplate->setLexicalDeclContext(CurContext);
9061         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9062 
9063         // For source fidelity, store the other template param lists.
9064         if (TemplateParamLists.size() > 1) {
9065           NewFD->setTemplateParameterListsInfo(Context,
9066               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9067                   .drop_back(1));
9068         }
9069       } else {
9070         // This is a function template specialization.
9071         isFunctionTemplateSpecialization = true;
9072         // For source fidelity, store all the template param lists.
9073         if (TemplateParamLists.size() > 0)
9074           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9075 
9076         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9077         if (isFriend) {
9078           // We want to remove the "template<>", found here.
9079           SourceRange RemoveRange = TemplateParams->getSourceRange();
9080 
9081           // If we remove the template<> and the name is not a
9082           // template-id, we're actually silently creating a problem:
9083           // the friend declaration will refer to an untemplated decl,
9084           // and clearly the user wants a template specialization.  So
9085           // we need to insert '<>' after the name.
9086           SourceLocation InsertLoc;
9087           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9088             InsertLoc = D.getName().getSourceRange().getEnd();
9089             InsertLoc = getLocForEndOfToken(InsertLoc);
9090           }
9091 
9092           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9093             << Name << RemoveRange
9094             << FixItHint::CreateRemoval(RemoveRange)
9095             << FixItHint::CreateInsertion(InsertLoc, "<>");
9096         }
9097       }
9098     } else {
9099       // Check that we can declare a template here.
9100       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9101           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9102         NewFD->setInvalidDecl();
9103 
9104       // All template param lists were matched against the scope specifier:
9105       // this is NOT (an explicit specialization of) a template.
9106       if (TemplateParamLists.size() > 0)
9107         // For source fidelity, store all the template param lists.
9108         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9109     }
9110 
9111     if (Invalid) {
9112       NewFD->setInvalidDecl();
9113       if (FunctionTemplate)
9114         FunctionTemplate->setInvalidDecl();
9115     }
9116 
9117     // C++ [dcl.fct.spec]p5:
9118     //   The virtual specifier shall only be used in declarations of
9119     //   nonstatic class member functions that appear within a
9120     //   member-specification of a class declaration; see 10.3.
9121     //
9122     if (isVirtual && !NewFD->isInvalidDecl()) {
9123       if (!isVirtualOkay) {
9124         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9125              diag::err_virtual_non_function);
9126       } else if (!CurContext->isRecord()) {
9127         // 'virtual' was specified outside of the class.
9128         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9129              diag::err_virtual_out_of_class)
9130           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9131       } else if (NewFD->getDescribedFunctionTemplate()) {
9132         // C++ [temp.mem]p3:
9133         //  A member function template shall not be virtual.
9134         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9135              diag::err_virtual_member_function_template)
9136           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9137       } else {
9138         // Okay: Add virtual to the method.
9139         NewFD->setVirtualAsWritten(true);
9140       }
9141 
9142       if (getLangOpts().CPlusPlus14 &&
9143           NewFD->getReturnType()->isUndeducedType())
9144         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9145     }
9146 
9147     if (getLangOpts().CPlusPlus14 &&
9148         (NewFD->isDependentContext() ||
9149          (isFriend && CurContext->isDependentContext())) &&
9150         NewFD->getReturnType()->isUndeducedType()) {
9151       // If the function template is referenced directly (for instance, as a
9152       // member of the current instantiation), pretend it has a dependent type.
9153       // This is not really justified by the standard, but is the only sane
9154       // thing to do.
9155       // FIXME: For a friend function, we have not marked the function as being
9156       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9157       const FunctionProtoType *FPT =
9158           NewFD->getType()->castAs<FunctionProtoType>();
9159       QualType Result =
9160           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9161       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9162                                              FPT->getExtProtoInfo()));
9163     }
9164 
9165     // C++ [dcl.fct.spec]p3:
9166     //  The inline specifier shall not appear on a block scope function
9167     //  declaration.
9168     if (isInline && !NewFD->isInvalidDecl()) {
9169       if (CurContext->isFunctionOrMethod()) {
9170         // 'inline' is not allowed on block scope function declaration.
9171         Diag(D.getDeclSpec().getInlineSpecLoc(),
9172              diag::err_inline_declaration_block_scope) << Name
9173           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9174       }
9175     }
9176 
9177     // C++ [dcl.fct.spec]p6:
9178     //  The explicit specifier shall be used only in the declaration of a
9179     //  constructor or conversion function within its class definition;
9180     //  see 12.3.1 and 12.3.2.
9181     if (hasExplicit && !NewFD->isInvalidDecl() &&
9182         !isa<CXXDeductionGuideDecl>(NewFD)) {
9183       if (!CurContext->isRecord()) {
9184         // 'explicit' was specified outside of the class.
9185         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9186              diag::err_explicit_out_of_class)
9187             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9188       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9189                  !isa<CXXConversionDecl>(NewFD)) {
9190         // 'explicit' was specified on a function that wasn't a constructor
9191         // or conversion function.
9192         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9193              diag::err_explicit_non_ctor_or_conv_function)
9194             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9195       }
9196     }
9197 
9198     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9199     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9200       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9201       // are implicitly inline.
9202       NewFD->setImplicitlyInline();
9203 
9204       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9205       // be either constructors or to return a literal type. Therefore,
9206       // destructors cannot be declared constexpr.
9207       if (isa<CXXDestructorDecl>(NewFD) &&
9208           (!getLangOpts().CPlusPlus20 ||
9209            ConstexprKind == ConstexprSpecKind::Consteval)) {
9210         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9211             << static_cast<int>(ConstexprKind);
9212         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9213                                     ? ConstexprSpecKind::Unspecified
9214                                     : ConstexprSpecKind::Constexpr);
9215       }
9216       // C++20 [dcl.constexpr]p2: An allocation function, or a
9217       // deallocation function shall not be declared with the consteval
9218       // specifier.
9219       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9220           (NewFD->getOverloadedOperator() == OO_New ||
9221            NewFD->getOverloadedOperator() == OO_Array_New ||
9222            NewFD->getOverloadedOperator() == OO_Delete ||
9223            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9224         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9225              diag::err_invalid_consteval_decl_kind)
9226             << NewFD;
9227         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9228       }
9229     }
9230 
9231     // If __module_private__ was specified, mark the function accordingly.
9232     if (D.getDeclSpec().isModulePrivateSpecified()) {
9233       if (isFunctionTemplateSpecialization) {
9234         SourceLocation ModulePrivateLoc
9235           = D.getDeclSpec().getModulePrivateSpecLoc();
9236         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9237           << 0
9238           << FixItHint::CreateRemoval(ModulePrivateLoc);
9239       } else {
9240         NewFD->setModulePrivate();
9241         if (FunctionTemplate)
9242           FunctionTemplate->setModulePrivate();
9243       }
9244     }
9245 
9246     if (isFriend) {
9247       if (FunctionTemplate) {
9248         FunctionTemplate->setObjectOfFriendDecl();
9249         FunctionTemplate->setAccess(AS_public);
9250       }
9251       NewFD->setObjectOfFriendDecl();
9252       NewFD->setAccess(AS_public);
9253     }
9254 
9255     // If a function is defined as defaulted or deleted, mark it as such now.
9256     // We'll do the relevant checks on defaulted / deleted functions later.
9257     switch (D.getFunctionDefinitionKind()) {
9258     case FunctionDefinitionKind::Declaration:
9259     case FunctionDefinitionKind::Definition:
9260       break;
9261 
9262     case FunctionDefinitionKind::Defaulted:
9263       NewFD->setDefaulted();
9264       break;
9265 
9266     case FunctionDefinitionKind::Deleted:
9267       NewFD->setDeletedAsWritten();
9268       break;
9269     }
9270 
9271     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9272         D.isFunctionDefinition()) {
9273       // C++ [class.mfct]p2:
9274       //   A member function may be defined (8.4) in its class definition, in
9275       //   which case it is an inline member function (7.1.2)
9276       NewFD->setImplicitlyInline();
9277     }
9278 
9279     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9280         !CurContext->isRecord()) {
9281       // C++ [class.static]p1:
9282       //   A data or function member of a class may be declared static
9283       //   in a class definition, in which case it is a static member of
9284       //   the class.
9285 
9286       // Complain about the 'static' specifier if it's on an out-of-line
9287       // member function definition.
9288 
9289       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9290       // member function template declaration and class member template
9291       // declaration (MSVC versions before 2015), warn about this.
9292       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9293            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9294              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9295            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9296            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9297         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9298     }
9299 
9300     // C++11 [except.spec]p15:
9301     //   A deallocation function with no exception-specification is treated
9302     //   as if it were specified with noexcept(true).
9303     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9304     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9305          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9306         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9307       NewFD->setType(Context.getFunctionType(
9308           FPT->getReturnType(), FPT->getParamTypes(),
9309           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9310   }
9311 
9312   // Filter out previous declarations that don't match the scope.
9313   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9314                        D.getCXXScopeSpec().isNotEmpty() ||
9315                        isMemberSpecialization ||
9316                        isFunctionTemplateSpecialization);
9317 
9318   // Handle GNU asm-label extension (encoded as an attribute).
9319   if (Expr *E = (Expr*) D.getAsmLabel()) {
9320     // The parser guarantees this is a string.
9321     StringLiteral *SE = cast<StringLiteral>(E);
9322     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9323                                         /*IsLiteralLabel=*/true,
9324                                         SE->getStrTokenLoc(0)));
9325   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9326     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9327       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9328     if (I != ExtnameUndeclaredIdentifiers.end()) {
9329       if (isDeclExternC(NewFD)) {
9330         NewFD->addAttr(I->second);
9331         ExtnameUndeclaredIdentifiers.erase(I);
9332       } else
9333         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9334             << /*Variable*/0 << NewFD;
9335     }
9336   }
9337 
9338   // Copy the parameter declarations from the declarator D to the function
9339   // declaration NewFD, if they are available.  First scavenge them into Params.
9340   SmallVector<ParmVarDecl*, 16> Params;
9341   unsigned FTIIdx;
9342   if (D.isFunctionDeclarator(FTIIdx)) {
9343     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9344 
9345     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9346     // function that takes no arguments, not a function that takes a
9347     // single void argument.
9348     // We let through "const void" here because Sema::GetTypeForDeclarator
9349     // already checks for that case.
9350     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9351       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9352         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9353         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9354         Param->setDeclContext(NewFD);
9355         Params.push_back(Param);
9356 
9357         if (Param->isInvalidDecl())
9358           NewFD->setInvalidDecl();
9359       }
9360     }
9361 
9362     if (!getLangOpts().CPlusPlus) {
9363       // In C, find all the tag declarations from the prototype and move them
9364       // into the function DeclContext. Remove them from the surrounding tag
9365       // injection context of the function, which is typically but not always
9366       // the TU.
9367       DeclContext *PrototypeTagContext =
9368           getTagInjectionContext(NewFD->getLexicalDeclContext());
9369       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9370         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9371 
9372         // We don't want to reparent enumerators. Look at their parent enum
9373         // instead.
9374         if (!TD) {
9375           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9376             TD = cast<EnumDecl>(ECD->getDeclContext());
9377         }
9378         if (!TD)
9379           continue;
9380         DeclContext *TagDC = TD->getLexicalDeclContext();
9381         if (!TagDC->containsDecl(TD))
9382           continue;
9383         TagDC->removeDecl(TD);
9384         TD->setDeclContext(NewFD);
9385         NewFD->addDecl(TD);
9386 
9387         // Preserve the lexical DeclContext if it is not the surrounding tag
9388         // injection context of the FD. In this example, the semantic context of
9389         // E will be f and the lexical context will be S, while both the
9390         // semantic and lexical contexts of S will be f:
9391         //   void f(struct S { enum E { a } f; } s);
9392         if (TagDC != PrototypeTagContext)
9393           TD->setLexicalDeclContext(TagDC);
9394       }
9395     }
9396   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9397     // When we're declaring a function with a typedef, typeof, etc as in the
9398     // following example, we'll need to synthesize (unnamed)
9399     // parameters for use in the declaration.
9400     //
9401     // @code
9402     // typedef void fn(int);
9403     // fn f;
9404     // @endcode
9405 
9406     // Synthesize a parameter for each argument type.
9407     for (const auto &AI : FT->param_types()) {
9408       ParmVarDecl *Param =
9409           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9410       Param->setScopeInfo(0, Params.size());
9411       Params.push_back(Param);
9412     }
9413   } else {
9414     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9415            "Should not need args for typedef of non-prototype fn");
9416   }
9417 
9418   // Finally, we know we have the right number of parameters, install them.
9419   NewFD->setParams(Params);
9420 
9421   if (D.getDeclSpec().isNoreturnSpecified())
9422     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9423                                            D.getDeclSpec().getNoreturnSpecLoc(),
9424                                            AttributeCommonInfo::AS_Keyword));
9425 
9426   // Functions returning a variably modified type violate C99 6.7.5.2p2
9427   // because all functions have linkage.
9428   if (!NewFD->isInvalidDecl() &&
9429       NewFD->getReturnType()->isVariablyModifiedType()) {
9430     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9431     NewFD->setInvalidDecl();
9432   }
9433 
9434   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9435   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9436       !NewFD->hasAttr<SectionAttr>())
9437     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9438         Context, PragmaClangTextSection.SectionName,
9439         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9440 
9441   // Apply an implicit SectionAttr if #pragma code_seg is active.
9442   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9443       !NewFD->hasAttr<SectionAttr>()) {
9444     NewFD->addAttr(SectionAttr::CreateImplicit(
9445         Context, CodeSegStack.CurrentValue->getString(),
9446         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9447         SectionAttr::Declspec_allocate));
9448     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9449                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9450                          ASTContext::PSF_Read,
9451                      NewFD))
9452       NewFD->dropAttr<SectionAttr>();
9453   }
9454 
9455   // Apply an implicit CodeSegAttr from class declspec or
9456   // apply an implicit SectionAttr from #pragma code_seg if active.
9457   if (!NewFD->hasAttr<CodeSegAttr>()) {
9458     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9459                                                                  D.isFunctionDefinition())) {
9460       NewFD->addAttr(SAttr);
9461     }
9462   }
9463 
9464   // Handle attributes.
9465   ProcessDeclAttributes(S, NewFD, D);
9466 
9467   if (getLangOpts().OpenCL) {
9468     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9469     // type declaration will generate a compilation error.
9470     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9471     if (AddressSpace != LangAS::Default) {
9472       Diag(NewFD->getLocation(),
9473            diag::err_opencl_return_value_with_address_space);
9474       NewFD->setInvalidDecl();
9475     }
9476   }
9477 
9478   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9479     checkDeviceDecl(NewFD, D.getBeginLoc());
9480 
9481   if (!getLangOpts().CPlusPlus) {
9482     // Perform semantic checking on the function declaration.
9483     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9484       CheckMain(NewFD, D.getDeclSpec());
9485 
9486     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9487       CheckMSVCRTEntryPoint(NewFD);
9488 
9489     if (!NewFD->isInvalidDecl())
9490       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9491                                                   isMemberSpecialization));
9492     else if (!Previous.empty())
9493       // Recover gracefully from an invalid redeclaration.
9494       D.setRedeclaration(true);
9495     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9496             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9497            "previous declaration set still overloaded");
9498 
9499     // Diagnose no-prototype function declarations with calling conventions that
9500     // don't support variadic calls. Only do this in C and do it after merging
9501     // possibly prototyped redeclarations.
9502     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9503     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9504       CallingConv CC = FT->getExtInfo().getCC();
9505       if (!supportsVariadicCall(CC)) {
9506         // Windows system headers sometimes accidentally use stdcall without
9507         // (void) parameters, so we relax this to a warning.
9508         int DiagID =
9509             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9510         Diag(NewFD->getLocation(), DiagID)
9511             << FunctionType::getNameForCallConv(CC);
9512       }
9513     }
9514 
9515    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9516        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9517      checkNonTrivialCUnion(NewFD->getReturnType(),
9518                            NewFD->getReturnTypeSourceRange().getBegin(),
9519                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9520   } else {
9521     // C++11 [replacement.functions]p3:
9522     //  The program's definitions shall not be specified as inline.
9523     //
9524     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9525     //
9526     // Suppress the diagnostic if the function is __attribute__((used)), since
9527     // that forces an external definition to be emitted.
9528     if (D.getDeclSpec().isInlineSpecified() &&
9529         NewFD->isReplaceableGlobalAllocationFunction() &&
9530         !NewFD->hasAttr<UsedAttr>())
9531       Diag(D.getDeclSpec().getInlineSpecLoc(),
9532            diag::ext_operator_new_delete_declared_inline)
9533         << NewFD->getDeclName();
9534 
9535     // If the declarator is a template-id, translate the parser's template
9536     // argument list into our AST format.
9537     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9538       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9539       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9540       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9541       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9542                                          TemplateId->NumArgs);
9543       translateTemplateArguments(TemplateArgsPtr,
9544                                  TemplateArgs);
9545 
9546       HasExplicitTemplateArgs = true;
9547 
9548       if (NewFD->isInvalidDecl()) {
9549         HasExplicitTemplateArgs = false;
9550       } else if (FunctionTemplate) {
9551         // Function template with explicit template arguments.
9552         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9553           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9554 
9555         HasExplicitTemplateArgs = false;
9556       } else {
9557         assert((isFunctionTemplateSpecialization ||
9558                 D.getDeclSpec().isFriendSpecified()) &&
9559                "should have a 'template<>' for this decl");
9560         // "friend void foo<>(int);" is an implicit specialization decl.
9561         isFunctionTemplateSpecialization = true;
9562       }
9563     } else if (isFriend && isFunctionTemplateSpecialization) {
9564       // This combination is only possible in a recovery case;  the user
9565       // wrote something like:
9566       //   template <> friend void foo(int);
9567       // which we're recovering from as if the user had written:
9568       //   friend void foo<>(int);
9569       // Go ahead and fake up a template id.
9570       HasExplicitTemplateArgs = true;
9571       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9572       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9573     }
9574 
9575     // We do not add HD attributes to specializations here because
9576     // they may have different constexpr-ness compared to their
9577     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9578     // may end up with different effective targets. Instead, a
9579     // specialization inherits its target attributes from its template
9580     // in the CheckFunctionTemplateSpecialization() call below.
9581     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9582       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9583 
9584     // If it's a friend (and only if it's a friend), it's possible
9585     // that either the specialized function type or the specialized
9586     // template is dependent, and therefore matching will fail.  In
9587     // this case, don't check the specialization yet.
9588     if (isFunctionTemplateSpecialization && isFriend &&
9589         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9590          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9591              TemplateArgs.arguments()))) {
9592       assert(HasExplicitTemplateArgs &&
9593              "friend function specialization without template args");
9594       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9595                                                        Previous))
9596         NewFD->setInvalidDecl();
9597     } else if (isFunctionTemplateSpecialization) {
9598       if (CurContext->isDependentContext() && CurContext->isRecord()
9599           && !isFriend) {
9600         isDependentClassScopeExplicitSpecialization = true;
9601       } else if (!NewFD->isInvalidDecl() &&
9602                  CheckFunctionTemplateSpecialization(
9603                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9604                      Previous))
9605         NewFD->setInvalidDecl();
9606 
9607       // C++ [dcl.stc]p1:
9608       //   A storage-class-specifier shall not be specified in an explicit
9609       //   specialization (14.7.3)
9610       FunctionTemplateSpecializationInfo *Info =
9611           NewFD->getTemplateSpecializationInfo();
9612       if (Info && SC != SC_None) {
9613         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9614           Diag(NewFD->getLocation(),
9615                diag::err_explicit_specialization_inconsistent_storage_class)
9616             << SC
9617             << FixItHint::CreateRemoval(
9618                                       D.getDeclSpec().getStorageClassSpecLoc());
9619 
9620         else
9621           Diag(NewFD->getLocation(),
9622                diag::ext_explicit_specialization_storage_class)
9623             << FixItHint::CreateRemoval(
9624                                       D.getDeclSpec().getStorageClassSpecLoc());
9625       }
9626     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9627       if (CheckMemberSpecialization(NewFD, Previous))
9628           NewFD->setInvalidDecl();
9629     }
9630 
9631     // Perform semantic checking on the function declaration.
9632     if (!isDependentClassScopeExplicitSpecialization) {
9633       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9634         CheckMain(NewFD, D.getDeclSpec());
9635 
9636       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9637         CheckMSVCRTEntryPoint(NewFD);
9638 
9639       if (!NewFD->isInvalidDecl())
9640         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9641                                                     isMemberSpecialization));
9642       else if (!Previous.empty())
9643         // Recover gracefully from an invalid redeclaration.
9644         D.setRedeclaration(true);
9645     }
9646 
9647     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9648             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9649            "previous declaration set still overloaded");
9650 
9651     NamedDecl *PrincipalDecl = (FunctionTemplate
9652                                 ? cast<NamedDecl>(FunctionTemplate)
9653                                 : NewFD);
9654 
9655     if (isFriend && NewFD->getPreviousDecl()) {
9656       AccessSpecifier Access = AS_public;
9657       if (!NewFD->isInvalidDecl())
9658         Access = NewFD->getPreviousDecl()->getAccess();
9659 
9660       NewFD->setAccess(Access);
9661       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9662     }
9663 
9664     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9665         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9666       PrincipalDecl->setNonMemberOperator();
9667 
9668     // If we have a function template, check the template parameter
9669     // list. This will check and merge default template arguments.
9670     if (FunctionTemplate) {
9671       FunctionTemplateDecl *PrevTemplate =
9672                                      FunctionTemplate->getPreviousDecl();
9673       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9674                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9675                                     : nullptr,
9676                             D.getDeclSpec().isFriendSpecified()
9677                               ? (D.isFunctionDefinition()
9678                                    ? TPC_FriendFunctionTemplateDefinition
9679                                    : TPC_FriendFunctionTemplate)
9680                               : (D.getCXXScopeSpec().isSet() &&
9681                                  DC && DC->isRecord() &&
9682                                  DC->isDependentContext())
9683                                   ? TPC_ClassTemplateMember
9684                                   : TPC_FunctionTemplate);
9685     }
9686 
9687     if (NewFD->isInvalidDecl()) {
9688       // Ignore all the rest of this.
9689     } else if (!D.isRedeclaration()) {
9690       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9691                                        AddToScope };
9692       // Fake up an access specifier if it's supposed to be a class member.
9693       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9694         NewFD->setAccess(AS_public);
9695 
9696       // Qualified decls generally require a previous declaration.
9697       if (D.getCXXScopeSpec().isSet()) {
9698         // ...with the major exception of templated-scope or
9699         // dependent-scope friend declarations.
9700 
9701         // TODO: we currently also suppress this check in dependent
9702         // contexts because (1) the parameter depth will be off when
9703         // matching friend templates and (2) we might actually be
9704         // selecting a friend based on a dependent factor.  But there
9705         // are situations where these conditions don't apply and we
9706         // can actually do this check immediately.
9707         //
9708         // Unless the scope is dependent, it's always an error if qualified
9709         // redeclaration lookup found nothing at all. Diagnose that now;
9710         // nothing will diagnose that error later.
9711         if (isFriend &&
9712             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9713              (!Previous.empty() && CurContext->isDependentContext()))) {
9714           // ignore these
9715         } else if (NewFD->isCPUDispatchMultiVersion() ||
9716                    NewFD->isCPUSpecificMultiVersion()) {
9717           // ignore this, we allow the redeclaration behavior here to create new
9718           // versions of the function.
9719         } else {
9720           // The user tried to provide an out-of-line definition for a
9721           // function that is a member of a class or namespace, but there
9722           // was no such member function declared (C++ [class.mfct]p2,
9723           // C++ [namespace.memdef]p2). For example:
9724           //
9725           // class X {
9726           //   void f() const;
9727           // };
9728           //
9729           // void X::f() { } // ill-formed
9730           //
9731           // Complain about this problem, and attempt to suggest close
9732           // matches (e.g., those that differ only in cv-qualifiers and
9733           // whether the parameter types are references).
9734 
9735           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9736                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9737             AddToScope = ExtraArgs.AddToScope;
9738             return Result;
9739           }
9740         }
9741 
9742         // Unqualified local friend declarations are required to resolve
9743         // to something.
9744       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9745         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9746                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9747           AddToScope = ExtraArgs.AddToScope;
9748           return Result;
9749         }
9750       }
9751     } else if (!D.isFunctionDefinition() &&
9752                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9753                !isFriend && !isFunctionTemplateSpecialization &&
9754                !isMemberSpecialization) {
9755       // An out-of-line member function declaration must also be a
9756       // definition (C++ [class.mfct]p2).
9757       // Note that this is not the case for explicit specializations of
9758       // function templates or member functions of class templates, per
9759       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9760       // extension for compatibility with old SWIG code which likes to
9761       // generate them.
9762       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9763         << D.getCXXScopeSpec().getRange();
9764     }
9765   }
9766 
9767   // If this is the first declaration of a library builtin function, add
9768   // attributes as appropriate.
9769   if (!D.isRedeclaration() &&
9770       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9771     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9772       if (unsigned BuiltinID = II->getBuiltinID()) {
9773         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9774           // Validate the type matches unless this builtin is specified as
9775           // matching regardless of its declared type.
9776           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9777             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9778           } else {
9779             ASTContext::GetBuiltinTypeError Error;
9780             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9781             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9782 
9783             if (!Error && !BuiltinType.isNull() &&
9784                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9785                     NewFD->getType(), BuiltinType))
9786               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9787           }
9788         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9789                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9790           // FIXME: We should consider this a builtin only in the std namespace.
9791           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9792         }
9793       }
9794     }
9795   }
9796 
9797   ProcessPragmaWeak(S, NewFD);
9798   checkAttributesAfterMerging(*this, *NewFD);
9799 
9800   AddKnownFunctionAttributes(NewFD);
9801 
9802   if (NewFD->hasAttr<OverloadableAttr>() &&
9803       !NewFD->getType()->getAs<FunctionProtoType>()) {
9804     Diag(NewFD->getLocation(),
9805          diag::err_attribute_overloadable_no_prototype)
9806       << NewFD;
9807 
9808     // Turn this into a variadic function with no parameters.
9809     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9810     FunctionProtoType::ExtProtoInfo EPI(
9811         Context.getDefaultCallingConvention(true, false));
9812     EPI.Variadic = true;
9813     EPI.ExtInfo = FT->getExtInfo();
9814 
9815     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9816     NewFD->setType(R);
9817   }
9818 
9819   // If there's a #pragma GCC visibility in scope, and this isn't a class
9820   // member, set the visibility of this function.
9821   if (!DC->isRecord() && NewFD->isExternallyVisible())
9822     AddPushedVisibilityAttribute(NewFD);
9823 
9824   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9825   // marking the function.
9826   AddCFAuditedAttribute(NewFD);
9827 
9828   // If this is a function definition, check if we have to apply optnone due to
9829   // a pragma.
9830   if(D.isFunctionDefinition())
9831     AddRangeBasedOptnone(NewFD);
9832 
9833   // If this is the first declaration of an extern C variable, update
9834   // the map of such variables.
9835   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9836       isIncompleteDeclExternC(*this, NewFD))
9837     RegisterLocallyScopedExternCDecl(NewFD, S);
9838 
9839   // Set this FunctionDecl's range up to the right paren.
9840   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9841 
9842   if (D.isRedeclaration() && !Previous.empty()) {
9843     NamedDecl *Prev = Previous.getRepresentativeDecl();
9844     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9845                                    isMemberSpecialization ||
9846                                        isFunctionTemplateSpecialization,
9847                                    D.isFunctionDefinition());
9848   }
9849 
9850   if (getLangOpts().CUDA) {
9851     IdentifierInfo *II = NewFD->getIdentifier();
9852     if (II && II->isStr(getCudaConfigureFuncName()) &&
9853         !NewFD->isInvalidDecl() &&
9854         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9855       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9856         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9857             << getCudaConfigureFuncName();
9858       Context.setcudaConfigureCallDecl(NewFD);
9859     }
9860 
9861     // Variadic functions, other than a *declaration* of printf, are not allowed
9862     // in device-side CUDA code, unless someone passed
9863     // -fcuda-allow-variadic-functions.
9864     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9865         (NewFD->hasAttr<CUDADeviceAttr>() ||
9866          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9867         !(II && II->isStr("printf") && NewFD->isExternC() &&
9868           !D.isFunctionDefinition())) {
9869       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9870     }
9871   }
9872 
9873   MarkUnusedFileScopedDecl(NewFD);
9874 
9875 
9876 
9877   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9878     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9879     if ((getLangOpts().OpenCLVersion >= 120)
9880         && (SC == SC_Static)) {
9881       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9882       D.setInvalidType();
9883     }
9884 
9885     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9886     if (!NewFD->getReturnType()->isVoidType()) {
9887       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9888       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9889           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9890                                 : FixItHint());
9891       D.setInvalidType();
9892     }
9893 
9894     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9895     for (auto Param : NewFD->parameters())
9896       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9897 
9898     if (getLangOpts().OpenCLCPlusPlus) {
9899       if (DC->isRecord()) {
9900         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9901         D.setInvalidType();
9902       }
9903       if (FunctionTemplate) {
9904         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9905         D.setInvalidType();
9906       }
9907     }
9908   }
9909 
9910   if (getLangOpts().CPlusPlus) {
9911     if (FunctionTemplate) {
9912       if (NewFD->isInvalidDecl())
9913         FunctionTemplate->setInvalidDecl();
9914       return FunctionTemplate;
9915     }
9916 
9917     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9918       CompleteMemberSpecialization(NewFD, Previous);
9919   }
9920 
9921   for (const ParmVarDecl *Param : NewFD->parameters()) {
9922     QualType PT = Param->getType();
9923 
9924     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9925     // types.
9926     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9927       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9928         QualType ElemTy = PipeTy->getElementType();
9929           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9930             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9931             D.setInvalidType();
9932           }
9933       }
9934     }
9935   }
9936 
9937   // Here we have an function template explicit specialization at class scope.
9938   // The actual specialization will be postponed to template instatiation
9939   // time via the ClassScopeFunctionSpecializationDecl node.
9940   if (isDependentClassScopeExplicitSpecialization) {
9941     ClassScopeFunctionSpecializationDecl *NewSpec =
9942                          ClassScopeFunctionSpecializationDecl::Create(
9943                                 Context, CurContext, NewFD->getLocation(),
9944                                 cast<CXXMethodDecl>(NewFD),
9945                                 HasExplicitTemplateArgs, TemplateArgs);
9946     CurContext->addDecl(NewSpec);
9947     AddToScope = false;
9948   }
9949 
9950   // Diagnose availability attributes. Availability cannot be used on functions
9951   // that are run during load/unload.
9952   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9953     if (NewFD->hasAttr<ConstructorAttr>()) {
9954       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9955           << 1;
9956       NewFD->dropAttr<AvailabilityAttr>();
9957     }
9958     if (NewFD->hasAttr<DestructorAttr>()) {
9959       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9960           << 2;
9961       NewFD->dropAttr<AvailabilityAttr>();
9962     }
9963   }
9964 
9965   // Diagnose no_builtin attribute on function declaration that are not a
9966   // definition.
9967   // FIXME: We should really be doing this in
9968   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9969   // the FunctionDecl and at this point of the code
9970   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9971   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9972   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9973     switch (D.getFunctionDefinitionKind()) {
9974     case FunctionDefinitionKind::Defaulted:
9975     case FunctionDefinitionKind::Deleted:
9976       Diag(NBA->getLocation(),
9977            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9978           << NBA->getSpelling();
9979       break;
9980     case FunctionDefinitionKind::Declaration:
9981       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9982           << NBA->getSpelling();
9983       break;
9984     case FunctionDefinitionKind::Definition:
9985       break;
9986     }
9987 
9988   return NewFD;
9989 }
9990 
9991 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9992 /// when __declspec(code_seg) "is applied to a class, all member functions of
9993 /// the class and nested classes -- this includes compiler-generated special
9994 /// member functions -- are put in the specified segment."
9995 /// The actual behavior is a little more complicated. The Microsoft compiler
9996 /// won't check outer classes if there is an active value from #pragma code_seg.
9997 /// The CodeSeg is always applied from the direct parent but only from outer
9998 /// classes when the #pragma code_seg stack is empty. See:
9999 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10000 /// available since MS has removed the page.
10001 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10002   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10003   if (!Method)
10004     return nullptr;
10005   const CXXRecordDecl *Parent = Method->getParent();
10006   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10007     Attr *NewAttr = SAttr->clone(S.getASTContext());
10008     NewAttr->setImplicit(true);
10009     return NewAttr;
10010   }
10011 
10012   // The Microsoft compiler won't check outer classes for the CodeSeg
10013   // when the #pragma code_seg stack is active.
10014   if (S.CodeSegStack.CurrentValue)
10015    return nullptr;
10016 
10017   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10018     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10019       Attr *NewAttr = SAttr->clone(S.getASTContext());
10020       NewAttr->setImplicit(true);
10021       return NewAttr;
10022     }
10023   }
10024   return nullptr;
10025 }
10026 
10027 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10028 /// containing class. Otherwise it will return implicit SectionAttr if the
10029 /// function is a definition and there is an active value on CodeSegStack
10030 /// (from the current #pragma code-seg value).
10031 ///
10032 /// \param FD Function being declared.
10033 /// \param IsDefinition Whether it is a definition or just a declarartion.
10034 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10035 ///          nullptr if no attribute should be added.
10036 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10037                                                        bool IsDefinition) {
10038   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10039     return A;
10040   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10041       CodeSegStack.CurrentValue)
10042     return SectionAttr::CreateImplicit(
10043         getASTContext(), CodeSegStack.CurrentValue->getString(),
10044         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10045         SectionAttr::Declspec_allocate);
10046   return nullptr;
10047 }
10048 
10049 /// Determines if we can perform a correct type check for \p D as a
10050 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10051 /// best-effort check.
10052 ///
10053 /// \param NewD The new declaration.
10054 /// \param OldD The old declaration.
10055 /// \param NewT The portion of the type of the new declaration to check.
10056 /// \param OldT The portion of the type of the old declaration to check.
10057 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10058                                           QualType NewT, QualType OldT) {
10059   if (!NewD->getLexicalDeclContext()->isDependentContext())
10060     return true;
10061 
10062   // For dependently-typed local extern declarations and friends, we can't
10063   // perform a correct type check in general until instantiation:
10064   //
10065   //   int f();
10066   //   template<typename T> void g() { T f(); }
10067   //
10068   // (valid if g() is only instantiated with T = int).
10069   if (NewT->isDependentType() &&
10070       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10071     return false;
10072 
10073   // Similarly, if the previous declaration was a dependent local extern
10074   // declaration, we don't really know its type yet.
10075   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10076     return false;
10077 
10078   return true;
10079 }
10080 
10081 /// Checks if the new declaration declared in dependent context must be
10082 /// put in the same redeclaration chain as the specified declaration.
10083 ///
10084 /// \param D Declaration that is checked.
10085 /// \param PrevDecl Previous declaration found with proper lookup method for the
10086 ///                 same declaration name.
10087 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10088 ///          belongs to.
10089 ///
10090 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10091   if (!D->getLexicalDeclContext()->isDependentContext())
10092     return true;
10093 
10094   // Don't chain dependent friend function definitions until instantiation, to
10095   // permit cases like
10096   //
10097   //   void func();
10098   //   template<typename T> class C1 { friend void func() {} };
10099   //   template<typename T> class C2 { friend void func() {} };
10100   //
10101   // ... which is valid if only one of C1 and C2 is ever instantiated.
10102   //
10103   // FIXME: This need only apply to function definitions. For now, we proxy
10104   // this by checking for a file-scope function. We do not want this to apply
10105   // to friend declarations nominating member functions, because that gets in
10106   // the way of access checks.
10107   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10108     return false;
10109 
10110   auto *VD = dyn_cast<ValueDecl>(D);
10111   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10112   return !VD || !PrevVD ||
10113          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10114                                         PrevVD->getType());
10115 }
10116 
10117 /// Check the target attribute of the function for MultiVersion
10118 /// validity.
10119 ///
10120 /// Returns true if there was an error, false otherwise.
10121 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10122   const auto *TA = FD->getAttr<TargetAttr>();
10123   assert(TA && "MultiVersion Candidate requires a target attribute");
10124   ParsedTargetAttr ParseInfo = TA->parse();
10125   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10126   enum ErrType { Feature = 0, Architecture = 1 };
10127 
10128   if (!ParseInfo.Architecture.empty() &&
10129       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10130     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10131         << Architecture << ParseInfo.Architecture;
10132     return true;
10133   }
10134 
10135   for (const auto &Feat : ParseInfo.Features) {
10136     auto BareFeat = StringRef{Feat}.substr(1);
10137     if (Feat[0] == '-') {
10138       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10139           << Feature << ("no-" + BareFeat).str();
10140       return true;
10141     }
10142 
10143     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10144         !TargetInfo.isValidFeatureName(BareFeat)) {
10145       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10146           << Feature << BareFeat;
10147       return true;
10148     }
10149   }
10150   return false;
10151 }
10152 
10153 // Provide a white-list of attributes that are allowed to be combined with
10154 // multiversion functions.
10155 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10156                                            MultiVersionKind MVType) {
10157   // Note: this list/diagnosis must match the list in
10158   // checkMultiversionAttributesAllSame.
10159   switch (Kind) {
10160   default:
10161     return false;
10162   case attr::Used:
10163     return MVType == MultiVersionKind::Target;
10164   case attr::NonNull:
10165   case attr::NoThrow:
10166     return true;
10167   }
10168 }
10169 
10170 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10171                                                  const FunctionDecl *FD,
10172                                                  const FunctionDecl *CausedFD,
10173                                                  MultiVersionKind MVType) {
10174   bool IsCPUSpecificCPUDispatchMVType =
10175       MVType == MultiVersionKind::CPUDispatch ||
10176       MVType == MultiVersionKind::CPUSpecific;
10177   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10178                             Sema &S, const Attr *A) {
10179     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10180         << IsCPUSpecificCPUDispatchMVType << A;
10181     if (CausedFD)
10182       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10183     return true;
10184   };
10185 
10186   for (const Attr *A : FD->attrs()) {
10187     switch (A->getKind()) {
10188     case attr::CPUDispatch:
10189     case attr::CPUSpecific:
10190       if (MVType != MultiVersionKind::CPUDispatch &&
10191           MVType != MultiVersionKind::CPUSpecific)
10192         return Diagnose(S, A);
10193       break;
10194     case attr::Target:
10195       if (MVType != MultiVersionKind::Target)
10196         return Diagnose(S, A);
10197       break;
10198     default:
10199       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10200         return Diagnose(S, A);
10201       break;
10202     }
10203   }
10204   return false;
10205 }
10206 
10207 bool Sema::areMultiversionVariantFunctionsCompatible(
10208     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10209     const PartialDiagnostic &NoProtoDiagID,
10210     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10211     const PartialDiagnosticAt &NoSupportDiagIDAt,
10212     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10213     bool ConstexprSupported, bool CLinkageMayDiffer) {
10214   enum DoesntSupport {
10215     FuncTemplates = 0,
10216     VirtFuncs = 1,
10217     DeducedReturn = 2,
10218     Constructors = 3,
10219     Destructors = 4,
10220     DeletedFuncs = 5,
10221     DefaultedFuncs = 6,
10222     ConstexprFuncs = 7,
10223     ConstevalFuncs = 8,
10224   };
10225   enum Different {
10226     CallingConv = 0,
10227     ReturnType = 1,
10228     ConstexprSpec = 2,
10229     InlineSpec = 3,
10230     StorageClass = 4,
10231     Linkage = 5,
10232   };
10233 
10234   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10235       !OldFD->getType()->getAs<FunctionProtoType>()) {
10236     Diag(OldFD->getLocation(), NoProtoDiagID);
10237     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10238     return true;
10239   }
10240 
10241   if (NoProtoDiagID.getDiagID() != 0 &&
10242       !NewFD->getType()->getAs<FunctionProtoType>())
10243     return Diag(NewFD->getLocation(), NoProtoDiagID);
10244 
10245   if (!TemplatesSupported &&
10246       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10247     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10248            << FuncTemplates;
10249 
10250   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10251     if (NewCXXFD->isVirtual())
10252       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10253              << VirtFuncs;
10254 
10255     if (isa<CXXConstructorDecl>(NewCXXFD))
10256       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10257              << Constructors;
10258 
10259     if (isa<CXXDestructorDecl>(NewCXXFD))
10260       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10261              << Destructors;
10262   }
10263 
10264   if (NewFD->isDeleted())
10265     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10266            << DeletedFuncs;
10267 
10268   if (NewFD->isDefaulted())
10269     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10270            << DefaultedFuncs;
10271 
10272   if (!ConstexprSupported && NewFD->isConstexpr())
10273     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10274            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10275 
10276   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10277   const auto *NewType = cast<FunctionType>(NewQType);
10278   QualType NewReturnType = NewType->getReturnType();
10279 
10280   if (NewReturnType->isUndeducedType())
10281     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10282            << DeducedReturn;
10283 
10284   // Ensure the return type is identical.
10285   if (OldFD) {
10286     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10287     const auto *OldType = cast<FunctionType>(OldQType);
10288     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10289     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10290 
10291     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10292       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10293 
10294     QualType OldReturnType = OldType->getReturnType();
10295 
10296     if (OldReturnType != NewReturnType)
10297       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10298 
10299     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10300       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10301 
10302     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10303       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10304 
10305     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10306       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10307 
10308     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10309       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10310 
10311     if (CheckEquivalentExceptionSpec(
10312             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10313             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10314       return true;
10315   }
10316   return false;
10317 }
10318 
10319 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10320                                              const FunctionDecl *NewFD,
10321                                              bool CausesMV,
10322                                              MultiVersionKind MVType) {
10323   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10324     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10325     if (OldFD)
10326       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10327     return true;
10328   }
10329 
10330   bool IsCPUSpecificCPUDispatchMVType =
10331       MVType == MultiVersionKind::CPUDispatch ||
10332       MVType == MultiVersionKind::CPUSpecific;
10333 
10334   if (CausesMV && OldFD &&
10335       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10336     return true;
10337 
10338   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10339     return true;
10340 
10341   // Only allow transition to MultiVersion if it hasn't been used.
10342   if (OldFD && CausesMV && OldFD->isUsed(false))
10343     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10344 
10345   return S.areMultiversionVariantFunctionsCompatible(
10346       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10347       PartialDiagnosticAt(NewFD->getLocation(),
10348                           S.PDiag(diag::note_multiversioning_caused_here)),
10349       PartialDiagnosticAt(NewFD->getLocation(),
10350                           S.PDiag(diag::err_multiversion_doesnt_support)
10351                               << IsCPUSpecificCPUDispatchMVType),
10352       PartialDiagnosticAt(NewFD->getLocation(),
10353                           S.PDiag(diag::err_multiversion_diff)),
10354       /*TemplatesSupported=*/false,
10355       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10356       /*CLinkageMayDiffer=*/false);
10357 }
10358 
10359 /// Check the validity of a multiversion function declaration that is the
10360 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10361 ///
10362 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10363 ///
10364 /// Returns true if there was an error, false otherwise.
10365 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10366                                            MultiVersionKind MVType,
10367                                            const TargetAttr *TA) {
10368   assert(MVType != MultiVersionKind::None &&
10369          "Function lacks multiversion attribute");
10370 
10371   // Target only causes MV if it is default, otherwise this is a normal
10372   // function.
10373   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10374     return false;
10375 
10376   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10377     FD->setInvalidDecl();
10378     return true;
10379   }
10380 
10381   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10382     FD->setInvalidDecl();
10383     return true;
10384   }
10385 
10386   FD->setIsMultiVersion();
10387   return false;
10388 }
10389 
10390 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10391   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10392     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10393       return true;
10394   }
10395 
10396   return false;
10397 }
10398 
10399 static bool CheckTargetCausesMultiVersioning(
10400     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10401     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10402     LookupResult &Previous) {
10403   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10404   ParsedTargetAttr NewParsed = NewTA->parse();
10405   // Sort order doesn't matter, it just needs to be consistent.
10406   llvm::sort(NewParsed.Features);
10407 
10408   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10409   // to change, this is a simple redeclaration.
10410   if (!NewTA->isDefaultVersion() &&
10411       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10412     return false;
10413 
10414   // Otherwise, this decl causes MultiVersioning.
10415   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10416     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10417     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10418     NewFD->setInvalidDecl();
10419     return true;
10420   }
10421 
10422   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10423                                        MultiVersionKind::Target)) {
10424     NewFD->setInvalidDecl();
10425     return true;
10426   }
10427 
10428   if (CheckMultiVersionValue(S, NewFD)) {
10429     NewFD->setInvalidDecl();
10430     return true;
10431   }
10432 
10433   // If this is 'default', permit the forward declaration.
10434   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10435     Redeclaration = true;
10436     OldDecl = OldFD;
10437     OldFD->setIsMultiVersion();
10438     NewFD->setIsMultiVersion();
10439     return false;
10440   }
10441 
10442   if (CheckMultiVersionValue(S, OldFD)) {
10443     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10444     NewFD->setInvalidDecl();
10445     return true;
10446   }
10447 
10448   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10449 
10450   if (OldParsed == NewParsed) {
10451     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10452     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10453     NewFD->setInvalidDecl();
10454     return true;
10455   }
10456 
10457   for (const auto *FD : OldFD->redecls()) {
10458     const auto *CurTA = FD->getAttr<TargetAttr>();
10459     // We allow forward declarations before ANY multiversioning attributes, but
10460     // nothing after the fact.
10461     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10462         (!CurTA || CurTA->isInherited())) {
10463       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10464           << 0;
10465       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10466       NewFD->setInvalidDecl();
10467       return true;
10468     }
10469   }
10470 
10471   OldFD->setIsMultiVersion();
10472   NewFD->setIsMultiVersion();
10473   Redeclaration = false;
10474   MergeTypeWithPrevious = false;
10475   OldDecl = nullptr;
10476   Previous.clear();
10477   return false;
10478 }
10479 
10480 /// Check the validity of a new function declaration being added to an existing
10481 /// multiversioned declaration collection.
10482 static bool CheckMultiVersionAdditionalDecl(
10483     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10484     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10485     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10486     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10487     LookupResult &Previous) {
10488 
10489   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10490   // Disallow mixing of multiversioning types.
10491   if ((OldMVType == MultiVersionKind::Target &&
10492        NewMVType != MultiVersionKind::Target) ||
10493       (NewMVType == MultiVersionKind::Target &&
10494        OldMVType != MultiVersionKind::Target)) {
10495     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10496     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10497     NewFD->setInvalidDecl();
10498     return true;
10499   }
10500 
10501   ParsedTargetAttr NewParsed;
10502   if (NewTA) {
10503     NewParsed = NewTA->parse();
10504     llvm::sort(NewParsed.Features);
10505   }
10506 
10507   bool UseMemberUsingDeclRules =
10508       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10509 
10510   // Next, check ALL non-overloads to see if this is a redeclaration of a
10511   // previous member of the MultiVersion set.
10512   for (NamedDecl *ND : Previous) {
10513     FunctionDecl *CurFD = ND->getAsFunction();
10514     if (!CurFD)
10515       continue;
10516     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10517       continue;
10518 
10519     if (NewMVType == MultiVersionKind::Target) {
10520       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10521       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10522         NewFD->setIsMultiVersion();
10523         Redeclaration = true;
10524         OldDecl = ND;
10525         return false;
10526       }
10527 
10528       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10529       if (CurParsed == NewParsed) {
10530         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10531         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10532         NewFD->setInvalidDecl();
10533         return true;
10534       }
10535     } else {
10536       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10537       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10538       // Handle CPUDispatch/CPUSpecific versions.
10539       // Only 1 CPUDispatch function is allowed, this will make it go through
10540       // the redeclaration errors.
10541       if (NewMVType == MultiVersionKind::CPUDispatch &&
10542           CurFD->hasAttr<CPUDispatchAttr>()) {
10543         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10544             std::equal(
10545                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10546                 NewCPUDisp->cpus_begin(),
10547                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10548                   return Cur->getName() == New->getName();
10549                 })) {
10550           NewFD->setIsMultiVersion();
10551           Redeclaration = true;
10552           OldDecl = ND;
10553           return false;
10554         }
10555 
10556         // If the declarations don't match, this is an error condition.
10557         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10558         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10559         NewFD->setInvalidDecl();
10560         return true;
10561       }
10562       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10563 
10564         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10565             std::equal(
10566                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10567                 NewCPUSpec->cpus_begin(),
10568                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10569                   return Cur->getName() == New->getName();
10570                 })) {
10571           NewFD->setIsMultiVersion();
10572           Redeclaration = true;
10573           OldDecl = ND;
10574           return false;
10575         }
10576 
10577         // Only 1 version of CPUSpecific is allowed for each CPU.
10578         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10579           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10580             if (CurII == NewII) {
10581               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10582                   << NewII;
10583               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10584               NewFD->setInvalidDecl();
10585               return true;
10586             }
10587           }
10588         }
10589       }
10590       // If the two decls aren't the same MVType, there is no possible error
10591       // condition.
10592     }
10593   }
10594 
10595   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10596   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10597   // handled in the attribute adding step.
10598   if (NewMVType == MultiVersionKind::Target &&
10599       CheckMultiVersionValue(S, NewFD)) {
10600     NewFD->setInvalidDecl();
10601     return true;
10602   }
10603 
10604   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10605                                        !OldFD->isMultiVersion(), NewMVType)) {
10606     NewFD->setInvalidDecl();
10607     return true;
10608   }
10609 
10610   // Permit forward declarations in the case where these two are compatible.
10611   if (!OldFD->isMultiVersion()) {
10612     OldFD->setIsMultiVersion();
10613     NewFD->setIsMultiVersion();
10614     Redeclaration = true;
10615     OldDecl = OldFD;
10616     return false;
10617   }
10618 
10619   NewFD->setIsMultiVersion();
10620   Redeclaration = false;
10621   MergeTypeWithPrevious = false;
10622   OldDecl = nullptr;
10623   Previous.clear();
10624   return false;
10625 }
10626 
10627 
10628 /// Check the validity of a mulitversion function declaration.
10629 /// Also sets the multiversion'ness' of the function itself.
10630 ///
10631 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10632 ///
10633 /// Returns true if there was an error, false otherwise.
10634 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10635                                       bool &Redeclaration, NamedDecl *&OldDecl,
10636                                       bool &MergeTypeWithPrevious,
10637                                       LookupResult &Previous) {
10638   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10639   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10640   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10641 
10642   // Mixing Multiversioning types is prohibited.
10643   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10644       (NewCPUDisp && NewCPUSpec)) {
10645     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10646     NewFD->setInvalidDecl();
10647     return true;
10648   }
10649 
10650   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10651 
10652   // Main isn't allowed to become a multiversion function, however it IS
10653   // permitted to have 'main' be marked with the 'target' optimization hint.
10654   if (NewFD->isMain()) {
10655     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10656         MVType == MultiVersionKind::CPUDispatch ||
10657         MVType == MultiVersionKind::CPUSpecific) {
10658       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10659       NewFD->setInvalidDecl();
10660       return true;
10661     }
10662     return false;
10663   }
10664 
10665   if (!OldDecl || !OldDecl->getAsFunction() ||
10666       OldDecl->getDeclContext()->getRedeclContext() !=
10667           NewFD->getDeclContext()->getRedeclContext()) {
10668     // If there's no previous declaration, AND this isn't attempting to cause
10669     // multiversioning, this isn't an error condition.
10670     if (MVType == MultiVersionKind::None)
10671       return false;
10672     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10673   }
10674 
10675   FunctionDecl *OldFD = OldDecl->getAsFunction();
10676 
10677   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10678     return false;
10679 
10680   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10681     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10682         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10683     NewFD->setInvalidDecl();
10684     return true;
10685   }
10686 
10687   // Handle the target potentially causes multiversioning case.
10688   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10689     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10690                                             Redeclaration, OldDecl,
10691                                             MergeTypeWithPrevious, Previous);
10692 
10693   // At this point, we have a multiversion function decl (in OldFD) AND an
10694   // appropriate attribute in the current function decl.  Resolve that these are
10695   // still compatible with previous declarations.
10696   return CheckMultiVersionAdditionalDecl(
10697       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10698       OldDecl, MergeTypeWithPrevious, Previous);
10699 }
10700 
10701 /// Perform semantic checking of a new function declaration.
10702 ///
10703 /// Performs semantic analysis of the new function declaration
10704 /// NewFD. This routine performs all semantic checking that does not
10705 /// require the actual declarator involved in the declaration, and is
10706 /// used both for the declaration of functions as they are parsed
10707 /// (called via ActOnDeclarator) and for the declaration of functions
10708 /// that have been instantiated via C++ template instantiation (called
10709 /// via InstantiateDecl).
10710 ///
10711 /// \param IsMemberSpecialization whether this new function declaration is
10712 /// a member specialization (that replaces any definition provided by the
10713 /// previous declaration).
10714 ///
10715 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10716 ///
10717 /// \returns true if the function declaration is a redeclaration.
10718 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10719                                     LookupResult &Previous,
10720                                     bool IsMemberSpecialization) {
10721   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10722          "Variably modified return types are not handled here");
10723 
10724   // Determine whether the type of this function should be merged with
10725   // a previous visible declaration. This never happens for functions in C++,
10726   // and always happens in C if the previous declaration was visible.
10727   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10728                                !Previous.isShadowed();
10729 
10730   bool Redeclaration = false;
10731   NamedDecl *OldDecl = nullptr;
10732   bool MayNeedOverloadableChecks = false;
10733 
10734   // Merge or overload the declaration with an existing declaration of
10735   // the same name, if appropriate.
10736   if (!Previous.empty()) {
10737     // Determine whether NewFD is an overload of PrevDecl or
10738     // a declaration that requires merging. If it's an overload,
10739     // there's no more work to do here; we'll just add the new
10740     // function to the scope.
10741     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10742       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10743       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10744         Redeclaration = true;
10745         OldDecl = Candidate;
10746       }
10747     } else {
10748       MayNeedOverloadableChecks = true;
10749       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10750                             /*NewIsUsingDecl*/ false)) {
10751       case Ovl_Match:
10752         Redeclaration = true;
10753         break;
10754 
10755       case Ovl_NonFunction:
10756         Redeclaration = true;
10757         break;
10758 
10759       case Ovl_Overload:
10760         Redeclaration = false;
10761         break;
10762       }
10763     }
10764   }
10765 
10766   // Check for a previous extern "C" declaration with this name.
10767   if (!Redeclaration &&
10768       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10769     if (!Previous.empty()) {
10770       // This is an extern "C" declaration with the same name as a previous
10771       // declaration, and thus redeclares that entity...
10772       Redeclaration = true;
10773       OldDecl = Previous.getFoundDecl();
10774       MergeTypeWithPrevious = false;
10775 
10776       // ... except in the presence of __attribute__((overloadable)).
10777       if (OldDecl->hasAttr<OverloadableAttr>() ||
10778           NewFD->hasAttr<OverloadableAttr>()) {
10779         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10780           MayNeedOverloadableChecks = true;
10781           Redeclaration = false;
10782           OldDecl = nullptr;
10783         }
10784       }
10785     }
10786   }
10787 
10788   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10789                                 MergeTypeWithPrevious, Previous))
10790     return Redeclaration;
10791 
10792   // PPC MMA non-pointer types are not allowed as function return types.
10793   if (Context.getTargetInfo().getTriple().isPPC64() &&
10794       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10795     NewFD->setInvalidDecl();
10796   }
10797 
10798   // C++11 [dcl.constexpr]p8:
10799   //   A constexpr specifier for a non-static member function that is not
10800   //   a constructor declares that member function to be const.
10801   //
10802   // This needs to be delayed until we know whether this is an out-of-line
10803   // definition of a static member function.
10804   //
10805   // This rule is not present in C++1y, so we produce a backwards
10806   // compatibility warning whenever it happens in C++11.
10807   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10808   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10809       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10810       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10811     CXXMethodDecl *OldMD = nullptr;
10812     if (OldDecl)
10813       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10814     if (!OldMD || !OldMD->isStatic()) {
10815       const FunctionProtoType *FPT =
10816         MD->getType()->castAs<FunctionProtoType>();
10817       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10818       EPI.TypeQuals.addConst();
10819       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10820                                           FPT->getParamTypes(), EPI));
10821 
10822       // Warn that we did this, if we're not performing template instantiation.
10823       // In that case, we'll have warned already when the template was defined.
10824       if (!inTemplateInstantiation()) {
10825         SourceLocation AddConstLoc;
10826         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10827                 .IgnoreParens().getAs<FunctionTypeLoc>())
10828           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10829 
10830         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10831           << FixItHint::CreateInsertion(AddConstLoc, " const");
10832       }
10833     }
10834   }
10835 
10836   if (Redeclaration) {
10837     // NewFD and OldDecl represent declarations that need to be
10838     // merged.
10839     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10840       NewFD->setInvalidDecl();
10841       return Redeclaration;
10842     }
10843 
10844     Previous.clear();
10845     Previous.addDecl(OldDecl);
10846 
10847     if (FunctionTemplateDecl *OldTemplateDecl =
10848             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10849       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10850       FunctionTemplateDecl *NewTemplateDecl
10851         = NewFD->getDescribedFunctionTemplate();
10852       assert(NewTemplateDecl && "Template/non-template mismatch");
10853 
10854       // The call to MergeFunctionDecl above may have created some state in
10855       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10856       // can add it as a redeclaration.
10857       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10858 
10859       NewFD->setPreviousDeclaration(OldFD);
10860       if (NewFD->isCXXClassMember()) {
10861         NewFD->setAccess(OldTemplateDecl->getAccess());
10862         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10863       }
10864 
10865       // If this is an explicit specialization of a member that is a function
10866       // template, mark it as a member specialization.
10867       if (IsMemberSpecialization &&
10868           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10869         NewTemplateDecl->setMemberSpecialization();
10870         assert(OldTemplateDecl->isMemberSpecialization());
10871         // Explicit specializations of a member template do not inherit deleted
10872         // status from the parent member template that they are specializing.
10873         if (OldFD->isDeleted()) {
10874           // FIXME: This assert will not hold in the presence of modules.
10875           assert(OldFD->getCanonicalDecl() == OldFD);
10876           // FIXME: We need an update record for this AST mutation.
10877           OldFD->setDeletedAsWritten(false);
10878         }
10879       }
10880 
10881     } else {
10882       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10883         auto *OldFD = cast<FunctionDecl>(OldDecl);
10884         // This needs to happen first so that 'inline' propagates.
10885         NewFD->setPreviousDeclaration(OldFD);
10886         if (NewFD->isCXXClassMember())
10887           NewFD->setAccess(OldFD->getAccess());
10888       }
10889     }
10890   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10891              !NewFD->getAttr<OverloadableAttr>()) {
10892     assert((Previous.empty() ||
10893             llvm::any_of(Previous,
10894                          [](const NamedDecl *ND) {
10895                            return ND->hasAttr<OverloadableAttr>();
10896                          })) &&
10897            "Non-redecls shouldn't happen without overloadable present");
10898 
10899     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10900       const auto *FD = dyn_cast<FunctionDecl>(ND);
10901       return FD && !FD->hasAttr<OverloadableAttr>();
10902     });
10903 
10904     if (OtherUnmarkedIter != Previous.end()) {
10905       Diag(NewFD->getLocation(),
10906            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10907       Diag((*OtherUnmarkedIter)->getLocation(),
10908            diag::note_attribute_overloadable_prev_overload)
10909           << false;
10910 
10911       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10912     }
10913   }
10914 
10915   if (LangOpts.OpenMP)
10916     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10917 
10918   // Semantic checking for this function declaration (in isolation).
10919 
10920   if (getLangOpts().CPlusPlus) {
10921     // C++-specific checks.
10922     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10923       CheckConstructor(Constructor);
10924     } else if (CXXDestructorDecl *Destructor =
10925                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10926       CXXRecordDecl *Record = Destructor->getParent();
10927       QualType ClassType = Context.getTypeDeclType(Record);
10928 
10929       // FIXME: Shouldn't we be able to perform this check even when the class
10930       // type is dependent? Both gcc and edg can handle that.
10931       if (!ClassType->isDependentType()) {
10932         DeclarationName Name
10933           = Context.DeclarationNames.getCXXDestructorName(
10934                                         Context.getCanonicalType(ClassType));
10935         if (NewFD->getDeclName() != Name) {
10936           Diag(NewFD->getLocation(), diag::err_destructor_name);
10937           NewFD->setInvalidDecl();
10938           return Redeclaration;
10939         }
10940       }
10941     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10942       if (auto *TD = Guide->getDescribedFunctionTemplate())
10943         CheckDeductionGuideTemplate(TD);
10944 
10945       // A deduction guide is not on the list of entities that can be
10946       // explicitly specialized.
10947       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10948         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10949             << /*explicit specialization*/ 1;
10950     }
10951 
10952     // Find any virtual functions that this function overrides.
10953     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10954       if (!Method->isFunctionTemplateSpecialization() &&
10955           !Method->getDescribedFunctionTemplate() &&
10956           Method->isCanonicalDecl()) {
10957         AddOverriddenMethods(Method->getParent(), Method);
10958       }
10959       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10960         // C++2a [class.virtual]p6
10961         // A virtual method shall not have a requires-clause.
10962         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10963              diag::err_constrained_virtual_method);
10964 
10965       if (Method->isStatic())
10966         checkThisInStaticMemberFunctionType(Method);
10967     }
10968 
10969     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10970       ActOnConversionDeclarator(Conversion);
10971 
10972     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10973     if (NewFD->isOverloadedOperator() &&
10974         CheckOverloadedOperatorDeclaration(NewFD)) {
10975       NewFD->setInvalidDecl();
10976       return Redeclaration;
10977     }
10978 
10979     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10980     if (NewFD->getLiteralIdentifier() &&
10981         CheckLiteralOperatorDeclaration(NewFD)) {
10982       NewFD->setInvalidDecl();
10983       return Redeclaration;
10984     }
10985 
10986     // In C++, check default arguments now that we have merged decls. Unless
10987     // the lexical context is the class, because in this case this is done
10988     // during delayed parsing anyway.
10989     if (!CurContext->isRecord())
10990       CheckCXXDefaultArguments(NewFD);
10991 
10992     // If this function is declared as being extern "C", then check to see if
10993     // the function returns a UDT (class, struct, or union type) that is not C
10994     // compatible, and if it does, warn the user.
10995     // But, issue any diagnostic on the first declaration only.
10996     if (Previous.empty() && NewFD->isExternC()) {
10997       QualType R = NewFD->getReturnType();
10998       if (R->isIncompleteType() && !R->isVoidType())
10999         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11000             << NewFD << R;
11001       else if (!R.isPODType(Context) && !R->isVoidType() &&
11002                !R->isObjCObjectPointerType())
11003         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11004     }
11005 
11006     // C++1z [dcl.fct]p6:
11007     //   [...] whether the function has a non-throwing exception-specification
11008     //   [is] part of the function type
11009     //
11010     // This results in an ABI break between C++14 and C++17 for functions whose
11011     // declared type includes an exception-specification in a parameter or
11012     // return type. (Exception specifications on the function itself are OK in
11013     // most cases, and exception specifications are not permitted in most other
11014     // contexts where they could make it into a mangling.)
11015     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11016       auto HasNoexcept = [&](QualType T) -> bool {
11017         // Strip off declarator chunks that could be between us and a function
11018         // type. We don't need to look far, exception specifications are very
11019         // restricted prior to C++17.
11020         if (auto *RT = T->getAs<ReferenceType>())
11021           T = RT->getPointeeType();
11022         else if (T->isAnyPointerType())
11023           T = T->getPointeeType();
11024         else if (auto *MPT = T->getAs<MemberPointerType>())
11025           T = MPT->getPointeeType();
11026         if (auto *FPT = T->getAs<FunctionProtoType>())
11027           if (FPT->isNothrow())
11028             return true;
11029         return false;
11030       };
11031 
11032       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11033       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11034       for (QualType T : FPT->param_types())
11035         AnyNoexcept |= HasNoexcept(T);
11036       if (AnyNoexcept)
11037         Diag(NewFD->getLocation(),
11038              diag::warn_cxx17_compat_exception_spec_in_signature)
11039             << NewFD;
11040     }
11041 
11042     if (!Redeclaration && LangOpts.CUDA)
11043       checkCUDATargetOverload(NewFD, Previous);
11044   }
11045   return Redeclaration;
11046 }
11047 
11048 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11049   // C++11 [basic.start.main]p3:
11050   //   A program that [...] declares main to be inline, static or
11051   //   constexpr is ill-formed.
11052   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11053   //   appear in a declaration of main.
11054   // static main is not an error under C99, but we should warn about it.
11055   // We accept _Noreturn main as an extension.
11056   if (FD->getStorageClass() == SC_Static)
11057     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11058          ? diag::err_static_main : diag::warn_static_main)
11059       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11060   if (FD->isInlineSpecified())
11061     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11062       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11063   if (DS.isNoreturnSpecified()) {
11064     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11065     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11066     Diag(NoreturnLoc, diag::ext_noreturn_main);
11067     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11068       << FixItHint::CreateRemoval(NoreturnRange);
11069   }
11070   if (FD->isConstexpr()) {
11071     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11072         << FD->isConsteval()
11073         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11074     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11075   }
11076 
11077   if (getLangOpts().OpenCL) {
11078     Diag(FD->getLocation(), diag::err_opencl_no_main)
11079         << FD->hasAttr<OpenCLKernelAttr>();
11080     FD->setInvalidDecl();
11081     return;
11082   }
11083 
11084   QualType T = FD->getType();
11085   assert(T->isFunctionType() && "function decl is not of function type");
11086   const FunctionType* FT = T->castAs<FunctionType>();
11087 
11088   // Set default calling convention for main()
11089   if (FT->getCallConv() != CC_C) {
11090     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11091     FD->setType(QualType(FT, 0));
11092     T = Context.getCanonicalType(FD->getType());
11093   }
11094 
11095   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11096     // In C with GNU extensions we allow main() to have non-integer return
11097     // type, but we should warn about the extension, and we disable the
11098     // implicit-return-zero rule.
11099 
11100     // GCC in C mode accepts qualified 'int'.
11101     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11102       FD->setHasImplicitReturnZero(true);
11103     else {
11104       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11105       SourceRange RTRange = FD->getReturnTypeSourceRange();
11106       if (RTRange.isValid())
11107         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11108             << FixItHint::CreateReplacement(RTRange, "int");
11109     }
11110   } else {
11111     // In C and C++, main magically returns 0 if you fall off the end;
11112     // set the flag which tells us that.
11113     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11114 
11115     // All the standards say that main() should return 'int'.
11116     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11117       FD->setHasImplicitReturnZero(true);
11118     else {
11119       // Otherwise, this is just a flat-out error.
11120       SourceRange RTRange = FD->getReturnTypeSourceRange();
11121       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11122           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11123                                 : FixItHint());
11124       FD->setInvalidDecl(true);
11125     }
11126   }
11127 
11128   // Treat protoless main() as nullary.
11129   if (isa<FunctionNoProtoType>(FT)) return;
11130 
11131   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11132   unsigned nparams = FTP->getNumParams();
11133   assert(FD->getNumParams() == nparams);
11134 
11135   bool HasExtraParameters = (nparams > 3);
11136 
11137   if (FTP->isVariadic()) {
11138     Diag(FD->getLocation(), diag::ext_variadic_main);
11139     // FIXME: if we had information about the location of the ellipsis, we
11140     // could add a FixIt hint to remove it as a parameter.
11141   }
11142 
11143   // Darwin passes an undocumented fourth argument of type char**.  If
11144   // other platforms start sprouting these, the logic below will start
11145   // getting shifty.
11146   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11147     HasExtraParameters = false;
11148 
11149   if (HasExtraParameters) {
11150     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11151     FD->setInvalidDecl(true);
11152     nparams = 3;
11153   }
11154 
11155   // FIXME: a lot of the following diagnostics would be improved
11156   // if we had some location information about types.
11157 
11158   QualType CharPP =
11159     Context.getPointerType(Context.getPointerType(Context.CharTy));
11160   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11161 
11162   for (unsigned i = 0; i < nparams; ++i) {
11163     QualType AT = FTP->getParamType(i);
11164 
11165     bool mismatch = true;
11166 
11167     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11168       mismatch = false;
11169     else if (Expected[i] == CharPP) {
11170       // As an extension, the following forms are okay:
11171       //   char const **
11172       //   char const * const *
11173       //   char * const *
11174 
11175       QualifierCollector qs;
11176       const PointerType* PT;
11177       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11178           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11179           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11180                               Context.CharTy)) {
11181         qs.removeConst();
11182         mismatch = !qs.empty();
11183       }
11184     }
11185 
11186     if (mismatch) {
11187       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11188       // TODO: suggest replacing given type with expected type
11189       FD->setInvalidDecl(true);
11190     }
11191   }
11192 
11193   if (nparams == 1 && !FD->isInvalidDecl()) {
11194     Diag(FD->getLocation(), diag::warn_main_one_arg);
11195   }
11196 
11197   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11198     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11199     FD->setInvalidDecl();
11200   }
11201 }
11202 
11203 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11204 
11205   // Default calling convention for main and wmain is __cdecl
11206   if (FD->getName() == "main" || FD->getName() == "wmain")
11207     return false;
11208 
11209   // Default calling convention for MinGW is __cdecl
11210   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11211   if (T.isWindowsGNUEnvironment())
11212     return false;
11213 
11214   // Default calling convention for WinMain, wWinMain and DllMain
11215   // is __stdcall on 32 bit Windows
11216   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11217     return true;
11218 
11219   return false;
11220 }
11221 
11222 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11223   QualType T = FD->getType();
11224   assert(T->isFunctionType() && "function decl is not of function type");
11225   const FunctionType *FT = T->castAs<FunctionType>();
11226 
11227   // Set an implicit return of 'zero' if the function can return some integral,
11228   // enumeration, pointer or nullptr type.
11229   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11230       FT->getReturnType()->isAnyPointerType() ||
11231       FT->getReturnType()->isNullPtrType())
11232     // DllMain is exempt because a return value of zero means it failed.
11233     if (FD->getName() != "DllMain")
11234       FD->setHasImplicitReturnZero(true);
11235 
11236   // Explicity specified calling conventions are applied to MSVC entry points
11237   if (!hasExplicitCallingConv(T)) {
11238     if (isDefaultStdCall(FD, *this)) {
11239       if (FT->getCallConv() != CC_X86StdCall) {
11240         FT = Context.adjustFunctionType(
11241             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11242         FD->setType(QualType(FT, 0));
11243       }
11244     } else if (FT->getCallConv() != CC_C) {
11245       FT = Context.adjustFunctionType(FT,
11246                                       FT->getExtInfo().withCallingConv(CC_C));
11247       FD->setType(QualType(FT, 0));
11248     }
11249   }
11250 
11251   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11252     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11253     FD->setInvalidDecl();
11254   }
11255 }
11256 
11257 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11258   // FIXME: Need strict checking.  In C89, we need to check for
11259   // any assignment, increment, decrement, function-calls, or
11260   // commas outside of a sizeof.  In C99, it's the same list,
11261   // except that the aforementioned are allowed in unevaluated
11262   // expressions.  Everything else falls under the
11263   // "may accept other forms of constant expressions" exception.
11264   //
11265   // Regular C++ code will not end up here (exceptions: language extensions,
11266   // OpenCL C++ etc), so the constant expression rules there don't matter.
11267   if (Init->isValueDependent()) {
11268     assert(Init->containsErrors() &&
11269            "Dependent code should only occur in error-recovery path.");
11270     return true;
11271   }
11272   const Expr *Culprit;
11273   if (Init->isConstantInitializer(Context, false, &Culprit))
11274     return false;
11275   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11276     << Culprit->getSourceRange();
11277   return true;
11278 }
11279 
11280 namespace {
11281   // Visits an initialization expression to see if OrigDecl is evaluated in
11282   // its own initialization and throws a warning if it does.
11283   class SelfReferenceChecker
11284       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11285     Sema &S;
11286     Decl *OrigDecl;
11287     bool isRecordType;
11288     bool isPODType;
11289     bool isReferenceType;
11290 
11291     bool isInitList;
11292     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11293 
11294   public:
11295     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11296 
11297     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11298                                                     S(S), OrigDecl(OrigDecl) {
11299       isPODType = false;
11300       isRecordType = false;
11301       isReferenceType = false;
11302       isInitList = false;
11303       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11304         isPODType = VD->getType().isPODType(S.Context);
11305         isRecordType = VD->getType()->isRecordType();
11306         isReferenceType = VD->getType()->isReferenceType();
11307       }
11308     }
11309 
11310     // For most expressions, just call the visitor.  For initializer lists,
11311     // track the index of the field being initialized since fields are
11312     // initialized in order allowing use of previously initialized fields.
11313     void CheckExpr(Expr *E) {
11314       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11315       if (!InitList) {
11316         Visit(E);
11317         return;
11318       }
11319 
11320       // Track and increment the index here.
11321       isInitList = true;
11322       InitFieldIndex.push_back(0);
11323       for (auto Child : InitList->children()) {
11324         CheckExpr(cast<Expr>(Child));
11325         ++InitFieldIndex.back();
11326       }
11327       InitFieldIndex.pop_back();
11328     }
11329 
11330     // Returns true if MemberExpr is checked and no further checking is needed.
11331     // Returns false if additional checking is required.
11332     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11333       llvm::SmallVector<FieldDecl*, 4> Fields;
11334       Expr *Base = E;
11335       bool ReferenceField = false;
11336 
11337       // Get the field members used.
11338       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11339         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11340         if (!FD)
11341           return false;
11342         Fields.push_back(FD);
11343         if (FD->getType()->isReferenceType())
11344           ReferenceField = true;
11345         Base = ME->getBase()->IgnoreParenImpCasts();
11346       }
11347 
11348       // Keep checking only if the base Decl is the same.
11349       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11350       if (!DRE || DRE->getDecl() != OrigDecl)
11351         return false;
11352 
11353       // A reference field can be bound to an unininitialized field.
11354       if (CheckReference && !ReferenceField)
11355         return true;
11356 
11357       // Convert FieldDecls to their index number.
11358       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11359       for (const FieldDecl *I : llvm::reverse(Fields))
11360         UsedFieldIndex.push_back(I->getFieldIndex());
11361 
11362       // See if a warning is needed by checking the first difference in index
11363       // numbers.  If field being used has index less than the field being
11364       // initialized, then the use is safe.
11365       for (auto UsedIter = UsedFieldIndex.begin(),
11366                 UsedEnd = UsedFieldIndex.end(),
11367                 OrigIter = InitFieldIndex.begin(),
11368                 OrigEnd = InitFieldIndex.end();
11369            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11370         if (*UsedIter < *OrigIter)
11371           return true;
11372         if (*UsedIter > *OrigIter)
11373           break;
11374       }
11375 
11376       // TODO: Add a different warning which will print the field names.
11377       HandleDeclRefExpr(DRE);
11378       return true;
11379     }
11380 
11381     // For most expressions, the cast is directly above the DeclRefExpr.
11382     // For conditional operators, the cast can be outside the conditional
11383     // operator if both expressions are DeclRefExpr's.
11384     void HandleValue(Expr *E) {
11385       E = E->IgnoreParens();
11386       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11387         HandleDeclRefExpr(DRE);
11388         return;
11389       }
11390 
11391       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11392         Visit(CO->getCond());
11393         HandleValue(CO->getTrueExpr());
11394         HandleValue(CO->getFalseExpr());
11395         return;
11396       }
11397 
11398       if (BinaryConditionalOperator *BCO =
11399               dyn_cast<BinaryConditionalOperator>(E)) {
11400         Visit(BCO->getCond());
11401         HandleValue(BCO->getFalseExpr());
11402         return;
11403       }
11404 
11405       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11406         HandleValue(OVE->getSourceExpr());
11407         return;
11408       }
11409 
11410       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11411         if (BO->getOpcode() == BO_Comma) {
11412           Visit(BO->getLHS());
11413           HandleValue(BO->getRHS());
11414           return;
11415         }
11416       }
11417 
11418       if (isa<MemberExpr>(E)) {
11419         if (isInitList) {
11420           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11421                                       false /*CheckReference*/))
11422             return;
11423         }
11424 
11425         Expr *Base = E->IgnoreParenImpCasts();
11426         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11427           // Check for static member variables and don't warn on them.
11428           if (!isa<FieldDecl>(ME->getMemberDecl()))
11429             return;
11430           Base = ME->getBase()->IgnoreParenImpCasts();
11431         }
11432         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11433           HandleDeclRefExpr(DRE);
11434         return;
11435       }
11436 
11437       Visit(E);
11438     }
11439 
11440     // Reference types not handled in HandleValue are handled here since all
11441     // uses of references are bad, not just r-value uses.
11442     void VisitDeclRefExpr(DeclRefExpr *E) {
11443       if (isReferenceType)
11444         HandleDeclRefExpr(E);
11445     }
11446 
11447     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11448       if (E->getCastKind() == CK_LValueToRValue) {
11449         HandleValue(E->getSubExpr());
11450         return;
11451       }
11452 
11453       Inherited::VisitImplicitCastExpr(E);
11454     }
11455 
11456     void VisitMemberExpr(MemberExpr *E) {
11457       if (isInitList) {
11458         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11459           return;
11460       }
11461 
11462       // Don't warn on arrays since they can be treated as pointers.
11463       if (E->getType()->canDecayToPointerType()) return;
11464 
11465       // Warn when a non-static method call is followed by non-static member
11466       // field accesses, which is followed by a DeclRefExpr.
11467       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11468       bool Warn = (MD && !MD->isStatic());
11469       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11470       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11471         if (!isa<FieldDecl>(ME->getMemberDecl()))
11472           Warn = false;
11473         Base = ME->getBase()->IgnoreParenImpCasts();
11474       }
11475 
11476       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11477         if (Warn)
11478           HandleDeclRefExpr(DRE);
11479         return;
11480       }
11481 
11482       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11483       // Visit that expression.
11484       Visit(Base);
11485     }
11486 
11487     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11488       Expr *Callee = E->getCallee();
11489 
11490       if (isa<UnresolvedLookupExpr>(Callee))
11491         return Inherited::VisitCXXOperatorCallExpr(E);
11492 
11493       Visit(Callee);
11494       for (auto Arg: E->arguments())
11495         HandleValue(Arg->IgnoreParenImpCasts());
11496     }
11497 
11498     void VisitUnaryOperator(UnaryOperator *E) {
11499       // For POD record types, addresses of its own members are well-defined.
11500       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11501           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11502         if (!isPODType)
11503           HandleValue(E->getSubExpr());
11504         return;
11505       }
11506 
11507       if (E->isIncrementDecrementOp()) {
11508         HandleValue(E->getSubExpr());
11509         return;
11510       }
11511 
11512       Inherited::VisitUnaryOperator(E);
11513     }
11514 
11515     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11516 
11517     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11518       if (E->getConstructor()->isCopyConstructor()) {
11519         Expr *ArgExpr = E->getArg(0);
11520         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11521           if (ILE->getNumInits() == 1)
11522             ArgExpr = ILE->getInit(0);
11523         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11524           if (ICE->getCastKind() == CK_NoOp)
11525             ArgExpr = ICE->getSubExpr();
11526         HandleValue(ArgExpr);
11527         return;
11528       }
11529       Inherited::VisitCXXConstructExpr(E);
11530     }
11531 
11532     void VisitCallExpr(CallExpr *E) {
11533       // Treat std::move as a use.
11534       if (E->isCallToStdMove()) {
11535         HandleValue(E->getArg(0));
11536         return;
11537       }
11538 
11539       Inherited::VisitCallExpr(E);
11540     }
11541 
11542     void VisitBinaryOperator(BinaryOperator *E) {
11543       if (E->isCompoundAssignmentOp()) {
11544         HandleValue(E->getLHS());
11545         Visit(E->getRHS());
11546         return;
11547       }
11548 
11549       Inherited::VisitBinaryOperator(E);
11550     }
11551 
11552     // A custom visitor for BinaryConditionalOperator is needed because the
11553     // regular visitor would check the condition and true expression separately
11554     // but both point to the same place giving duplicate diagnostics.
11555     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11556       Visit(E->getCond());
11557       Visit(E->getFalseExpr());
11558     }
11559 
11560     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11561       Decl* ReferenceDecl = DRE->getDecl();
11562       if (OrigDecl != ReferenceDecl) return;
11563       unsigned diag;
11564       if (isReferenceType) {
11565         diag = diag::warn_uninit_self_reference_in_reference_init;
11566       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11567         diag = diag::warn_static_self_reference_in_init;
11568       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11569                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11570                  DRE->getDecl()->getType()->isRecordType()) {
11571         diag = diag::warn_uninit_self_reference_in_init;
11572       } else {
11573         // Local variables will be handled by the CFG analysis.
11574         return;
11575       }
11576 
11577       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11578                             S.PDiag(diag)
11579                                 << DRE->getDecl() << OrigDecl->getLocation()
11580                                 << DRE->getSourceRange());
11581     }
11582   };
11583 
11584   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11585   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11586                                  bool DirectInit) {
11587     // Parameters arguments are occassionially constructed with itself,
11588     // for instance, in recursive functions.  Skip them.
11589     if (isa<ParmVarDecl>(OrigDecl))
11590       return;
11591 
11592     E = E->IgnoreParens();
11593 
11594     // Skip checking T a = a where T is not a record or reference type.
11595     // Doing so is a way to silence uninitialized warnings.
11596     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11597       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11598         if (ICE->getCastKind() == CK_LValueToRValue)
11599           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11600             if (DRE->getDecl() == OrigDecl)
11601               return;
11602 
11603     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11604   }
11605 } // end anonymous namespace
11606 
11607 namespace {
11608   // Simple wrapper to add the name of a variable or (if no variable is
11609   // available) a DeclarationName into a diagnostic.
11610   struct VarDeclOrName {
11611     VarDecl *VDecl;
11612     DeclarationName Name;
11613 
11614     friend const Sema::SemaDiagnosticBuilder &
11615     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11616       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11617     }
11618   };
11619 } // end anonymous namespace
11620 
11621 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11622                                             DeclarationName Name, QualType Type,
11623                                             TypeSourceInfo *TSI,
11624                                             SourceRange Range, bool DirectInit,
11625                                             Expr *Init) {
11626   bool IsInitCapture = !VDecl;
11627   assert((!VDecl || !VDecl->isInitCapture()) &&
11628          "init captures are expected to be deduced prior to initialization");
11629 
11630   VarDeclOrName VN{VDecl, Name};
11631 
11632   DeducedType *Deduced = Type->getContainedDeducedType();
11633   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11634 
11635   // C++11 [dcl.spec.auto]p3
11636   if (!Init) {
11637     assert(VDecl && "no init for init capture deduction?");
11638 
11639     // Except for class argument deduction, and then for an initializing
11640     // declaration only, i.e. no static at class scope or extern.
11641     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11642         VDecl->hasExternalStorage() ||
11643         VDecl->isStaticDataMember()) {
11644       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11645         << VDecl->getDeclName() << Type;
11646       return QualType();
11647     }
11648   }
11649 
11650   ArrayRef<Expr*> DeduceInits;
11651   if (Init)
11652     DeduceInits = Init;
11653 
11654   if (DirectInit) {
11655     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11656       DeduceInits = PL->exprs();
11657   }
11658 
11659   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11660     assert(VDecl && "non-auto type for init capture deduction?");
11661     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11662     InitializationKind Kind = InitializationKind::CreateForInit(
11663         VDecl->getLocation(), DirectInit, Init);
11664     // FIXME: Initialization should not be taking a mutable list of inits.
11665     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11666     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11667                                                        InitsCopy);
11668   }
11669 
11670   if (DirectInit) {
11671     if (auto *IL = dyn_cast<InitListExpr>(Init))
11672       DeduceInits = IL->inits();
11673   }
11674 
11675   // Deduction only works if we have exactly one source expression.
11676   if (DeduceInits.empty()) {
11677     // It isn't possible to write this directly, but it is possible to
11678     // end up in this situation with "auto x(some_pack...);"
11679     Diag(Init->getBeginLoc(), IsInitCapture
11680                                   ? diag::err_init_capture_no_expression
11681                                   : diag::err_auto_var_init_no_expression)
11682         << VN << Type << Range;
11683     return QualType();
11684   }
11685 
11686   if (DeduceInits.size() > 1) {
11687     Diag(DeduceInits[1]->getBeginLoc(),
11688          IsInitCapture ? diag::err_init_capture_multiple_expressions
11689                        : diag::err_auto_var_init_multiple_expressions)
11690         << VN << Type << Range;
11691     return QualType();
11692   }
11693 
11694   Expr *DeduceInit = DeduceInits[0];
11695   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11696     Diag(Init->getBeginLoc(), IsInitCapture
11697                                   ? diag::err_init_capture_paren_braces
11698                                   : diag::err_auto_var_init_paren_braces)
11699         << isa<InitListExpr>(Init) << VN << Type << Range;
11700     return QualType();
11701   }
11702 
11703   // Expressions default to 'id' when we're in a debugger.
11704   bool DefaultedAnyToId = false;
11705   if (getLangOpts().DebuggerCastResultToId &&
11706       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11707     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11708     if (Result.isInvalid()) {
11709       return QualType();
11710     }
11711     Init = Result.get();
11712     DefaultedAnyToId = true;
11713   }
11714 
11715   // C++ [dcl.decomp]p1:
11716   //   If the assignment-expression [...] has array type A and no ref-qualifier
11717   //   is present, e has type cv A
11718   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11719       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11720       DeduceInit->getType()->isConstantArrayType())
11721     return Context.getQualifiedType(DeduceInit->getType(),
11722                                     Type.getQualifiers());
11723 
11724   QualType DeducedType;
11725   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11726     if (!IsInitCapture)
11727       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11728     else if (isa<InitListExpr>(Init))
11729       Diag(Range.getBegin(),
11730            diag::err_init_capture_deduction_failure_from_init_list)
11731           << VN
11732           << (DeduceInit->getType().isNull() ? TSI->getType()
11733                                              : DeduceInit->getType())
11734           << DeduceInit->getSourceRange();
11735     else
11736       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11737           << VN << TSI->getType()
11738           << (DeduceInit->getType().isNull() ? TSI->getType()
11739                                              : DeduceInit->getType())
11740           << DeduceInit->getSourceRange();
11741   }
11742 
11743   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11744   // 'id' instead of a specific object type prevents most of our usual
11745   // checks.
11746   // We only want to warn outside of template instantiations, though:
11747   // inside a template, the 'id' could have come from a parameter.
11748   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11749       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11750     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11751     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11752   }
11753 
11754   return DeducedType;
11755 }
11756 
11757 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11758                                          Expr *Init) {
11759   assert(!Init || !Init->containsErrors());
11760   QualType DeducedType = deduceVarTypeFromInitializer(
11761       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11762       VDecl->getSourceRange(), DirectInit, Init);
11763   if (DeducedType.isNull()) {
11764     VDecl->setInvalidDecl();
11765     return true;
11766   }
11767 
11768   VDecl->setType(DeducedType);
11769   assert(VDecl->isLinkageValid());
11770 
11771   // In ARC, infer lifetime.
11772   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11773     VDecl->setInvalidDecl();
11774 
11775   if (getLangOpts().OpenCL)
11776     deduceOpenCLAddressSpace(VDecl);
11777 
11778   // If this is a redeclaration, check that the type we just deduced matches
11779   // the previously declared type.
11780   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11781     // We never need to merge the type, because we cannot form an incomplete
11782     // array of auto, nor deduce such a type.
11783     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11784   }
11785 
11786   // Check the deduced type is valid for a variable declaration.
11787   CheckVariableDeclarationType(VDecl);
11788   return VDecl->isInvalidDecl();
11789 }
11790 
11791 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11792                                               SourceLocation Loc) {
11793   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11794     Init = EWC->getSubExpr();
11795 
11796   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11797     Init = CE->getSubExpr();
11798 
11799   QualType InitType = Init->getType();
11800   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11801           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11802          "shouldn't be called if type doesn't have a non-trivial C struct");
11803   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11804     for (auto I : ILE->inits()) {
11805       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11806           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11807         continue;
11808       SourceLocation SL = I->getExprLoc();
11809       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11810     }
11811     return;
11812   }
11813 
11814   if (isa<ImplicitValueInitExpr>(Init)) {
11815     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11816       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11817                             NTCUK_Init);
11818   } else {
11819     // Assume all other explicit initializers involving copying some existing
11820     // object.
11821     // TODO: ignore any explicit initializers where we can guarantee
11822     // copy-elision.
11823     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11824       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11825   }
11826 }
11827 
11828 namespace {
11829 
11830 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11831   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11832   // in the source code or implicitly by the compiler if it is in a union
11833   // defined in a system header and has non-trivial ObjC ownership
11834   // qualifications. We don't want those fields to participate in determining
11835   // whether the containing union is non-trivial.
11836   return FD->hasAttr<UnavailableAttr>();
11837 }
11838 
11839 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11840     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11841                                     void> {
11842   using Super =
11843       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11844                                     void>;
11845 
11846   DiagNonTrivalCUnionDefaultInitializeVisitor(
11847       QualType OrigTy, SourceLocation OrigLoc,
11848       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11849       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11850 
11851   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11852                      const FieldDecl *FD, bool InNonTrivialUnion) {
11853     if (const auto *AT = S.Context.getAsArrayType(QT))
11854       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11855                                      InNonTrivialUnion);
11856     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11857   }
11858 
11859   void visitARCStrong(QualType QT, const FieldDecl *FD,
11860                       bool InNonTrivialUnion) {
11861     if (InNonTrivialUnion)
11862       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11863           << 1 << 0 << QT << FD->getName();
11864   }
11865 
11866   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11867     if (InNonTrivialUnion)
11868       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11869           << 1 << 0 << QT << FD->getName();
11870   }
11871 
11872   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11873     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11874     if (RD->isUnion()) {
11875       if (OrigLoc.isValid()) {
11876         bool IsUnion = false;
11877         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11878           IsUnion = OrigRD->isUnion();
11879         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11880             << 0 << OrigTy << IsUnion << UseContext;
11881         // Reset OrigLoc so that this diagnostic is emitted only once.
11882         OrigLoc = SourceLocation();
11883       }
11884       InNonTrivialUnion = true;
11885     }
11886 
11887     if (InNonTrivialUnion)
11888       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11889           << 0 << 0 << QT.getUnqualifiedType() << "";
11890 
11891     for (const FieldDecl *FD : RD->fields())
11892       if (!shouldIgnoreForRecordTriviality(FD))
11893         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11894   }
11895 
11896   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11897 
11898   // The non-trivial C union type or the struct/union type that contains a
11899   // non-trivial C union.
11900   QualType OrigTy;
11901   SourceLocation OrigLoc;
11902   Sema::NonTrivialCUnionContext UseContext;
11903   Sema &S;
11904 };
11905 
11906 struct DiagNonTrivalCUnionDestructedTypeVisitor
11907     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11908   using Super =
11909       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11910 
11911   DiagNonTrivalCUnionDestructedTypeVisitor(
11912       QualType OrigTy, SourceLocation OrigLoc,
11913       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11914       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11915 
11916   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11917                      const FieldDecl *FD, bool InNonTrivialUnion) {
11918     if (const auto *AT = S.Context.getAsArrayType(QT))
11919       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11920                                      InNonTrivialUnion);
11921     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11922   }
11923 
11924   void visitARCStrong(QualType QT, const FieldDecl *FD,
11925                       bool InNonTrivialUnion) {
11926     if (InNonTrivialUnion)
11927       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11928           << 1 << 1 << QT << FD->getName();
11929   }
11930 
11931   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11932     if (InNonTrivialUnion)
11933       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11934           << 1 << 1 << QT << FD->getName();
11935   }
11936 
11937   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11938     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11939     if (RD->isUnion()) {
11940       if (OrigLoc.isValid()) {
11941         bool IsUnion = false;
11942         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11943           IsUnion = OrigRD->isUnion();
11944         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11945             << 1 << OrigTy << IsUnion << UseContext;
11946         // Reset OrigLoc so that this diagnostic is emitted only once.
11947         OrigLoc = SourceLocation();
11948       }
11949       InNonTrivialUnion = true;
11950     }
11951 
11952     if (InNonTrivialUnion)
11953       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11954           << 0 << 1 << QT.getUnqualifiedType() << "";
11955 
11956     for (const FieldDecl *FD : RD->fields())
11957       if (!shouldIgnoreForRecordTriviality(FD))
11958         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11959   }
11960 
11961   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11962   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11963                           bool InNonTrivialUnion) {}
11964 
11965   // The non-trivial C union type or the struct/union type that contains a
11966   // non-trivial C union.
11967   QualType OrigTy;
11968   SourceLocation OrigLoc;
11969   Sema::NonTrivialCUnionContext UseContext;
11970   Sema &S;
11971 };
11972 
11973 struct DiagNonTrivalCUnionCopyVisitor
11974     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11975   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11976 
11977   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11978                                  Sema::NonTrivialCUnionContext UseContext,
11979                                  Sema &S)
11980       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11981 
11982   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11983                      const FieldDecl *FD, bool InNonTrivialUnion) {
11984     if (const auto *AT = S.Context.getAsArrayType(QT))
11985       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11986                                      InNonTrivialUnion);
11987     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11988   }
11989 
11990   void visitARCStrong(QualType QT, const FieldDecl *FD,
11991                       bool InNonTrivialUnion) {
11992     if (InNonTrivialUnion)
11993       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11994           << 1 << 2 << QT << FD->getName();
11995   }
11996 
11997   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11998     if (InNonTrivialUnion)
11999       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12000           << 1 << 2 << QT << FD->getName();
12001   }
12002 
12003   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12004     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12005     if (RD->isUnion()) {
12006       if (OrigLoc.isValid()) {
12007         bool IsUnion = false;
12008         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12009           IsUnion = OrigRD->isUnion();
12010         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12011             << 2 << OrigTy << IsUnion << UseContext;
12012         // Reset OrigLoc so that this diagnostic is emitted only once.
12013         OrigLoc = SourceLocation();
12014       }
12015       InNonTrivialUnion = true;
12016     }
12017 
12018     if (InNonTrivialUnion)
12019       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12020           << 0 << 2 << QT.getUnqualifiedType() << "";
12021 
12022     for (const FieldDecl *FD : RD->fields())
12023       if (!shouldIgnoreForRecordTriviality(FD))
12024         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12025   }
12026 
12027   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12028                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12029   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12030   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12031                             bool InNonTrivialUnion) {}
12032 
12033   // The non-trivial C union type or the struct/union type that contains a
12034   // non-trivial C union.
12035   QualType OrigTy;
12036   SourceLocation OrigLoc;
12037   Sema::NonTrivialCUnionContext UseContext;
12038   Sema &S;
12039 };
12040 
12041 } // namespace
12042 
12043 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12044                                  NonTrivialCUnionContext UseContext,
12045                                  unsigned NonTrivialKind) {
12046   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12047           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12048           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12049          "shouldn't be called if type doesn't have a non-trivial C union");
12050 
12051   if ((NonTrivialKind & NTCUK_Init) &&
12052       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12053     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12054         .visit(QT, nullptr, false);
12055   if ((NonTrivialKind & NTCUK_Destruct) &&
12056       QT.hasNonTrivialToPrimitiveDestructCUnion())
12057     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12058         .visit(QT, nullptr, false);
12059   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12060     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12061         .visit(QT, nullptr, false);
12062 }
12063 
12064 /// AddInitializerToDecl - Adds the initializer Init to the
12065 /// declaration dcl. If DirectInit is true, this is C++ direct
12066 /// initialization rather than copy initialization.
12067 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12068   // If there is no declaration, there was an error parsing it.  Just ignore
12069   // the initializer.
12070   if (!RealDecl || RealDecl->isInvalidDecl()) {
12071     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12072     return;
12073   }
12074 
12075   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12076     // Pure-specifiers are handled in ActOnPureSpecifier.
12077     Diag(Method->getLocation(), diag::err_member_function_initialization)
12078       << Method->getDeclName() << Init->getSourceRange();
12079     Method->setInvalidDecl();
12080     return;
12081   }
12082 
12083   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12084   if (!VDecl) {
12085     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12086     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12087     RealDecl->setInvalidDecl();
12088     return;
12089   }
12090 
12091   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12092   if (VDecl->getType()->isUndeducedType()) {
12093     // Attempt typo correction early so that the type of the init expression can
12094     // be deduced based on the chosen correction if the original init contains a
12095     // TypoExpr.
12096     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12097     if (!Res.isUsable()) {
12098       // There are unresolved typos in Init, just drop them.
12099       // FIXME: improve the recovery strategy to preserve the Init.
12100       RealDecl->setInvalidDecl();
12101       return;
12102     }
12103     if (Res.get()->containsErrors()) {
12104       // Invalidate the decl as we don't know the type for recovery-expr yet.
12105       RealDecl->setInvalidDecl();
12106       VDecl->setInit(Res.get());
12107       return;
12108     }
12109     Init = Res.get();
12110 
12111     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12112       return;
12113   }
12114 
12115   // dllimport cannot be used on variable definitions.
12116   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12117     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12118     VDecl->setInvalidDecl();
12119     return;
12120   }
12121 
12122   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12123     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12124     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12125     VDecl->setInvalidDecl();
12126     return;
12127   }
12128 
12129   if (!VDecl->getType()->isDependentType()) {
12130     // A definition must end up with a complete type, which means it must be
12131     // complete with the restriction that an array type might be completed by
12132     // the initializer; note that later code assumes this restriction.
12133     QualType BaseDeclType = VDecl->getType();
12134     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12135       BaseDeclType = Array->getElementType();
12136     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12137                             diag::err_typecheck_decl_incomplete_type)) {
12138       RealDecl->setInvalidDecl();
12139       return;
12140     }
12141 
12142     // The variable can not have an abstract class type.
12143     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12144                                diag::err_abstract_type_in_decl,
12145                                AbstractVariableType))
12146       VDecl->setInvalidDecl();
12147   }
12148 
12149   // If adding the initializer will turn this declaration into a definition,
12150   // and we already have a definition for this variable, diagnose or otherwise
12151   // handle the situation.
12152   VarDecl *Def;
12153   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12154       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12155       !VDecl->isThisDeclarationADemotedDefinition() &&
12156       checkVarDeclRedefinition(Def, VDecl))
12157     return;
12158 
12159   if (getLangOpts().CPlusPlus) {
12160     // C++ [class.static.data]p4
12161     //   If a static data member is of const integral or const
12162     //   enumeration type, its declaration in the class definition can
12163     //   specify a constant-initializer which shall be an integral
12164     //   constant expression (5.19). In that case, the member can appear
12165     //   in integral constant expressions. The member shall still be
12166     //   defined in a namespace scope if it is used in the program and the
12167     //   namespace scope definition shall not contain an initializer.
12168     //
12169     // We already performed a redefinition check above, but for static
12170     // data members we also need to check whether there was an in-class
12171     // declaration with an initializer.
12172     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12173       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12174           << VDecl->getDeclName();
12175       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12176            diag::note_previous_initializer)
12177           << 0;
12178       return;
12179     }
12180 
12181     if (VDecl->hasLocalStorage())
12182       setFunctionHasBranchProtectedScope();
12183 
12184     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12185       VDecl->setInvalidDecl();
12186       return;
12187     }
12188   }
12189 
12190   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12191   // a kernel function cannot be initialized."
12192   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12193     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12194     VDecl->setInvalidDecl();
12195     return;
12196   }
12197 
12198   // The LoaderUninitialized attribute acts as a definition (of undef).
12199   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12200     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12201     VDecl->setInvalidDecl();
12202     return;
12203   }
12204 
12205   // Get the decls type and save a reference for later, since
12206   // CheckInitializerTypes may change it.
12207   QualType DclT = VDecl->getType(), SavT = DclT;
12208 
12209   // Expressions default to 'id' when we're in a debugger
12210   // and we are assigning it to a variable of Objective-C pointer type.
12211   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12212       Init->getType() == Context.UnknownAnyTy) {
12213     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12214     if (Result.isInvalid()) {
12215       VDecl->setInvalidDecl();
12216       return;
12217     }
12218     Init = Result.get();
12219   }
12220 
12221   // Perform the initialization.
12222   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12223   if (!VDecl->isInvalidDecl()) {
12224     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12225     InitializationKind Kind = InitializationKind::CreateForInit(
12226         VDecl->getLocation(), DirectInit, Init);
12227 
12228     MultiExprArg Args = Init;
12229     if (CXXDirectInit)
12230       Args = MultiExprArg(CXXDirectInit->getExprs(),
12231                           CXXDirectInit->getNumExprs());
12232 
12233     // Try to correct any TypoExprs in the initialization arguments.
12234     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12235       ExprResult Res = CorrectDelayedTyposInExpr(
12236           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12237           [this, Entity, Kind](Expr *E) {
12238             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12239             return Init.Failed() ? ExprError() : E;
12240           });
12241       if (Res.isInvalid()) {
12242         VDecl->setInvalidDecl();
12243       } else if (Res.get() != Args[Idx]) {
12244         Args[Idx] = Res.get();
12245       }
12246     }
12247     if (VDecl->isInvalidDecl())
12248       return;
12249 
12250     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12251                                    /*TopLevelOfInitList=*/false,
12252                                    /*TreatUnavailableAsInvalid=*/false);
12253     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12254     if (Result.isInvalid()) {
12255       // If the provied initializer fails to initialize the var decl,
12256       // we attach a recovery expr for better recovery.
12257       auto RecoveryExpr =
12258           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12259       if (RecoveryExpr.get())
12260         VDecl->setInit(RecoveryExpr.get());
12261       return;
12262     }
12263 
12264     Init = Result.getAs<Expr>();
12265   }
12266 
12267   // Check for self-references within variable initializers.
12268   // Variables declared within a function/method body (except for references)
12269   // are handled by a dataflow analysis.
12270   // This is undefined behavior in C++, but valid in C.
12271   if (getLangOpts().CPlusPlus) {
12272     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12273         VDecl->getType()->isReferenceType()) {
12274       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12275     }
12276   }
12277 
12278   // If the type changed, it means we had an incomplete type that was
12279   // completed by the initializer. For example:
12280   //   int ary[] = { 1, 3, 5 };
12281   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12282   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12283     VDecl->setType(DclT);
12284 
12285   if (!VDecl->isInvalidDecl()) {
12286     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12287 
12288     if (VDecl->hasAttr<BlocksAttr>())
12289       checkRetainCycles(VDecl, Init);
12290 
12291     // It is safe to assign a weak reference into a strong variable.
12292     // Although this code can still have problems:
12293     //   id x = self.weakProp;
12294     //   id y = self.weakProp;
12295     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12296     // paths through the function. This should be revisited if
12297     // -Wrepeated-use-of-weak is made flow-sensitive.
12298     if (FunctionScopeInfo *FSI = getCurFunction())
12299       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12300            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12301           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12302                            Init->getBeginLoc()))
12303         FSI->markSafeWeakUse(Init);
12304   }
12305 
12306   // The initialization is usually a full-expression.
12307   //
12308   // FIXME: If this is a braced initialization of an aggregate, it is not
12309   // an expression, and each individual field initializer is a separate
12310   // full-expression. For instance, in:
12311   //
12312   //   struct Temp { ~Temp(); };
12313   //   struct S { S(Temp); };
12314   //   struct T { S a, b; } t = { Temp(), Temp() }
12315   //
12316   // we should destroy the first Temp before constructing the second.
12317   ExprResult Result =
12318       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12319                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12320   if (Result.isInvalid()) {
12321     VDecl->setInvalidDecl();
12322     return;
12323   }
12324   Init = Result.get();
12325 
12326   // Attach the initializer to the decl.
12327   VDecl->setInit(Init);
12328 
12329   if (VDecl->isLocalVarDecl()) {
12330     // Don't check the initializer if the declaration is malformed.
12331     if (VDecl->isInvalidDecl()) {
12332       // do nothing
12333 
12334     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12335     // This is true even in C++ for OpenCL.
12336     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12337       CheckForConstantInitializer(Init, DclT);
12338 
12339     // Otherwise, C++ does not restrict the initializer.
12340     } else if (getLangOpts().CPlusPlus) {
12341       // do nothing
12342 
12343     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12344     // static storage duration shall be constant expressions or string literals.
12345     } else if (VDecl->getStorageClass() == SC_Static) {
12346       CheckForConstantInitializer(Init, DclT);
12347 
12348     // C89 is stricter than C99 for aggregate initializers.
12349     // C89 6.5.7p3: All the expressions [...] in an initializer list
12350     // for an object that has aggregate or union type shall be
12351     // constant expressions.
12352     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12353                isa<InitListExpr>(Init)) {
12354       const Expr *Culprit;
12355       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12356         Diag(Culprit->getExprLoc(),
12357              diag::ext_aggregate_init_not_constant)
12358           << Culprit->getSourceRange();
12359       }
12360     }
12361 
12362     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12363       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12364         if (VDecl->hasLocalStorage())
12365           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12366   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12367              VDecl->getLexicalDeclContext()->isRecord()) {
12368     // This is an in-class initialization for a static data member, e.g.,
12369     //
12370     // struct S {
12371     //   static const int value = 17;
12372     // };
12373 
12374     // C++ [class.mem]p4:
12375     //   A member-declarator can contain a constant-initializer only
12376     //   if it declares a static member (9.4) of const integral or
12377     //   const enumeration type, see 9.4.2.
12378     //
12379     // C++11 [class.static.data]p3:
12380     //   If a non-volatile non-inline const static data member is of integral
12381     //   or enumeration type, its declaration in the class definition can
12382     //   specify a brace-or-equal-initializer in which every initializer-clause
12383     //   that is an assignment-expression is a constant expression. A static
12384     //   data member of literal type can be declared in the class definition
12385     //   with the constexpr specifier; if so, its declaration shall specify a
12386     //   brace-or-equal-initializer in which every initializer-clause that is
12387     //   an assignment-expression is a constant expression.
12388 
12389     // Do nothing on dependent types.
12390     if (DclT->isDependentType()) {
12391 
12392     // Allow any 'static constexpr' members, whether or not they are of literal
12393     // type. We separately check that every constexpr variable is of literal
12394     // type.
12395     } else if (VDecl->isConstexpr()) {
12396 
12397     // Require constness.
12398     } else if (!DclT.isConstQualified()) {
12399       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12400         << Init->getSourceRange();
12401       VDecl->setInvalidDecl();
12402 
12403     // We allow integer constant expressions in all cases.
12404     } else if (DclT->isIntegralOrEnumerationType()) {
12405       // Check whether the expression is a constant expression.
12406       SourceLocation Loc;
12407       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12408         // In C++11, a non-constexpr const static data member with an
12409         // in-class initializer cannot be volatile.
12410         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12411       else if (Init->isValueDependent())
12412         ; // Nothing to check.
12413       else if (Init->isIntegerConstantExpr(Context, &Loc))
12414         ; // Ok, it's an ICE!
12415       else if (Init->getType()->isScopedEnumeralType() &&
12416                Init->isCXX11ConstantExpr(Context))
12417         ; // Ok, it is a scoped-enum constant expression.
12418       else if (Init->isEvaluatable(Context)) {
12419         // If we can constant fold the initializer through heroics, accept it,
12420         // but report this as a use of an extension for -pedantic.
12421         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12422           << Init->getSourceRange();
12423       } else {
12424         // Otherwise, this is some crazy unknown case.  Report the issue at the
12425         // location provided by the isIntegerConstantExpr failed check.
12426         Diag(Loc, diag::err_in_class_initializer_non_constant)
12427           << Init->getSourceRange();
12428         VDecl->setInvalidDecl();
12429       }
12430 
12431     // We allow foldable floating-point constants as an extension.
12432     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12433       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12434       // it anyway and provide a fixit to add the 'constexpr'.
12435       if (getLangOpts().CPlusPlus11) {
12436         Diag(VDecl->getLocation(),
12437              diag::ext_in_class_initializer_float_type_cxx11)
12438             << DclT << Init->getSourceRange();
12439         Diag(VDecl->getBeginLoc(),
12440              diag::note_in_class_initializer_float_type_cxx11)
12441             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12442       } else {
12443         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12444           << DclT << Init->getSourceRange();
12445 
12446         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12447           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12448             << Init->getSourceRange();
12449           VDecl->setInvalidDecl();
12450         }
12451       }
12452 
12453     // Suggest adding 'constexpr' in C++11 for literal types.
12454     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12455       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12456           << DclT << Init->getSourceRange()
12457           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12458       VDecl->setConstexpr(true);
12459 
12460     } else {
12461       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12462         << DclT << Init->getSourceRange();
12463       VDecl->setInvalidDecl();
12464     }
12465   } else if (VDecl->isFileVarDecl()) {
12466     // In C, extern is typically used to avoid tentative definitions when
12467     // declaring variables in headers, but adding an intializer makes it a
12468     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12469     // In C++, extern is often used to give implictly static const variables
12470     // external linkage, so don't warn in that case. If selectany is present,
12471     // this might be header code intended for C and C++ inclusion, so apply the
12472     // C++ rules.
12473     if (VDecl->getStorageClass() == SC_Extern &&
12474         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12475          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12476         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12477         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12478       Diag(VDecl->getLocation(), diag::warn_extern_init);
12479 
12480     // In Microsoft C++ mode, a const variable defined in namespace scope has
12481     // external linkage by default if the variable is declared with
12482     // __declspec(dllexport).
12483     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12484         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12485         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12486       VDecl->setStorageClass(SC_Extern);
12487 
12488     // C99 6.7.8p4. All file scoped initializers need to be constant.
12489     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12490       CheckForConstantInitializer(Init, DclT);
12491   }
12492 
12493   QualType InitType = Init->getType();
12494   if (!InitType.isNull() &&
12495       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12496        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12497     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12498 
12499   // We will represent direct-initialization similarly to copy-initialization:
12500   //    int x(1);  -as-> int x = 1;
12501   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12502   //
12503   // Clients that want to distinguish between the two forms, can check for
12504   // direct initializer using VarDecl::getInitStyle().
12505   // A major benefit is that clients that don't particularly care about which
12506   // exactly form was it (like the CodeGen) can handle both cases without
12507   // special case code.
12508 
12509   // C++ 8.5p11:
12510   // The form of initialization (using parentheses or '=') is generally
12511   // insignificant, but does matter when the entity being initialized has a
12512   // class type.
12513   if (CXXDirectInit) {
12514     assert(DirectInit && "Call-style initializer must be direct init.");
12515     VDecl->setInitStyle(VarDecl::CallInit);
12516   } else if (DirectInit) {
12517     // This must be list-initialization. No other way is direct-initialization.
12518     VDecl->setInitStyle(VarDecl::ListInit);
12519   }
12520 
12521   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12522     DeclsToCheckForDeferredDiags.push_back(VDecl);
12523   CheckCompleteVariableDeclaration(VDecl);
12524 }
12525 
12526 /// ActOnInitializerError - Given that there was an error parsing an
12527 /// initializer for the given declaration, try to return to some form
12528 /// of sanity.
12529 void Sema::ActOnInitializerError(Decl *D) {
12530   // Our main concern here is re-establishing invariants like "a
12531   // variable's type is either dependent or complete".
12532   if (!D || D->isInvalidDecl()) return;
12533 
12534   VarDecl *VD = dyn_cast<VarDecl>(D);
12535   if (!VD) return;
12536 
12537   // Bindings are not usable if we can't make sense of the initializer.
12538   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12539     for (auto *BD : DD->bindings())
12540       BD->setInvalidDecl();
12541 
12542   // Auto types are meaningless if we can't make sense of the initializer.
12543   if (VD->getType()->isUndeducedType()) {
12544     D->setInvalidDecl();
12545     return;
12546   }
12547 
12548   QualType Ty = VD->getType();
12549   if (Ty->isDependentType()) return;
12550 
12551   // Require a complete type.
12552   if (RequireCompleteType(VD->getLocation(),
12553                           Context.getBaseElementType(Ty),
12554                           diag::err_typecheck_decl_incomplete_type)) {
12555     VD->setInvalidDecl();
12556     return;
12557   }
12558 
12559   // Require a non-abstract type.
12560   if (RequireNonAbstractType(VD->getLocation(), Ty,
12561                              diag::err_abstract_type_in_decl,
12562                              AbstractVariableType)) {
12563     VD->setInvalidDecl();
12564     return;
12565   }
12566 
12567   // Don't bother complaining about constructors or destructors,
12568   // though.
12569 }
12570 
12571 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12572   // If there is no declaration, there was an error parsing it. Just ignore it.
12573   if (!RealDecl)
12574     return;
12575 
12576   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12577     QualType Type = Var->getType();
12578 
12579     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12580     if (isa<DecompositionDecl>(RealDecl)) {
12581       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12582       Var->setInvalidDecl();
12583       return;
12584     }
12585 
12586     if (Type->isUndeducedType() &&
12587         DeduceVariableDeclarationType(Var, false, nullptr))
12588       return;
12589 
12590     // C++11 [class.static.data]p3: A static data member can be declared with
12591     // the constexpr specifier; if so, its declaration shall specify
12592     // a brace-or-equal-initializer.
12593     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12594     // the definition of a variable [...] or the declaration of a static data
12595     // member.
12596     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12597         !Var->isThisDeclarationADemotedDefinition()) {
12598       if (Var->isStaticDataMember()) {
12599         // C++1z removes the relevant rule; the in-class declaration is always
12600         // a definition there.
12601         if (!getLangOpts().CPlusPlus17 &&
12602             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12603           Diag(Var->getLocation(),
12604                diag::err_constexpr_static_mem_var_requires_init)
12605               << Var;
12606           Var->setInvalidDecl();
12607           return;
12608         }
12609       } else {
12610         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12611         Var->setInvalidDecl();
12612         return;
12613       }
12614     }
12615 
12616     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12617     // be initialized.
12618     if (!Var->isInvalidDecl() &&
12619         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12620         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12621       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12622       Var->setInvalidDecl();
12623       return;
12624     }
12625 
12626     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12627       if (Var->getStorageClass() == SC_Extern) {
12628         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12629             << Var;
12630         Var->setInvalidDecl();
12631         return;
12632       }
12633       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12634                               diag::err_typecheck_decl_incomplete_type)) {
12635         Var->setInvalidDecl();
12636         return;
12637       }
12638       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12639         if (!RD->hasTrivialDefaultConstructor()) {
12640           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12641           Var->setInvalidDecl();
12642           return;
12643         }
12644       }
12645       // The declaration is unitialized, no need for further checks.
12646       return;
12647     }
12648 
12649     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12650     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12651         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12652       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12653                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12654 
12655 
12656     switch (DefKind) {
12657     case VarDecl::Definition:
12658       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12659         break;
12660 
12661       // We have an out-of-line definition of a static data member
12662       // that has an in-class initializer, so we type-check this like
12663       // a declaration.
12664       //
12665       LLVM_FALLTHROUGH;
12666 
12667     case VarDecl::DeclarationOnly:
12668       // It's only a declaration.
12669 
12670       // Block scope. C99 6.7p7: If an identifier for an object is
12671       // declared with no linkage (C99 6.2.2p6), the type for the
12672       // object shall be complete.
12673       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12674           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12675           RequireCompleteType(Var->getLocation(), Type,
12676                               diag::err_typecheck_decl_incomplete_type))
12677         Var->setInvalidDecl();
12678 
12679       // Make sure that the type is not abstract.
12680       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12681           RequireNonAbstractType(Var->getLocation(), Type,
12682                                  diag::err_abstract_type_in_decl,
12683                                  AbstractVariableType))
12684         Var->setInvalidDecl();
12685       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12686           Var->getStorageClass() == SC_PrivateExtern) {
12687         Diag(Var->getLocation(), diag::warn_private_extern);
12688         Diag(Var->getLocation(), diag::note_private_extern);
12689       }
12690 
12691       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12692           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12693         ExternalDeclarations.push_back(Var);
12694 
12695       return;
12696 
12697     case VarDecl::TentativeDefinition:
12698       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12699       // object that has file scope without an initializer, and without a
12700       // storage-class specifier or with the storage-class specifier "static",
12701       // constitutes a tentative definition. Note: A tentative definition with
12702       // external linkage is valid (C99 6.2.2p5).
12703       if (!Var->isInvalidDecl()) {
12704         if (const IncompleteArrayType *ArrayT
12705                                     = Context.getAsIncompleteArrayType(Type)) {
12706           if (RequireCompleteSizedType(
12707                   Var->getLocation(), ArrayT->getElementType(),
12708                   diag::err_array_incomplete_or_sizeless_type))
12709             Var->setInvalidDecl();
12710         } else if (Var->getStorageClass() == SC_Static) {
12711           // C99 6.9.2p3: If the declaration of an identifier for an object is
12712           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12713           // declared type shall not be an incomplete type.
12714           // NOTE: code such as the following
12715           //     static struct s;
12716           //     struct s { int a; };
12717           // is accepted by gcc. Hence here we issue a warning instead of
12718           // an error and we do not invalidate the static declaration.
12719           // NOTE: to avoid multiple warnings, only check the first declaration.
12720           if (Var->isFirstDecl())
12721             RequireCompleteType(Var->getLocation(), Type,
12722                                 diag::ext_typecheck_decl_incomplete_type);
12723         }
12724       }
12725 
12726       // Record the tentative definition; we're done.
12727       if (!Var->isInvalidDecl())
12728         TentativeDefinitions.push_back(Var);
12729       return;
12730     }
12731 
12732     // Provide a specific diagnostic for uninitialized variable
12733     // definitions with incomplete array type.
12734     if (Type->isIncompleteArrayType()) {
12735       Diag(Var->getLocation(),
12736            diag::err_typecheck_incomplete_array_needs_initializer);
12737       Var->setInvalidDecl();
12738       return;
12739     }
12740 
12741     // Provide a specific diagnostic for uninitialized variable
12742     // definitions with reference type.
12743     if (Type->isReferenceType()) {
12744       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12745           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12746       Var->setInvalidDecl();
12747       return;
12748     }
12749 
12750     // Do not attempt to type-check the default initializer for a
12751     // variable with dependent type.
12752     if (Type->isDependentType())
12753       return;
12754 
12755     if (Var->isInvalidDecl())
12756       return;
12757 
12758     if (!Var->hasAttr<AliasAttr>()) {
12759       if (RequireCompleteType(Var->getLocation(),
12760                               Context.getBaseElementType(Type),
12761                               diag::err_typecheck_decl_incomplete_type)) {
12762         Var->setInvalidDecl();
12763         return;
12764       }
12765     } else {
12766       return;
12767     }
12768 
12769     // The variable can not have an abstract class type.
12770     if (RequireNonAbstractType(Var->getLocation(), Type,
12771                                diag::err_abstract_type_in_decl,
12772                                AbstractVariableType)) {
12773       Var->setInvalidDecl();
12774       return;
12775     }
12776 
12777     // Check for jumps past the implicit initializer.  C++0x
12778     // clarifies that this applies to a "variable with automatic
12779     // storage duration", not a "local variable".
12780     // C++11 [stmt.dcl]p3
12781     //   A program that jumps from a point where a variable with automatic
12782     //   storage duration is not in scope to a point where it is in scope is
12783     //   ill-formed unless the variable has scalar type, class type with a
12784     //   trivial default constructor and a trivial destructor, a cv-qualified
12785     //   version of one of these types, or an array of one of the preceding
12786     //   types and is declared without an initializer.
12787     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12788       if (const RecordType *Record
12789             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12790         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12791         // Mark the function (if we're in one) for further checking even if the
12792         // looser rules of C++11 do not require such checks, so that we can
12793         // diagnose incompatibilities with C++98.
12794         if (!CXXRecord->isPOD())
12795           setFunctionHasBranchProtectedScope();
12796       }
12797     }
12798     // In OpenCL, we can't initialize objects in the __local address space,
12799     // even implicitly, so don't synthesize an implicit initializer.
12800     if (getLangOpts().OpenCL &&
12801         Var->getType().getAddressSpace() == LangAS::opencl_local)
12802       return;
12803     // C++03 [dcl.init]p9:
12804     //   If no initializer is specified for an object, and the
12805     //   object is of (possibly cv-qualified) non-POD class type (or
12806     //   array thereof), the object shall be default-initialized; if
12807     //   the object is of const-qualified type, the underlying class
12808     //   type shall have a user-declared default
12809     //   constructor. Otherwise, if no initializer is specified for
12810     //   a non- static object, the object and its subobjects, if
12811     //   any, have an indeterminate initial value); if the object
12812     //   or any of its subobjects are of const-qualified type, the
12813     //   program is ill-formed.
12814     // C++0x [dcl.init]p11:
12815     //   If no initializer is specified for an object, the object is
12816     //   default-initialized; [...].
12817     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12818     InitializationKind Kind
12819       = InitializationKind::CreateDefault(Var->getLocation());
12820 
12821     InitializationSequence InitSeq(*this, Entity, Kind, None);
12822     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12823 
12824     if (Init.get()) {
12825       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12826       // This is important for template substitution.
12827       Var->setInitStyle(VarDecl::CallInit);
12828     } else if (Init.isInvalid()) {
12829       // If default-init fails, attach a recovery-expr initializer to track
12830       // that initialization was attempted and failed.
12831       auto RecoveryExpr =
12832           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12833       if (RecoveryExpr.get())
12834         Var->setInit(RecoveryExpr.get());
12835     }
12836 
12837     CheckCompleteVariableDeclaration(Var);
12838   }
12839 }
12840 
12841 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12842   // If there is no declaration, there was an error parsing it. Ignore it.
12843   if (!D)
12844     return;
12845 
12846   VarDecl *VD = dyn_cast<VarDecl>(D);
12847   if (!VD) {
12848     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12849     D->setInvalidDecl();
12850     return;
12851   }
12852 
12853   VD->setCXXForRangeDecl(true);
12854 
12855   // for-range-declaration cannot be given a storage class specifier.
12856   int Error = -1;
12857   switch (VD->getStorageClass()) {
12858   case SC_None:
12859     break;
12860   case SC_Extern:
12861     Error = 0;
12862     break;
12863   case SC_Static:
12864     Error = 1;
12865     break;
12866   case SC_PrivateExtern:
12867     Error = 2;
12868     break;
12869   case SC_Auto:
12870     Error = 3;
12871     break;
12872   case SC_Register:
12873     Error = 4;
12874     break;
12875   }
12876 
12877   // for-range-declaration cannot be given a storage class specifier con't.
12878   switch (VD->getTSCSpec()) {
12879   case TSCS_thread_local:
12880     Error = 6;
12881     break;
12882   case TSCS___thread:
12883   case TSCS__Thread_local:
12884   case TSCS_unspecified:
12885     break;
12886   }
12887 
12888   if (Error != -1) {
12889     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12890         << VD << Error;
12891     D->setInvalidDecl();
12892   }
12893 }
12894 
12895 StmtResult
12896 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12897                                  IdentifierInfo *Ident,
12898                                  ParsedAttributes &Attrs,
12899                                  SourceLocation AttrEnd) {
12900   // C++1y [stmt.iter]p1:
12901   //   A range-based for statement of the form
12902   //      for ( for-range-identifier : for-range-initializer ) statement
12903   //   is equivalent to
12904   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12905   DeclSpec DS(Attrs.getPool().getFactory());
12906 
12907   const char *PrevSpec;
12908   unsigned DiagID;
12909   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12910                      getPrintingPolicy());
12911 
12912   Declarator D(DS, DeclaratorContext::ForInit);
12913   D.SetIdentifier(Ident, IdentLoc);
12914   D.takeAttributes(Attrs, AttrEnd);
12915 
12916   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12917                 IdentLoc);
12918   Decl *Var = ActOnDeclarator(S, D);
12919   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12920   FinalizeDeclaration(Var);
12921   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12922                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12923 }
12924 
12925 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12926   if (var->isInvalidDecl()) return;
12927 
12928   if (getLangOpts().OpenCL) {
12929     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12930     // initialiser
12931     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12932         !var->hasInit()) {
12933       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12934           << 1 /*Init*/;
12935       var->setInvalidDecl();
12936       return;
12937     }
12938   }
12939 
12940   // In Objective-C, don't allow jumps past the implicit initialization of a
12941   // local retaining variable.
12942   if (getLangOpts().ObjC &&
12943       var->hasLocalStorage()) {
12944     switch (var->getType().getObjCLifetime()) {
12945     case Qualifiers::OCL_None:
12946     case Qualifiers::OCL_ExplicitNone:
12947     case Qualifiers::OCL_Autoreleasing:
12948       break;
12949 
12950     case Qualifiers::OCL_Weak:
12951     case Qualifiers::OCL_Strong:
12952       setFunctionHasBranchProtectedScope();
12953       break;
12954     }
12955   }
12956 
12957   if (var->hasLocalStorage() &&
12958       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12959     setFunctionHasBranchProtectedScope();
12960 
12961   // Warn about externally-visible variables being defined without a
12962   // prior declaration.  We only want to do this for global
12963   // declarations, but we also specifically need to avoid doing it for
12964   // class members because the linkage of an anonymous class can
12965   // change if it's later given a typedef name.
12966   if (var->isThisDeclarationADefinition() &&
12967       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12968       var->isExternallyVisible() && var->hasLinkage() &&
12969       !var->isInline() && !var->getDescribedVarTemplate() &&
12970       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12971       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12972       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12973                                   var->getLocation())) {
12974     // Find a previous declaration that's not a definition.
12975     VarDecl *prev = var->getPreviousDecl();
12976     while (prev && prev->isThisDeclarationADefinition())
12977       prev = prev->getPreviousDecl();
12978 
12979     if (!prev) {
12980       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12981       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12982           << /* variable */ 0;
12983     }
12984   }
12985 
12986   // Cache the result of checking for constant initialization.
12987   Optional<bool> CacheHasConstInit;
12988   const Expr *CacheCulprit = nullptr;
12989   auto checkConstInit = [&]() mutable {
12990     if (!CacheHasConstInit)
12991       CacheHasConstInit = var->getInit()->isConstantInitializer(
12992             Context, var->getType()->isReferenceType(), &CacheCulprit);
12993     return *CacheHasConstInit;
12994   };
12995 
12996   if (var->getTLSKind() == VarDecl::TLS_Static) {
12997     if (var->getType().isDestructedType()) {
12998       // GNU C++98 edits for __thread, [basic.start.term]p3:
12999       //   The type of an object with thread storage duration shall not
13000       //   have a non-trivial destructor.
13001       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13002       if (getLangOpts().CPlusPlus11)
13003         Diag(var->getLocation(), diag::note_use_thread_local);
13004     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13005       if (!checkConstInit()) {
13006         // GNU C++98 edits for __thread, [basic.start.init]p4:
13007         //   An object of thread storage duration shall not require dynamic
13008         //   initialization.
13009         // FIXME: Need strict checking here.
13010         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13011           << CacheCulprit->getSourceRange();
13012         if (getLangOpts().CPlusPlus11)
13013           Diag(var->getLocation(), diag::note_use_thread_local);
13014       }
13015     }
13016   }
13017 
13018   // Apply section attributes and pragmas to global variables.
13019   bool GlobalStorage = var->hasGlobalStorage();
13020   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13021       !inTemplateInstantiation()) {
13022     PragmaStack<StringLiteral *> *Stack = nullptr;
13023     int SectionFlags = ASTContext::PSF_Read;
13024     if (var->getType().isConstQualified())
13025       Stack = &ConstSegStack;
13026     else if (!var->getInit()) {
13027       Stack = &BSSSegStack;
13028       SectionFlags |= ASTContext::PSF_Write;
13029     } else {
13030       Stack = &DataSegStack;
13031       SectionFlags |= ASTContext::PSF_Write;
13032     }
13033     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13034       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13035         SectionFlags |= ASTContext::PSF_Implicit;
13036       UnifySection(SA->getName(), SectionFlags, var);
13037     } else if (Stack->CurrentValue) {
13038       SectionFlags |= ASTContext::PSF_Implicit;
13039       auto SectionName = Stack->CurrentValue->getString();
13040       var->addAttr(SectionAttr::CreateImplicit(
13041           Context, SectionName, Stack->CurrentPragmaLocation,
13042           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13043       if (UnifySection(SectionName, SectionFlags, var))
13044         var->dropAttr<SectionAttr>();
13045     }
13046 
13047     // Apply the init_seg attribute if this has an initializer.  If the
13048     // initializer turns out to not be dynamic, we'll end up ignoring this
13049     // attribute.
13050     if (CurInitSeg && var->getInit())
13051       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13052                                                CurInitSegLoc,
13053                                                AttributeCommonInfo::AS_Pragma));
13054   }
13055 
13056   if (!var->getType()->isStructureType() && var->hasInit() &&
13057       isa<InitListExpr>(var->getInit())) {
13058     const auto *ILE = cast<InitListExpr>(var->getInit());
13059     unsigned NumInits = ILE->getNumInits();
13060     if (NumInits > 2)
13061       for (unsigned I = 0; I < NumInits; ++I) {
13062         const auto *Init = ILE->getInit(I);
13063         if (!Init)
13064           break;
13065         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13066         if (!SL)
13067           break;
13068 
13069         unsigned NumConcat = SL->getNumConcatenated();
13070         // Diagnose missing comma in string array initialization.
13071         // Do not warn when all the elements in the initializer are concatenated
13072         // together. Do not warn for macros too.
13073         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13074           bool OnlyOneMissingComma = true;
13075           for (unsigned J = I + 1; J < NumInits; ++J) {
13076             const auto *Init = ILE->getInit(J);
13077             if (!Init)
13078               break;
13079             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13080             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13081               OnlyOneMissingComma = false;
13082               break;
13083             }
13084           }
13085 
13086           if (OnlyOneMissingComma) {
13087             SmallVector<FixItHint, 1> Hints;
13088             for (unsigned i = 0; i < NumConcat - 1; ++i)
13089               Hints.push_back(FixItHint::CreateInsertion(
13090                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13091 
13092             Diag(SL->getStrTokenLoc(1),
13093                  diag::warn_concatenated_literal_array_init)
13094                 << Hints;
13095             Diag(SL->getBeginLoc(),
13096                  diag::note_concatenated_string_literal_silence);
13097           }
13098           // In any case, stop now.
13099           break;
13100         }
13101       }
13102   }
13103 
13104   // All the following checks are C++ only.
13105   if (!getLangOpts().CPlusPlus) {
13106     // If this variable must be emitted, add it as an initializer for the
13107     // current module.
13108     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13109       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13110     return;
13111   }
13112 
13113   QualType type = var->getType();
13114 
13115   if (var->hasAttr<BlocksAttr>())
13116     getCurFunction()->addByrefBlockVar(var);
13117 
13118   Expr *Init = var->getInit();
13119   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13120   QualType baseType = Context.getBaseElementType(type);
13121 
13122   // Check whether the initializer is sufficiently constant.
13123   if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13124       (GlobalStorage || var->isConstexpr() ||
13125        var->mightBeUsableInConstantExpressions(Context))) {
13126     // If this variable might have a constant initializer or might be usable in
13127     // constant expressions, check whether or not it actually is now.  We can't
13128     // do this lazily, because the result might depend on things that change
13129     // later, such as which constexpr functions happen to be defined.
13130     SmallVector<PartialDiagnosticAt, 8> Notes;
13131     bool HasConstInit;
13132     if (!getLangOpts().CPlusPlus11) {
13133       // Prior to C++11, in contexts where a constant initializer is required,
13134       // the set of valid constant initializers is described by syntactic rules
13135       // in [expr.const]p2-6.
13136       // FIXME: Stricter checking for these rules would be useful for constinit /
13137       // -Wglobal-constructors.
13138       HasConstInit = checkConstInit();
13139 
13140       // Compute and cache the constant value, and remember that we have a
13141       // constant initializer.
13142       if (HasConstInit) {
13143         (void)var->checkForConstantInitialization(Notes);
13144         Notes.clear();
13145       } else if (CacheCulprit) {
13146         Notes.emplace_back(CacheCulprit->getExprLoc(),
13147                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13148         Notes.back().second << CacheCulprit->getSourceRange();
13149       }
13150     } else {
13151       // Evaluate the initializer to see if it's a constant initializer.
13152       HasConstInit = var->checkForConstantInitialization(Notes);
13153     }
13154 
13155     if (HasConstInit) {
13156       // FIXME: Consider replacing the initializer with a ConstantExpr.
13157     } else if (var->isConstexpr()) {
13158       SourceLocation DiagLoc = var->getLocation();
13159       // If the note doesn't add any useful information other than a source
13160       // location, fold it into the primary diagnostic.
13161       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13162                                    diag::note_invalid_subexpr_in_const_expr) {
13163         DiagLoc = Notes[0].first;
13164         Notes.clear();
13165       }
13166       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13167           << var << Init->getSourceRange();
13168       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13169         Diag(Notes[I].first, Notes[I].second);
13170     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13171       auto *Attr = var->getAttr<ConstInitAttr>();
13172       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13173           << Init->getSourceRange();
13174       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13175           << Attr->getRange() << Attr->isConstinit();
13176       for (auto &it : Notes)
13177         Diag(it.first, it.second);
13178     } else if (IsGlobal &&
13179                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13180                                            var->getLocation())) {
13181       // Warn about globals which don't have a constant initializer.  Don't
13182       // warn about globals with a non-trivial destructor because we already
13183       // warned about them.
13184       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13185       if (!(RD && !RD->hasTrivialDestructor())) {
13186         // checkConstInit() here permits trivial default initialization even in
13187         // C++11 onwards, where such an initializer is not a constant initializer
13188         // but nonetheless doesn't require a global constructor.
13189         if (!checkConstInit())
13190           Diag(var->getLocation(), diag::warn_global_constructor)
13191               << Init->getSourceRange();
13192       }
13193     }
13194   }
13195 
13196   // Require the destructor.
13197   if (!type->isDependentType())
13198     if (const RecordType *recordType = baseType->getAs<RecordType>())
13199       FinalizeVarWithDestructor(var, recordType);
13200 
13201   // If this variable must be emitted, add it as an initializer for the current
13202   // module.
13203   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13204     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13205 
13206   // Build the bindings if this is a structured binding declaration.
13207   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13208     CheckCompleteDecompositionDeclaration(DD);
13209 }
13210 
13211 /// Determines if a variable's alignment is dependent.
13212 static bool hasDependentAlignment(VarDecl *VD) {
13213   if (VD->getType()->isDependentType())
13214     return true;
13215   for (auto *I : VD->specific_attrs<AlignedAttr>())
13216     if (I->isAlignmentDependent())
13217       return true;
13218   return false;
13219 }
13220 
13221 /// Check if VD needs to be dllexport/dllimport due to being in a
13222 /// dllexport/import function.
13223 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13224   assert(VD->isStaticLocal());
13225 
13226   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13227 
13228   // Find outermost function when VD is in lambda function.
13229   while (FD && !getDLLAttr(FD) &&
13230          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13231          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13232     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13233   }
13234 
13235   if (!FD)
13236     return;
13237 
13238   // Static locals inherit dll attributes from their function.
13239   if (Attr *A = getDLLAttr(FD)) {
13240     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13241     NewAttr->setInherited(true);
13242     VD->addAttr(NewAttr);
13243   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13244     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13245     NewAttr->setInherited(true);
13246     VD->addAttr(NewAttr);
13247 
13248     // Export this function to enforce exporting this static variable even
13249     // if it is not used in this compilation unit.
13250     if (!FD->hasAttr<DLLExportAttr>())
13251       FD->addAttr(NewAttr);
13252 
13253   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13254     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13255     NewAttr->setInherited(true);
13256     VD->addAttr(NewAttr);
13257   }
13258 }
13259 
13260 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13261 /// any semantic actions necessary after any initializer has been attached.
13262 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13263   // Note that we are no longer parsing the initializer for this declaration.
13264   ParsingInitForAutoVars.erase(ThisDecl);
13265 
13266   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13267   if (!VD)
13268     return;
13269 
13270   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13271   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13272       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13273     if (PragmaClangBSSSection.Valid)
13274       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13275           Context, PragmaClangBSSSection.SectionName,
13276           PragmaClangBSSSection.PragmaLocation,
13277           AttributeCommonInfo::AS_Pragma));
13278     if (PragmaClangDataSection.Valid)
13279       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13280           Context, PragmaClangDataSection.SectionName,
13281           PragmaClangDataSection.PragmaLocation,
13282           AttributeCommonInfo::AS_Pragma));
13283     if (PragmaClangRodataSection.Valid)
13284       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13285           Context, PragmaClangRodataSection.SectionName,
13286           PragmaClangRodataSection.PragmaLocation,
13287           AttributeCommonInfo::AS_Pragma));
13288     if (PragmaClangRelroSection.Valid)
13289       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13290           Context, PragmaClangRelroSection.SectionName,
13291           PragmaClangRelroSection.PragmaLocation,
13292           AttributeCommonInfo::AS_Pragma));
13293   }
13294 
13295   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13296     for (auto *BD : DD->bindings()) {
13297       FinalizeDeclaration(BD);
13298     }
13299   }
13300 
13301   checkAttributesAfterMerging(*this, *VD);
13302 
13303   // Perform TLS alignment check here after attributes attached to the variable
13304   // which may affect the alignment have been processed. Only perform the check
13305   // if the target has a maximum TLS alignment (zero means no constraints).
13306   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13307     // Protect the check so that it's not performed on dependent types and
13308     // dependent alignments (we can't determine the alignment in that case).
13309     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13310         !VD->isInvalidDecl()) {
13311       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13312       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13313         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13314           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13315           << (unsigned)MaxAlignChars.getQuantity();
13316       }
13317     }
13318   }
13319 
13320   if (VD->isStaticLocal())
13321     CheckStaticLocalForDllExport(VD);
13322 
13323   // Perform check for initializers of device-side global variables.
13324   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13325   // 7.5). We must also apply the same checks to all __shared__
13326   // variables whether they are local or not. CUDA also allows
13327   // constant initializers for __constant__ and __device__ variables.
13328   if (getLangOpts().CUDA)
13329     checkAllowedCUDAInitializer(VD);
13330 
13331   // Grab the dllimport or dllexport attribute off of the VarDecl.
13332   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13333 
13334   // Imported static data members cannot be defined out-of-line.
13335   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13336     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13337         VD->isThisDeclarationADefinition()) {
13338       // We allow definitions of dllimport class template static data members
13339       // with a warning.
13340       CXXRecordDecl *Context =
13341         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13342       bool IsClassTemplateMember =
13343           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13344           Context->getDescribedClassTemplate();
13345 
13346       Diag(VD->getLocation(),
13347            IsClassTemplateMember
13348                ? diag::warn_attribute_dllimport_static_field_definition
13349                : diag::err_attribute_dllimport_static_field_definition);
13350       Diag(IA->getLocation(), diag::note_attribute);
13351       if (!IsClassTemplateMember)
13352         VD->setInvalidDecl();
13353     }
13354   }
13355 
13356   // dllimport/dllexport variables cannot be thread local, their TLS index
13357   // isn't exported with the variable.
13358   if (DLLAttr && VD->getTLSKind()) {
13359     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13360     if (F && getDLLAttr(F)) {
13361       assert(VD->isStaticLocal());
13362       // But if this is a static local in a dlimport/dllexport function, the
13363       // function will never be inlined, which means the var would never be
13364       // imported, so having it marked import/export is safe.
13365     } else {
13366       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13367                                                                     << DLLAttr;
13368       VD->setInvalidDecl();
13369     }
13370   }
13371 
13372   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13373     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13374       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13375           << Attr;
13376       VD->dropAttr<UsedAttr>();
13377     }
13378   }
13379   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13380     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13381       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13382           << Attr;
13383       VD->dropAttr<RetainAttr>();
13384     }
13385   }
13386 
13387   const DeclContext *DC = VD->getDeclContext();
13388   // If there's a #pragma GCC visibility in scope, and this isn't a class
13389   // member, set the visibility of this variable.
13390   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13391     AddPushedVisibilityAttribute(VD);
13392 
13393   // FIXME: Warn on unused var template partial specializations.
13394   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13395     MarkUnusedFileScopedDecl(VD);
13396 
13397   // Now we have parsed the initializer and can update the table of magic
13398   // tag values.
13399   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13400       !VD->getType()->isIntegralOrEnumerationType())
13401     return;
13402 
13403   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13404     const Expr *MagicValueExpr = VD->getInit();
13405     if (!MagicValueExpr) {
13406       continue;
13407     }
13408     Optional<llvm::APSInt> MagicValueInt;
13409     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13410       Diag(I->getRange().getBegin(),
13411            diag::err_type_tag_for_datatype_not_ice)
13412         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13413       continue;
13414     }
13415     if (MagicValueInt->getActiveBits() > 64) {
13416       Diag(I->getRange().getBegin(),
13417            diag::err_type_tag_for_datatype_too_large)
13418         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13419       continue;
13420     }
13421     uint64_t MagicValue = MagicValueInt->getZExtValue();
13422     RegisterTypeTagForDatatype(I->getArgumentKind(),
13423                                MagicValue,
13424                                I->getMatchingCType(),
13425                                I->getLayoutCompatible(),
13426                                I->getMustBeNull());
13427   }
13428 }
13429 
13430 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13431   auto *VD = dyn_cast<VarDecl>(DD);
13432   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13433 }
13434 
13435 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13436                                                    ArrayRef<Decl *> Group) {
13437   SmallVector<Decl*, 8> Decls;
13438 
13439   if (DS.isTypeSpecOwned())
13440     Decls.push_back(DS.getRepAsDecl());
13441 
13442   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13443   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13444   bool DiagnosedMultipleDecomps = false;
13445   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13446   bool DiagnosedNonDeducedAuto = false;
13447 
13448   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13449     if (Decl *D = Group[i]) {
13450       // For declarators, there are some additional syntactic-ish checks we need
13451       // to perform.
13452       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13453         if (!FirstDeclaratorInGroup)
13454           FirstDeclaratorInGroup = DD;
13455         if (!FirstDecompDeclaratorInGroup)
13456           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13457         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13458             !hasDeducedAuto(DD))
13459           FirstNonDeducedAutoInGroup = DD;
13460 
13461         if (FirstDeclaratorInGroup != DD) {
13462           // A decomposition declaration cannot be combined with any other
13463           // declaration in the same group.
13464           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13465             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13466                  diag::err_decomp_decl_not_alone)
13467                 << FirstDeclaratorInGroup->getSourceRange()
13468                 << DD->getSourceRange();
13469             DiagnosedMultipleDecomps = true;
13470           }
13471 
13472           // A declarator that uses 'auto' in any way other than to declare a
13473           // variable with a deduced type cannot be combined with any other
13474           // declarator in the same group.
13475           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13476             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13477                  diag::err_auto_non_deduced_not_alone)
13478                 << FirstNonDeducedAutoInGroup->getType()
13479                        ->hasAutoForTrailingReturnType()
13480                 << FirstDeclaratorInGroup->getSourceRange()
13481                 << DD->getSourceRange();
13482             DiagnosedNonDeducedAuto = true;
13483           }
13484         }
13485       }
13486 
13487       Decls.push_back(D);
13488     }
13489   }
13490 
13491   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13492     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13493       handleTagNumbering(Tag, S);
13494       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13495           getLangOpts().CPlusPlus)
13496         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13497     }
13498   }
13499 
13500   return BuildDeclaratorGroup(Decls);
13501 }
13502 
13503 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13504 /// group, performing any necessary semantic checking.
13505 Sema::DeclGroupPtrTy
13506 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13507   // C++14 [dcl.spec.auto]p7: (DR1347)
13508   //   If the type that replaces the placeholder type is not the same in each
13509   //   deduction, the program is ill-formed.
13510   if (Group.size() > 1) {
13511     QualType Deduced;
13512     VarDecl *DeducedDecl = nullptr;
13513     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13514       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13515       if (!D || D->isInvalidDecl())
13516         break;
13517       DeducedType *DT = D->getType()->getContainedDeducedType();
13518       if (!DT || DT->getDeducedType().isNull())
13519         continue;
13520       if (Deduced.isNull()) {
13521         Deduced = DT->getDeducedType();
13522         DeducedDecl = D;
13523       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13524         auto *AT = dyn_cast<AutoType>(DT);
13525         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13526                         diag::err_auto_different_deductions)
13527                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13528                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13529                    << D->getDeclName();
13530         if (DeducedDecl->hasInit())
13531           Dia << DeducedDecl->getInit()->getSourceRange();
13532         if (D->getInit())
13533           Dia << D->getInit()->getSourceRange();
13534         D->setInvalidDecl();
13535         break;
13536       }
13537     }
13538   }
13539 
13540   ActOnDocumentableDecls(Group);
13541 
13542   return DeclGroupPtrTy::make(
13543       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13544 }
13545 
13546 void Sema::ActOnDocumentableDecl(Decl *D) {
13547   ActOnDocumentableDecls(D);
13548 }
13549 
13550 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13551   // Don't parse the comment if Doxygen diagnostics are ignored.
13552   if (Group.empty() || !Group[0])
13553     return;
13554 
13555   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13556                       Group[0]->getLocation()) &&
13557       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13558                       Group[0]->getLocation()))
13559     return;
13560 
13561   if (Group.size() >= 2) {
13562     // This is a decl group.  Normally it will contain only declarations
13563     // produced from declarator list.  But in case we have any definitions or
13564     // additional declaration references:
13565     //   'typedef struct S {} S;'
13566     //   'typedef struct S *S;'
13567     //   'struct S *pS;'
13568     // FinalizeDeclaratorGroup adds these as separate declarations.
13569     Decl *MaybeTagDecl = Group[0];
13570     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13571       Group = Group.slice(1);
13572     }
13573   }
13574 
13575   // FIMXE: We assume every Decl in the group is in the same file.
13576   // This is false when preprocessor constructs the group from decls in
13577   // different files (e. g. macros or #include).
13578   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13579 }
13580 
13581 /// Common checks for a parameter-declaration that should apply to both function
13582 /// parameters and non-type template parameters.
13583 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13584   // Check that there are no default arguments inside the type of this
13585   // parameter.
13586   if (getLangOpts().CPlusPlus)
13587     CheckExtraCXXDefaultArguments(D);
13588 
13589   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13590   if (D.getCXXScopeSpec().isSet()) {
13591     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13592       << D.getCXXScopeSpec().getRange();
13593   }
13594 
13595   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13596   // simple identifier except [...irrelevant cases...].
13597   switch (D.getName().getKind()) {
13598   case UnqualifiedIdKind::IK_Identifier:
13599     break;
13600 
13601   case UnqualifiedIdKind::IK_OperatorFunctionId:
13602   case UnqualifiedIdKind::IK_ConversionFunctionId:
13603   case UnqualifiedIdKind::IK_LiteralOperatorId:
13604   case UnqualifiedIdKind::IK_ConstructorName:
13605   case UnqualifiedIdKind::IK_DestructorName:
13606   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13607   case UnqualifiedIdKind::IK_DeductionGuideName:
13608     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13609       << GetNameForDeclarator(D).getName();
13610     break;
13611 
13612   case UnqualifiedIdKind::IK_TemplateId:
13613   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13614     // GetNameForDeclarator would not produce a useful name in this case.
13615     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13616     break;
13617   }
13618 }
13619 
13620 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13621 /// to introduce parameters into function prototype scope.
13622 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13623   const DeclSpec &DS = D.getDeclSpec();
13624 
13625   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13626 
13627   // C++03 [dcl.stc]p2 also permits 'auto'.
13628   StorageClass SC = SC_None;
13629   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13630     SC = SC_Register;
13631     // In C++11, the 'register' storage class specifier is deprecated.
13632     // In C++17, it is not allowed, but we tolerate it as an extension.
13633     if (getLangOpts().CPlusPlus11) {
13634       Diag(DS.getStorageClassSpecLoc(),
13635            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13636                                      : diag::warn_deprecated_register)
13637         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13638     }
13639   } else if (getLangOpts().CPlusPlus &&
13640              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13641     SC = SC_Auto;
13642   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13643     Diag(DS.getStorageClassSpecLoc(),
13644          diag::err_invalid_storage_class_in_func_decl);
13645     D.getMutableDeclSpec().ClearStorageClassSpecs();
13646   }
13647 
13648   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13649     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13650       << DeclSpec::getSpecifierName(TSCS);
13651   if (DS.isInlineSpecified())
13652     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13653         << getLangOpts().CPlusPlus17;
13654   if (DS.hasConstexprSpecifier())
13655     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13656         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13657 
13658   DiagnoseFunctionSpecifiers(DS);
13659 
13660   CheckFunctionOrTemplateParamDeclarator(S, D);
13661 
13662   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13663   QualType parmDeclType = TInfo->getType();
13664 
13665   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13666   IdentifierInfo *II = D.getIdentifier();
13667   if (II) {
13668     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13669                    ForVisibleRedeclaration);
13670     LookupName(R, S);
13671     if (R.isSingleResult()) {
13672       NamedDecl *PrevDecl = R.getFoundDecl();
13673       if (PrevDecl->isTemplateParameter()) {
13674         // Maybe we will complain about the shadowed template parameter.
13675         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13676         // Just pretend that we didn't see the previous declaration.
13677         PrevDecl = nullptr;
13678       } else if (S->isDeclScope(PrevDecl)) {
13679         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13680         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13681 
13682         // Recover by removing the name
13683         II = nullptr;
13684         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13685         D.setInvalidType(true);
13686       }
13687     }
13688   }
13689 
13690   // Temporarily put parameter variables in the translation unit, not
13691   // the enclosing context.  This prevents them from accidentally
13692   // looking like class members in C++.
13693   ParmVarDecl *New =
13694       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13695                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13696 
13697   if (D.isInvalidType())
13698     New->setInvalidDecl();
13699 
13700   assert(S->isFunctionPrototypeScope());
13701   assert(S->getFunctionPrototypeDepth() >= 1);
13702   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13703                     S->getNextFunctionPrototypeIndex());
13704 
13705   // Add the parameter declaration into this scope.
13706   S->AddDecl(New);
13707   if (II)
13708     IdResolver.AddDecl(New);
13709 
13710   ProcessDeclAttributes(S, New, D);
13711 
13712   if (D.getDeclSpec().isModulePrivateSpecified())
13713     Diag(New->getLocation(), diag::err_module_private_local)
13714         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13715         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13716 
13717   if (New->hasAttr<BlocksAttr>()) {
13718     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13719   }
13720 
13721   if (getLangOpts().OpenCL)
13722     deduceOpenCLAddressSpace(New);
13723 
13724   return New;
13725 }
13726 
13727 /// Synthesizes a variable for a parameter arising from a
13728 /// typedef.
13729 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13730                                               SourceLocation Loc,
13731                                               QualType T) {
13732   /* FIXME: setting StartLoc == Loc.
13733      Would it be worth to modify callers so as to provide proper source
13734      location for the unnamed parameters, embedding the parameter's type? */
13735   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13736                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13737                                            SC_None, nullptr);
13738   Param->setImplicit();
13739   return Param;
13740 }
13741 
13742 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13743   // Don't diagnose unused-parameter errors in template instantiations; we
13744   // will already have done so in the template itself.
13745   if (inTemplateInstantiation())
13746     return;
13747 
13748   for (const ParmVarDecl *Parameter : Parameters) {
13749     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13750         !Parameter->hasAttr<UnusedAttr>()) {
13751       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13752         << Parameter->getDeclName();
13753     }
13754   }
13755 }
13756 
13757 using AllUsesSetsPtrSet = llvm::SmallPtrSet<const NamedDecl *, 16>;
13758 
13759 namespace {
13760 
13761 struct AllUsesAreSetsVisitor : RecursiveASTVisitor<AllUsesAreSetsVisitor> {
13762   AllUsesSetsPtrSet &S;
13763 
13764   AllUsesAreSetsVisitor(AllUsesSetsPtrSet &Set) : S(Set) {}
13765 
13766   bool TraverseBinaryOperator(const BinaryOperator *BO) {
13767     auto *LHS = BO->getLHS();
13768     auto *DRE = dyn_cast<DeclRefExpr>(LHS);
13769     if (!BO->isAssignmentOp() || !DRE || !S.count(DRE->getFoundDecl())) {
13770       // This is not an assignment to one of our NamedDecls.
13771       if (!TraverseStmt(LHS))
13772         return false;
13773     }
13774     return TraverseStmt(BO->getRHS());
13775   }
13776 
13777   bool VisitDeclRefExpr(const DeclRefExpr *DRE) {
13778     // If we remove all Decls, no need to keep searching.
13779     return !S.erase(DRE->getFoundDecl()) || S.size();
13780   }
13781 
13782   bool OverloadedTraverse(Stmt *S) { return TraverseStmt(S); }
13783 
13784   bool OverloadedTraverse(Decl *D) { return TraverseDecl(D); }
13785 };
13786 
13787 } // end anonymous namespace
13788 
13789 /// For any NamedDecl in Decls that is not used in any way other than the LHS of
13790 /// an assignment, diagnose with the given DiagId.
13791 template <typename R, typename T>
13792 static void DiagnoseUnusedButSetDecls(Sema *Se, T *Parent, R Decls,
13793                                       unsigned DiagID) {
13794   // Put the Decls in a set so we only have to traverse the body once for all of
13795   // them.
13796   AllUsesSetsPtrSet AllUsesAreSets;
13797 
13798   for (const NamedDecl *ND : Decls) {
13799     AllUsesAreSets.insert(ND);
13800   }
13801 
13802   if (!AllUsesAreSets.size())
13803     return;
13804 
13805   AllUsesAreSetsVisitor Visitor(AllUsesAreSets);
13806   Visitor.OverloadedTraverse(Parent);
13807 
13808   for (const NamedDecl *ND : AllUsesAreSets) {
13809     Se->Diag(ND->getLocation(), DiagID) << ND->getDeclName();
13810   }
13811 }
13812 
13813 void Sema::DiagnoseUnusedButSetParameters(ArrayRef<ParmVarDecl *> Parameters) {
13814   // Don't diagnose unused-but-set-parameter errors in template instantiations;
13815   // we will already have done so in the template itself.
13816   if (inTemplateInstantiation())
13817     return;
13818 
13819   bool CPlusPlus = getLangOpts().CPlusPlus;
13820 
13821   auto IsCandidate = [&](const ParmVarDecl *P) {
13822     // Check for Ignored here, because if we have no candidates we can avoid
13823     // walking the AST.
13824     if (Diags.getDiagnosticLevel(diag::warn_unused_but_set_parameter,
13825                                  P->getLocation()) ==
13826         DiagnosticsEngine::Ignored)
13827       return false;
13828     if (!P->isReferenced() || !P->getDeclName() || P->hasAttr<UnusedAttr>())
13829       return false;
13830     // Mimic gcc's behavior regarding nonscalar types.
13831     if (CPlusPlus && !P->getType()->isScalarType())
13832       return false;
13833     return true;
13834   };
13835 
13836   auto Candidates = llvm::make_filter_range(Parameters, IsCandidate);
13837 
13838   if (Parameters.empty())
13839     return;
13840 
13841   // Traverse the Decl, not just the body; otherwise we'd miss things like
13842   // CXXCtorInitializer.
13843   if (Decl *D =
13844           Decl::castFromDeclContext((*Parameters.begin())->getDeclContext()))
13845     DiagnoseUnusedButSetDecls(this, D, Candidates,
13846                               diag::warn_unused_but_set_parameter);
13847 }
13848 
13849 void Sema::DiagnoseUnusedButSetVariables(CompoundStmt *CS) {
13850   bool CPlusPlus = getLangOpts().CPlusPlus;
13851 
13852   auto IsCandidate = [&](const Stmt *S) {
13853     const DeclStmt *SD = dyn_cast<DeclStmt>(S);
13854     if (!SD || !SD->isSingleDecl())
13855       return false;
13856     const VarDecl *VD = dyn_cast<VarDecl>(SD->getSingleDecl());
13857     // Check for Ignored here, because if we have no candidates we can avoid
13858     // walking the AST.
13859     if (!VD || Diags.getDiagnosticLevel(diag::warn_unused_but_set_variable,
13860                                         VD->getLocation()) ==
13861                    DiagnosticsEngine::Ignored)
13862       return false;
13863     if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
13864       return false;
13865     // Declarations which are const or constexpr can't be assigned to after
13866     // initialization anyway, and avoiding these cases will prevent false
13867     // positives when uses of a constexpr don't appear in the AST.
13868     if (VD->isConstexpr() || VD->getType().isConstQualified())
13869       return false;
13870     // Mimic gcc's behavior regarding nonscalar types.
13871     if (CPlusPlus && !VD->getType()->isScalarType())
13872       return false;
13873     return true;
13874   };
13875 
13876   auto Candidates = llvm::make_filter_range(CS->body(), IsCandidate);
13877 
13878   auto ToNamedDecl = [](const Stmt *S) {
13879     const DeclStmt *SD = dyn_cast<const DeclStmt>(S);
13880     return dyn_cast<const NamedDecl>(SD->getSingleDecl());
13881   };
13882 
13883   auto CandidateDecls = llvm::map_range(Candidates, ToNamedDecl);
13884 
13885   DiagnoseUnusedButSetDecls(this, CS, CandidateDecls,
13886                             diag::warn_unused_but_set_variable);
13887 }
13888 
13889 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13890     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13891   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13892     return;
13893 
13894   // Warn if the return value is pass-by-value and larger than the specified
13895   // threshold.
13896   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13897     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13898     if (Size > LangOpts.NumLargeByValueCopy)
13899       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13900   }
13901 
13902   // Warn if any parameter is pass-by-value and larger than the specified
13903   // threshold.
13904   for (const ParmVarDecl *Parameter : Parameters) {
13905     QualType T = Parameter->getType();
13906     if (T->isDependentType() || !T.isPODType(Context))
13907       continue;
13908     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13909     if (Size > LangOpts.NumLargeByValueCopy)
13910       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13911           << Parameter << Size;
13912   }
13913 }
13914 
13915 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13916                                   SourceLocation NameLoc, IdentifierInfo *Name,
13917                                   QualType T, TypeSourceInfo *TSInfo,
13918                                   StorageClass SC) {
13919   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13920   if (getLangOpts().ObjCAutoRefCount &&
13921       T.getObjCLifetime() == Qualifiers::OCL_None &&
13922       T->isObjCLifetimeType()) {
13923 
13924     Qualifiers::ObjCLifetime lifetime;
13925 
13926     // Special cases for arrays:
13927     //   - if it's const, use __unsafe_unretained
13928     //   - otherwise, it's an error
13929     if (T->isArrayType()) {
13930       if (!T.isConstQualified()) {
13931         if (DelayedDiagnostics.shouldDelayDiagnostics())
13932           DelayedDiagnostics.add(
13933               sema::DelayedDiagnostic::makeForbiddenType(
13934               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13935         else
13936           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13937               << TSInfo->getTypeLoc().getSourceRange();
13938       }
13939       lifetime = Qualifiers::OCL_ExplicitNone;
13940     } else {
13941       lifetime = T->getObjCARCImplicitLifetime();
13942     }
13943     T = Context.getLifetimeQualifiedType(T, lifetime);
13944   }
13945 
13946   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13947                                          Context.getAdjustedParameterType(T),
13948                                          TSInfo, SC, nullptr);
13949 
13950   // Make a note if we created a new pack in the scope of a lambda, so that
13951   // we know that references to that pack must also be expanded within the
13952   // lambda scope.
13953   if (New->isParameterPack())
13954     if (auto *LSI = getEnclosingLambda())
13955       LSI->LocalPacks.push_back(New);
13956 
13957   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13958       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13959     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13960                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13961 
13962   // Parameters can not be abstract class types.
13963   // For record types, this is done by the AbstractClassUsageDiagnoser once
13964   // the class has been completely parsed.
13965   if (!CurContext->isRecord() &&
13966       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13967                              AbstractParamType))
13968     New->setInvalidDecl();
13969 
13970   // Parameter declarators cannot be interface types. All ObjC objects are
13971   // passed by reference.
13972   if (T->isObjCObjectType()) {
13973     SourceLocation TypeEndLoc =
13974         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13975     Diag(NameLoc,
13976          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13977       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13978     T = Context.getObjCObjectPointerType(T);
13979     New->setType(T);
13980   }
13981 
13982   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13983   // duration shall not be qualified by an address-space qualifier."
13984   // Since all parameters have automatic store duration, they can not have
13985   // an address space.
13986   if (T.getAddressSpace() != LangAS::Default &&
13987       // OpenCL allows function arguments declared to be an array of a type
13988       // to be qualified with an address space.
13989       !(getLangOpts().OpenCL &&
13990         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13991     Diag(NameLoc, diag::err_arg_with_address_space);
13992     New->setInvalidDecl();
13993   }
13994 
13995   // PPC MMA non-pointer types are not allowed as function argument types.
13996   if (Context.getTargetInfo().getTriple().isPPC64() &&
13997       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13998     New->setInvalidDecl();
13999   }
14000 
14001   return New;
14002 }
14003 
14004 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14005                                            SourceLocation LocAfterDecls) {
14006   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14007 
14008   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14009   // for a K&R function.
14010   if (!FTI.hasPrototype) {
14011     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14012       --i;
14013       if (FTI.Params[i].Param == nullptr) {
14014         SmallString<256> Code;
14015         llvm::raw_svector_ostream(Code)
14016             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14017         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14018             << FTI.Params[i].Ident
14019             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14020 
14021         // Implicitly declare the argument as type 'int' for lack of a better
14022         // type.
14023         AttributeFactory attrs;
14024         DeclSpec DS(attrs);
14025         const char* PrevSpec; // unused
14026         unsigned DiagID; // unused
14027         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14028                            DiagID, Context.getPrintingPolicy());
14029         // Use the identifier location for the type source range.
14030         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14031         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14032         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14033         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14034         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14035       }
14036     }
14037   }
14038 }
14039 
14040 Decl *
14041 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14042                               MultiTemplateParamsArg TemplateParameterLists,
14043                               SkipBodyInfo *SkipBody) {
14044   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14045   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14046   Scope *ParentScope = FnBodyScope->getParent();
14047 
14048   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14049   // we define a non-templated function definition, we will create a declaration
14050   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14051   // The base function declaration will have the equivalent of an `omp declare
14052   // variant` annotation which specifies the mangled definition as a
14053   // specialization function under the OpenMP context defined as part of the
14054   // `omp begin declare variant`.
14055   SmallVector<FunctionDecl *, 4> Bases;
14056   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14057     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14058         ParentScope, D, TemplateParameterLists, Bases);
14059 
14060   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14061   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14062   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14063 
14064   if (!Bases.empty())
14065     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14066 
14067   return Dcl;
14068 }
14069 
14070 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14071   Consumer.HandleInlineFunctionDefinition(D);
14072 }
14073 
14074 static bool
14075 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14076                                 const FunctionDecl *&PossiblePrototype) {
14077   // Don't warn about invalid declarations.
14078   if (FD->isInvalidDecl())
14079     return false;
14080 
14081   // Or declarations that aren't global.
14082   if (!FD->isGlobal())
14083     return false;
14084 
14085   // Don't warn about C++ member functions.
14086   if (isa<CXXMethodDecl>(FD))
14087     return false;
14088 
14089   // Don't warn about 'main'.
14090   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14091     if (IdentifierInfo *II = FD->getIdentifier())
14092       if (II->isStr("main") || II->isStr("efi_main"))
14093         return false;
14094 
14095   // Don't warn about inline functions.
14096   if (FD->isInlined())
14097     return false;
14098 
14099   // Don't warn about function templates.
14100   if (FD->getDescribedFunctionTemplate())
14101     return false;
14102 
14103   // Don't warn about function template specializations.
14104   if (FD->isFunctionTemplateSpecialization())
14105     return false;
14106 
14107   // Don't warn for OpenCL kernels.
14108   if (FD->hasAttr<OpenCLKernelAttr>())
14109     return false;
14110 
14111   // Don't warn on explicitly deleted functions.
14112   if (FD->isDeleted())
14113     return false;
14114 
14115   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14116        Prev; Prev = Prev->getPreviousDecl()) {
14117     // Ignore any declarations that occur in function or method
14118     // scope, because they aren't visible from the header.
14119     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14120       continue;
14121 
14122     PossiblePrototype = Prev;
14123     return Prev->getType()->isFunctionNoProtoType();
14124   }
14125 
14126   return true;
14127 }
14128 
14129 void
14130 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14131                                    const FunctionDecl *EffectiveDefinition,
14132                                    SkipBodyInfo *SkipBody) {
14133   const FunctionDecl *Definition = EffectiveDefinition;
14134   if (!Definition &&
14135       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14136     return;
14137 
14138   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14139     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14140       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14141         // A merged copy of the same function, instantiated as a member of
14142         // the same class, is OK.
14143         if (declaresSameEntity(OrigFD, OrigDef) &&
14144             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14145                                cast<Decl>(FD->getLexicalDeclContext())))
14146           return;
14147       }
14148     }
14149   }
14150 
14151   if (canRedefineFunction(Definition, getLangOpts()))
14152     return;
14153 
14154   // Don't emit an error when this is redefinition of a typo-corrected
14155   // definition.
14156   if (TypoCorrectedFunctionDefinitions.count(Definition))
14157     return;
14158 
14159   // If we don't have a visible definition of the function, and it's inline or
14160   // a template, skip the new definition.
14161   if (SkipBody && !hasVisibleDefinition(Definition) &&
14162       (Definition->getFormalLinkage() == InternalLinkage ||
14163        Definition->isInlined() ||
14164        Definition->getDescribedFunctionTemplate() ||
14165        Definition->getNumTemplateParameterLists())) {
14166     SkipBody->ShouldSkip = true;
14167     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14168     if (auto *TD = Definition->getDescribedFunctionTemplate())
14169       makeMergedDefinitionVisible(TD);
14170     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14171     return;
14172   }
14173 
14174   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14175       Definition->getStorageClass() == SC_Extern)
14176     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14177         << FD << getLangOpts().CPlusPlus;
14178   else
14179     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14180 
14181   Diag(Definition->getLocation(), diag::note_previous_definition);
14182   FD->setInvalidDecl();
14183 }
14184 
14185 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14186                                    Sema &S) {
14187   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14188 
14189   LambdaScopeInfo *LSI = S.PushLambdaScope();
14190   LSI->CallOperator = CallOperator;
14191   LSI->Lambda = LambdaClass;
14192   LSI->ReturnType = CallOperator->getReturnType();
14193   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14194 
14195   if (LCD == LCD_None)
14196     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14197   else if (LCD == LCD_ByCopy)
14198     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14199   else if (LCD == LCD_ByRef)
14200     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14201   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14202 
14203   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14204   LSI->Mutable = !CallOperator->isConst();
14205 
14206   // Add the captures to the LSI so they can be noted as already
14207   // captured within tryCaptureVar.
14208   auto I = LambdaClass->field_begin();
14209   for (const auto &C : LambdaClass->captures()) {
14210     if (C.capturesVariable()) {
14211       VarDecl *VD = C.getCapturedVar();
14212       if (VD->isInitCapture())
14213         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14214       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14215       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14216           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14217           /*EllipsisLoc*/C.isPackExpansion()
14218                          ? C.getEllipsisLoc() : SourceLocation(),
14219           I->getType(), /*Invalid*/false);
14220 
14221     } else if (C.capturesThis()) {
14222       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14223                           C.getCaptureKind() == LCK_StarThis);
14224     } else {
14225       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14226                              I->getType());
14227     }
14228     ++I;
14229   }
14230 }
14231 
14232 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14233                                     SkipBodyInfo *SkipBody) {
14234   if (!D) {
14235     // Parsing the function declaration failed in some way. Push on a fake scope
14236     // anyway so we can try to parse the function body.
14237     PushFunctionScope();
14238     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14239     return D;
14240   }
14241 
14242   FunctionDecl *FD = nullptr;
14243 
14244   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14245     FD = FunTmpl->getTemplatedDecl();
14246   else
14247     FD = cast<FunctionDecl>(D);
14248 
14249   // Do not push if it is a lambda because one is already pushed when building
14250   // the lambda in ActOnStartOfLambdaDefinition().
14251   if (!isLambdaCallOperator(FD))
14252     PushExpressionEvaluationContext(
14253         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14254                           : ExprEvalContexts.back().Context);
14255 
14256   // Check for defining attributes before the check for redefinition.
14257   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14258     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14259     FD->dropAttr<AliasAttr>();
14260     FD->setInvalidDecl();
14261   }
14262   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14263     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14264     FD->dropAttr<IFuncAttr>();
14265     FD->setInvalidDecl();
14266   }
14267 
14268   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14269     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14270         Ctor->isDefaultConstructor() &&
14271         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14272       // If this is an MS ABI dllexport default constructor, instantiate any
14273       // default arguments.
14274       InstantiateDefaultCtorDefaultArgs(Ctor);
14275     }
14276   }
14277 
14278   // See if this is a redefinition. If 'will have body' (or similar) is already
14279   // set, then these checks were already performed when it was set.
14280   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14281       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14282     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14283 
14284     // If we're skipping the body, we're done. Don't enter the scope.
14285     if (SkipBody && SkipBody->ShouldSkip)
14286       return D;
14287   }
14288 
14289   // Mark this function as "will have a body eventually".  This lets users to
14290   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14291   // this function.
14292   FD->setWillHaveBody();
14293 
14294   // If we are instantiating a generic lambda call operator, push
14295   // a LambdaScopeInfo onto the function stack.  But use the information
14296   // that's already been calculated (ActOnLambdaExpr) to prime the current
14297   // LambdaScopeInfo.
14298   // When the template operator is being specialized, the LambdaScopeInfo,
14299   // has to be properly restored so that tryCaptureVariable doesn't try
14300   // and capture any new variables. In addition when calculating potential
14301   // captures during transformation of nested lambdas, it is necessary to
14302   // have the LSI properly restored.
14303   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14304     assert(inTemplateInstantiation() &&
14305            "There should be an active template instantiation on the stack "
14306            "when instantiating a generic lambda!");
14307     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14308   } else {
14309     // Enter a new function scope
14310     PushFunctionScope();
14311   }
14312 
14313   // Builtin functions cannot be defined.
14314   if (unsigned BuiltinID = FD->getBuiltinID()) {
14315     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14316         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14317       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14318       FD->setInvalidDecl();
14319     }
14320   }
14321 
14322   // The return type of a function definition must be complete
14323   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14324   QualType ResultType = FD->getReturnType();
14325   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14326       !FD->isInvalidDecl() &&
14327       RequireCompleteType(FD->getLocation(), ResultType,
14328                           diag::err_func_def_incomplete_result))
14329     FD->setInvalidDecl();
14330 
14331   if (FnBodyScope)
14332     PushDeclContext(FnBodyScope, FD);
14333 
14334   // Check the validity of our function parameters
14335   CheckParmsForFunctionDef(FD->parameters(),
14336                            /*CheckParameterNames=*/true);
14337 
14338   // Add non-parameter declarations already in the function to the current
14339   // scope.
14340   if (FnBodyScope) {
14341     for (Decl *NPD : FD->decls()) {
14342       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14343       if (!NonParmDecl)
14344         continue;
14345       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14346              "parameters should not be in newly created FD yet");
14347 
14348       // If the decl has a name, make it accessible in the current scope.
14349       if (NonParmDecl->getDeclName())
14350         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14351 
14352       // Similarly, dive into enums and fish their constants out, making them
14353       // accessible in this scope.
14354       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14355         for (auto *EI : ED->enumerators())
14356           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14357       }
14358     }
14359   }
14360 
14361   // Introduce our parameters into the function scope
14362   for (auto Param : FD->parameters()) {
14363     Param->setOwningFunction(FD);
14364 
14365     // If this has an identifier, add it to the scope stack.
14366     if (Param->getIdentifier() && FnBodyScope) {
14367       CheckShadow(FnBodyScope, Param);
14368 
14369       PushOnScopeChains(Param, FnBodyScope);
14370     }
14371   }
14372 
14373   // Ensure that the function's exception specification is instantiated.
14374   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14375     ResolveExceptionSpec(D->getLocation(), FPT);
14376 
14377   // dllimport cannot be applied to non-inline function definitions.
14378   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14379       !FD->isTemplateInstantiation()) {
14380     assert(!FD->hasAttr<DLLExportAttr>());
14381     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14382     FD->setInvalidDecl();
14383     return D;
14384   }
14385   // We want to attach documentation to original Decl (which might be
14386   // a function template).
14387   ActOnDocumentableDecl(D);
14388   if (getCurLexicalContext()->isObjCContainer() &&
14389       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14390       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14391     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14392 
14393   return D;
14394 }
14395 
14396 /// Given the set of return statements within a function body,
14397 /// compute the variables that are subject to the named return value
14398 /// optimization.
14399 ///
14400 /// Each of the variables that is subject to the named return value
14401 /// optimization will be marked as NRVO variables in the AST, and any
14402 /// return statement that has a marked NRVO variable as its NRVO candidate can
14403 /// use the named return value optimization.
14404 ///
14405 /// This function applies a very simplistic algorithm for NRVO: if every return
14406 /// statement in the scope of a variable has the same NRVO candidate, that
14407 /// candidate is an NRVO variable.
14408 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14409   ReturnStmt **Returns = Scope->Returns.data();
14410 
14411   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14412     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14413       if (!NRVOCandidate->isNRVOVariable())
14414         Returns[I]->setNRVOCandidate(nullptr);
14415     }
14416   }
14417 }
14418 
14419 bool Sema::canDelayFunctionBody(const Declarator &D) {
14420   // We can't delay parsing the body of a constexpr function template (yet).
14421   if (D.getDeclSpec().hasConstexprSpecifier())
14422     return false;
14423 
14424   // We can't delay parsing the body of a function template with a deduced
14425   // return type (yet).
14426   if (D.getDeclSpec().hasAutoTypeSpec()) {
14427     // If the placeholder introduces a non-deduced trailing return type,
14428     // we can still delay parsing it.
14429     if (D.getNumTypeObjects()) {
14430       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14431       if (Outer.Kind == DeclaratorChunk::Function &&
14432           Outer.Fun.hasTrailingReturnType()) {
14433         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14434         return Ty.isNull() || !Ty->isUndeducedType();
14435       }
14436     }
14437     return false;
14438   }
14439 
14440   return true;
14441 }
14442 
14443 bool Sema::canSkipFunctionBody(Decl *D) {
14444   // We cannot skip the body of a function (or function template) which is
14445   // constexpr, since we may need to evaluate its body in order to parse the
14446   // rest of the file.
14447   // We cannot skip the body of a function with an undeduced return type,
14448   // because any callers of that function need to know the type.
14449   if (const FunctionDecl *FD = D->getAsFunction()) {
14450     if (FD->isConstexpr())
14451       return false;
14452     // We can't simply call Type::isUndeducedType here, because inside template
14453     // auto can be deduced to a dependent type, which is not considered
14454     // "undeduced".
14455     if (FD->getReturnType()->getContainedDeducedType())
14456       return false;
14457   }
14458   return Consumer.shouldSkipFunctionBody(D);
14459 }
14460 
14461 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14462   if (!Decl)
14463     return nullptr;
14464   if (FunctionDecl *FD = Decl->getAsFunction())
14465     FD->setHasSkippedBody();
14466   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14467     MD->setHasSkippedBody();
14468   return Decl;
14469 }
14470 
14471 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14472   return ActOnFinishFunctionBody(D, BodyArg, false);
14473 }
14474 
14475 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14476 /// body.
14477 class ExitFunctionBodyRAII {
14478 public:
14479   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14480   ~ExitFunctionBodyRAII() {
14481     if (!IsLambda)
14482       S.PopExpressionEvaluationContext();
14483   }
14484 
14485 private:
14486   Sema &S;
14487   bool IsLambda = false;
14488 };
14489 
14490 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14491   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14492 
14493   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14494     if (EscapeInfo.count(BD))
14495       return EscapeInfo[BD];
14496 
14497     bool R = false;
14498     const BlockDecl *CurBD = BD;
14499 
14500     do {
14501       R = !CurBD->doesNotEscape();
14502       if (R)
14503         break;
14504       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14505     } while (CurBD);
14506 
14507     return EscapeInfo[BD] = R;
14508   };
14509 
14510   // If the location where 'self' is implicitly retained is inside a escaping
14511   // block, emit a diagnostic.
14512   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14513        S.ImplicitlyRetainedSelfLocs)
14514     if (IsOrNestedInEscapingBlock(P.second))
14515       S.Diag(P.first, diag::warn_implicitly_retains_self)
14516           << FixItHint::CreateInsertion(P.first, "self->");
14517 }
14518 
14519 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14520                                     bool IsInstantiation) {
14521   FunctionScopeInfo *FSI = getCurFunction();
14522   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14523 
14524   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14525     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14526 
14527   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14528   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14529 
14530   if (getLangOpts().Coroutines && FSI->isCoroutine())
14531     CheckCompletedCoroutineBody(FD, Body);
14532 
14533   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14534   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14535   // meant to pop the context added in ActOnStartOfFunctionDef().
14536   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14537 
14538   if (FD) {
14539     FD->setBody(Body);
14540     FD->setWillHaveBody(false);
14541 
14542     if (getLangOpts().CPlusPlus14) {
14543       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14544           FD->getReturnType()->isUndeducedType()) {
14545         // If the function has a deduced result type but contains no 'return'
14546         // statements, the result type as written must be exactly 'auto', and
14547         // the deduced result type is 'void'.
14548         if (!FD->getReturnType()->getAs<AutoType>()) {
14549           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14550               << FD->getReturnType();
14551           FD->setInvalidDecl();
14552         } else {
14553           // Substitute 'void' for the 'auto' in the type.
14554           TypeLoc ResultType = getReturnTypeLoc(FD);
14555           Context.adjustDeducedFunctionResultType(
14556               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14557         }
14558       }
14559     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14560       // In C++11, we don't use 'auto' deduction rules for lambda call
14561       // operators because we don't support return type deduction.
14562       auto *LSI = getCurLambda();
14563       if (LSI->HasImplicitReturnType) {
14564         deduceClosureReturnType(*LSI);
14565 
14566         // C++11 [expr.prim.lambda]p4:
14567         //   [...] if there are no return statements in the compound-statement
14568         //   [the deduced type is] the type void
14569         QualType RetType =
14570             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14571 
14572         // Update the return type to the deduced type.
14573         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14574         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14575                                             Proto->getExtProtoInfo()));
14576       }
14577     }
14578 
14579     // If the function implicitly returns zero (like 'main') or is naked,
14580     // don't complain about missing return statements.
14581     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14582       WP.disableCheckFallThrough();
14583 
14584     // MSVC permits the use of pure specifier (=0) on function definition,
14585     // defined at class scope, warn about this non-standard construct.
14586     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14587       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14588 
14589     if (!FD->isInvalidDecl()) {
14590       // Don't diagnose unused parameters of defaulted or deleted functions.
14591       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) {
14592         DiagnoseUnusedParameters(FD->parameters());
14593         DiagnoseUnusedButSetParameters(FD->parameters());
14594       }
14595       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14596                                              FD->getReturnType(), FD);
14597 
14598       // If this is a structor, we need a vtable.
14599       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14600         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14601       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14602         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14603 
14604       // Try to apply the named return value optimization. We have to check
14605       // if we can do this here because lambdas keep return statements around
14606       // to deduce an implicit return type.
14607       if (FD->getReturnType()->isRecordType() &&
14608           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14609         computeNRVO(Body, FSI);
14610     }
14611 
14612     // GNU warning -Wmissing-prototypes:
14613     //   Warn if a global function is defined without a previous
14614     //   prototype declaration. This warning is issued even if the
14615     //   definition itself provides a prototype. The aim is to detect
14616     //   global functions that fail to be declared in header files.
14617     const FunctionDecl *PossiblePrototype = nullptr;
14618     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14619       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14620 
14621       if (PossiblePrototype) {
14622         // We found a declaration that is not a prototype,
14623         // but that could be a zero-parameter prototype
14624         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14625           TypeLoc TL = TI->getTypeLoc();
14626           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14627             Diag(PossiblePrototype->getLocation(),
14628                  diag::note_declaration_not_a_prototype)
14629                 << (FD->getNumParams() != 0)
14630                 << (FD->getNumParams() == 0
14631                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14632                         : FixItHint{});
14633         }
14634       } else {
14635         // Returns true if the token beginning at this Loc is `const`.
14636         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14637                                 const LangOptions &LangOpts) {
14638           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14639           if (LocInfo.first.isInvalid())
14640             return false;
14641 
14642           bool Invalid = false;
14643           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14644           if (Invalid)
14645             return false;
14646 
14647           if (LocInfo.second > Buffer.size())
14648             return false;
14649 
14650           const char *LexStart = Buffer.data() + LocInfo.second;
14651           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14652 
14653           return StartTok.consume_front("const") &&
14654                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14655                   StartTok.startswith("/*") || StartTok.startswith("//"));
14656         };
14657 
14658         auto findBeginLoc = [&]() {
14659           // If the return type has `const` qualifier, we want to insert
14660           // `static` before `const` (and not before the typename).
14661           if ((FD->getReturnType()->isAnyPointerType() &&
14662                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14663               FD->getReturnType().isConstQualified()) {
14664             // But only do this if we can determine where the `const` is.
14665 
14666             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14667                              getLangOpts()))
14668 
14669               return FD->getBeginLoc();
14670           }
14671           return FD->getTypeSpecStartLoc();
14672         };
14673         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14674             << /* function */ 1
14675             << (FD->getStorageClass() == SC_None
14676                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14677                     : FixItHint{});
14678       }
14679 
14680       // GNU warning -Wstrict-prototypes
14681       //   Warn if K&R function is defined without a previous declaration.
14682       //   This warning is issued only if the definition itself does not provide
14683       //   a prototype. Only K&R definitions do not provide a prototype.
14684       if (!FD->hasWrittenPrototype()) {
14685         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14686         TypeLoc TL = TI->getTypeLoc();
14687         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14688         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14689       }
14690     }
14691 
14692     // Warn on CPUDispatch with an actual body.
14693     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14694       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14695         if (!CmpndBody->body_empty())
14696           Diag(CmpndBody->body_front()->getBeginLoc(),
14697                diag::warn_dispatch_body_ignored);
14698 
14699     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14700       const CXXMethodDecl *KeyFunction;
14701       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14702           MD->isVirtual() &&
14703           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14704           MD == KeyFunction->getCanonicalDecl()) {
14705         // Update the key-function state if necessary for this ABI.
14706         if (FD->isInlined() &&
14707             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14708           Context.setNonKeyFunction(MD);
14709 
14710           // If the newly-chosen key function is already defined, then we
14711           // need to mark the vtable as used retroactively.
14712           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14713           const FunctionDecl *Definition;
14714           if (KeyFunction && KeyFunction->isDefined(Definition))
14715             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14716         } else {
14717           // We just defined they key function; mark the vtable as used.
14718           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14719         }
14720       }
14721     }
14722 
14723     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14724            "Function parsing confused");
14725   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14726     assert(MD == getCurMethodDecl() && "Method parsing confused");
14727     MD->setBody(Body);
14728     if (!MD->isInvalidDecl()) {
14729       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14730                                              MD->getReturnType(), MD);
14731 
14732       if (Body)
14733         computeNRVO(Body, FSI);
14734     }
14735     if (FSI->ObjCShouldCallSuper) {
14736       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14737           << MD->getSelector().getAsString();
14738       FSI->ObjCShouldCallSuper = false;
14739     }
14740     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14741       const ObjCMethodDecl *InitMethod = nullptr;
14742       bool isDesignated =
14743           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14744       assert(isDesignated && InitMethod);
14745       (void)isDesignated;
14746 
14747       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14748         auto IFace = MD->getClassInterface();
14749         if (!IFace)
14750           return false;
14751         auto SuperD = IFace->getSuperClass();
14752         if (!SuperD)
14753           return false;
14754         return SuperD->getIdentifier() ==
14755             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14756       };
14757       // Don't issue this warning for unavailable inits or direct subclasses
14758       // of NSObject.
14759       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14760         Diag(MD->getLocation(),
14761              diag::warn_objc_designated_init_missing_super_call);
14762         Diag(InitMethod->getLocation(),
14763              diag::note_objc_designated_init_marked_here);
14764       }
14765       FSI->ObjCWarnForNoDesignatedInitChain = false;
14766     }
14767     if (FSI->ObjCWarnForNoInitDelegation) {
14768       // Don't issue this warning for unavaialable inits.
14769       if (!MD->isUnavailable())
14770         Diag(MD->getLocation(),
14771              diag::warn_objc_secondary_init_missing_init_call);
14772       FSI->ObjCWarnForNoInitDelegation = false;
14773     }
14774 
14775     diagnoseImplicitlyRetainedSelf(*this);
14776   } else {
14777     // Parsing the function declaration failed in some way. Pop the fake scope
14778     // we pushed on.
14779     PopFunctionScopeInfo(ActivePolicy, dcl);
14780     return nullptr;
14781   }
14782 
14783   if (Body && FSI->HasPotentialAvailabilityViolations)
14784     DiagnoseUnguardedAvailabilityViolations(dcl);
14785 
14786   assert(!FSI->ObjCShouldCallSuper &&
14787          "This should only be set for ObjC methods, which should have been "
14788          "handled in the block above.");
14789 
14790   // Verify and clean out per-function state.
14791   if (Body && (!FD || !FD->isDefaulted())) {
14792     // C++ constructors that have function-try-blocks can't have return
14793     // statements in the handlers of that block. (C++ [except.handle]p14)
14794     // Verify this.
14795     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14796       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14797 
14798     // Verify that gotos and switch cases don't jump into scopes illegally.
14799     if (FSI->NeedsScopeChecking() &&
14800         !PP.isCodeCompletionEnabled())
14801       DiagnoseInvalidJumps(Body);
14802 
14803     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14804       if (!Destructor->getParent()->isDependentType())
14805         CheckDestructor(Destructor);
14806 
14807       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14808                                              Destructor->getParent());
14809     }
14810 
14811     // If any errors have occurred, clear out any temporaries that may have
14812     // been leftover. This ensures that these temporaries won't be picked up for
14813     // deletion in some later function.
14814     if (hasUncompilableErrorOccurred() ||
14815         getDiagnostics().getSuppressAllDiagnostics()) {
14816       DiscardCleanupsInEvaluationContext();
14817     }
14818     if (!hasUncompilableErrorOccurred() &&
14819         !isa<FunctionTemplateDecl>(dcl)) {
14820       // Since the body is valid, issue any analysis-based warnings that are
14821       // enabled.
14822       ActivePolicy = &WP;
14823     }
14824 
14825     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14826         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14827       FD->setInvalidDecl();
14828 
14829     if (FD && FD->hasAttr<NakedAttr>()) {
14830       for (const Stmt *S : Body->children()) {
14831         // Allow local register variables without initializer as they don't
14832         // require prologue.
14833         bool RegisterVariables = false;
14834         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14835           for (const auto *Decl : DS->decls()) {
14836             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14837               RegisterVariables =
14838                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14839               if (!RegisterVariables)
14840                 break;
14841             }
14842           }
14843         }
14844         if (RegisterVariables)
14845           continue;
14846         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14847           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14848           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14849           FD->setInvalidDecl();
14850           break;
14851         }
14852       }
14853     }
14854 
14855     assert(ExprCleanupObjects.size() ==
14856                ExprEvalContexts.back().NumCleanupObjects &&
14857            "Leftover temporaries in function");
14858     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14859     assert(MaybeODRUseExprs.empty() &&
14860            "Leftover expressions for odr-use checking");
14861   }
14862 
14863   if (!IsInstantiation)
14864     PopDeclContext();
14865 
14866   PopFunctionScopeInfo(ActivePolicy, dcl);
14867   // If any errors have occurred, clear out any temporaries that may have
14868   // been leftover. This ensures that these temporaries won't be picked up for
14869   // deletion in some later function.
14870   if (hasUncompilableErrorOccurred()) {
14871     DiscardCleanupsInEvaluationContext();
14872   }
14873 
14874   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14875     auto ES = getEmissionStatus(FD);
14876     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14877         ES == Sema::FunctionEmissionStatus::Unknown)
14878       DeclsToCheckForDeferredDiags.push_back(FD);
14879   }
14880 
14881   return dcl;
14882 }
14883 
14884 /// When we finish delayed parsing of an attribute, we must attach it to the
14885 /// relevant Decl.
14886 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14887                                        ParsedAttributes &Attrs) {
14888   // Always attach attributes to the underlying decl.
14889   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14890     D = TD->getTemplatedDecl();
14891   ProcessDeclAttributeList(S, D, Attrs);
14892 
14893   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14894     if (Method->isStatic())
14895       checkThisInStaticMemberFunctionAttributes(Method);
14896 }
14897 
14898 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14899 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14900 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14901                                           IdentifierInfo &II, Scope *S) {
14902   // Find the scope in which the identifier is injected and the corresponding
14903   // DeclContext.
14904   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14905   // In that case, we inject the declaration into the translation unit scope
14906   // instead.
14907   Scope *BlockScope = S;
14908   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14909     BlockScope = BlockScope->getParent();
14910 
14911   Scope *ContextScope = BlockScope;
14912   while (!ContextScope->getEntity())
14913     ContextScope = ContextScope->getParent();
14914   ContextRAII SavedContext(*this, ContextScope->getEntity());
14915 
14916   // Before we produce a declaration for an implicitly defined
14917   // function, see whether there was a locally-scoped declaration of
14918   // this name as a function or variable. If so, use that
14919   // (non-visible) declaration, and complain about it.
14920   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14921   if (ExternCPrev) {
14922     // We still need to inject the function into the enclosing block scope so
14923     // that later (non-call) uses can see it.
14924     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14925 
14926     // C89 footnote 38:
14927     //   If in fact it is not defined as having type "function returning int",
14928     //   the behavior is undefined.
14929     if (!isa<FunctionDecl>(ExternCPrev) ||
14930         !Context.typesAreCompatible(
14931             cast<FunctionDecl>(ExternCPrev)->getType(),
14932             Context.getFunctionNoProtoType(Context.IntTy))) {
14933       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14934           << ExternCPrev << !getLangOpts().C99;
14935       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14936       return ExternCPrev;
14937     }
14938   }
14939 
14940   // Extension in C99.  Legal in C90, but warn about it.
14941   unsigned diag_id;
14942   if (II.getName().startswith("__builtin_"))
14943     diag_id = diag::warn_builtin_unknown;
14944   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14945   else if (getLangOpts().OpenCL)
14946     diag_id = diag::err_opencl_implicit_function_decl;
14947   else if (getLangOpts().C99)
14948     diag_id = diag::ext_implicit_function_decl;
14949   else
14950     diag_id = diag::warn_implicit_function_decl;
14951   Diag(Loc, diag_id) << &II;
14952 
14953   // If we found a prior declaration of this function, don't bother building
14954   // another one. We've already pushed that one into scope, so there's nothing
14955   // more to do.
14956   if (ExternCPrev)
14957     return ExternCPrev;
14958 
14959   // Because typo correction is expensive, only do it if the implicit
14960   // function declaration is going to be treated as an error.
14961   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14962     TypoCorrection Corrected;
14963     DeclFilterCCC<FunctionDecl> CCC{};
14964     if (S && (Corrected =
14965                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14966                               S, nullptr, CCC, CTK_NonError)))
14967       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14968                    /*ErrorRecovery*/false);
14969   }
14970 
14971   // Set a Declarator for the implicit definition: int foo();
14972   const char *Dummy;
14973   AttributeFactory attrFactory;
14974   DeclSpec DS(attrFactory);
14975   unsigned DiagID;
14976   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14977                                   Context.getPrintingPolicy());
14978   (void)Error; // Silence warning.
14979   assert(!Error && "Error setting up implicit decl!");
14980   SourceLocation NoLoc;
14981   Declarator D(DS, DeclaratorContext::Block);
14982   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14983                                              /*IsAmbiguous=*/false,
14984                                              /*LParenLoc=*/NoLoc,
14985                                              /*Params=*/nullptr,
14986                                              /*NumParams=*/0,
14987                                              /*EllipsisLoc=*/NoLoc,
14988                                              /*RParenLoc=*/NoLoc,
14989                                              /*RefQualifierIsLvalueRef=*/true,
14990                                              /*RefQualifierLoc=*/NoLoc,
14991                                              /*MutableLoc=*/NoLoc, EST_None,
14992                                              /*ESpecRange=*/SourceRange(),
14993                                              /*Exceptions=*/nullptr,
14994                                              /*ExceptionRanges=*/nullptr,
14995                                              /*NumExceptions=*/0,
14996                                              /*NoexceptExpr=*/nullptr,
14997                                              /*ExceptionSpecTokens=*/nullptr,
14998                                              /*DeclsInPrototype=*/None, Loc,
14999                                              Loc, D),
15000                 std::move(DS.getAttributes()), SourceLocation());
15001   D.SetIdentifier(&II, Loc);
15002 
15003   // Insert this function into the enclosing block scope.
15004   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15005   FD->setImplicit();
15006 
15007   AddKnownFunctionAttributes(FD);
15008 
15009   return FD;
15010 }
15011 
15012 /// If this function is a C++ replaceable global allocation function
15013 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15014 /// adds any function attributes that we know a priori based on the standard.
15015 ///
15016 /// We need to check for duplicate attributes both here and where user-written
15017 /// attributes are applied to declarations.
15018 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15019     FunctionDecl *FD) {
15020   if (FD->isInvalidDecl())
15021     return;
15022 
15023   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15024       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15025     return;
15026 
15027   Optional<unsigned> AlignmentParam;
15028   bool IsNothrow = false;
15029   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15030     return;
15031 
15032   // C++2a [basic.stc.dynamic.allocation]p4:
15033   //   An allocation function that has a non-throwing exception specification
15034   //   indicates failure by returning a null pointer value. Any other allocation
15035   //   function never returns a null pointer value and indicates failure only by
15036   //   throwing an exception [...]
15037   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15038     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15039 
15040   // C++2a [basic.stc.dynamic.allocation]p2:
15041   //   An allocation function attempts to allocate the requested amount of
15042   //   storage. [...] If the request succeeds, the value returned by a
15043   //   replaceable allocation function is a [...] pointer value p0 different
15044   //   from any previously returned value p1 [...]
15045   //
15046   // However, this particular information is being added in codegen,
15047   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15048 
15049   // C++2a [basic.stc.dynamic.allocation]p2:
15050   //   An allocation function attempts to allocate the requested amount of
15051   //   storage. If it is successful, it returns the address of the start of a
15052   //   block of storage whose length in bytes is at least as large as the
15053   //   requested size.
15054   if (!FD->hasAttr<AllocSizeAttr>()) {
15055     FD->addAttr(AllocSizeAttr::CreateImplicit(
15056         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15057         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15058   }
15059 
15060   // C++2a [basic.stc.dynamic.allocation]p3:
15061   //   For an allocation function [...], the pointer returned on a successful
15062   //   call shall represent the address of storage that is aligned as follows:
15063   //   (3.1) If the allocation function takes an argument of type
15064   //         std​::​align_­val_­t, the storage will have the alignment
15065   //         specified by the value of this argument.
15066   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15067     FD->addAttr(AllocAlignAttr::CreateImplicit(
15068         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15069   }
15070 
15071   // FIXME:
15072   // C++2a [basic.stc.dynamic.allocation]p3:
15073   //   For an allocation function [...], the pointer returned on a successful
15074   //   call shall represent the address of storage that is aligned as follows:
15075   //   (3.2) Otherwise, if the allocation function is named operator new[],
15076   //         the storage is aligned for any object that does not have
15077   //         new-extended alignment ([basic.align]) and is no larger than the
15078   //         requested size.
15079   //   (3.3) Otherwise, the storage is aligned for any object that does not
15080   //         have new-extended alignment and is of the requested size.
15081 }
15082 
15083 /// Adds any function attributes that we know a priori based on
15084 /// the declaration of this function.
15085 ///
15086 /// These attributes can apply both to implicitly-declared builtins
15087 /// (like __builtin___printf_chk) or to library-declared functions
15088 /// like NSLog or printf.
15089 ///
15090 /// We need to check for duplicate attributes both here and where user-written
15091 /// attributes are applied to declarations.
15092 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15093   if (FD->isInvalidDecl())
15094     return;
15095 
15096   // If this is a built-in function, map its builtin attributes to
15097   // actual attributes.
15098   if (unsigned BuiltinID = FD->getBuiltinID()) {
15099     // Handle printf-formatting attributes.
15100     unsigned FormatIdx;
15101     bool HasVAListArg;
15102     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15103       if (!FD->hasAttr<FormatAttr>()) {
15104         const char *fmt = "printf";
15105         unsigned int NumParams = FD->getNumParams();
15106         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15107             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15108           fmt = "NSString";
15109         FD->addAttr(FormatAttr::CreateImplicit(Context,
15110                                                &Context.Idents.get(fmt),
15111                                                FormatIdx+1,
15112                                                HasVAListArg ? 0 : FormatIdx+2,
15113                                                FD->getLocation()));
15114       }
15115     }
15116     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15117                                              HasVAListArg)) {
15118      if (!FD->hasAttr<FormatAttr>())
15119        FD->addAttr(FormatAttr::CreateImplicit(Context,
15120                                               &Context.Idents.get("scanf"),
15121                                               FormatIdx+1,
15122                                               HasVAListArg ? 0 : FormatIdx+2,
15123                                               FD->getLocation()));
15124     }
15125 
15126     // Handle automatically recognized callbacks.
15127     SmallVector<int, 4> Encoding;
15128     if (!FD->hasAttr<CallbackAttr>() &&
15129         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15130       FD->addAttr(CallbackAttr::CreateImplicit(
15131           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15132 
15133     // Mark const if we don't care about errno and that is the only thing
15134     // preventing the function from being const. This allows IRgen to use LLVM
15135     // intrinsics for such functions.
15136     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15137         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15138       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15139 
15140     // We make "fma" on some platforms const because we know it does not set
15141     // errno in those environments even though it could set errno based on the
15142     // C standard.
15143     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15144     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15145         !FD->hasAttr<ConstAttr>()) {
15146       switch (BuiltinID) {
15147       case Builtin::BI__builtin_fma:
15148       case Builtin::BI__builtin_fmaf:
15149       case Builtin::BI__builtin_fmal:
15150       case Builtin::BIfma:
15151       case Builtin::BIfmaf:
15152       case Builtin::BIfmal:
15153         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15154         break;
15155       default:
15156         break;
15157       }
15158     }
15159 
15160     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15161         !FD->hasAttr<ReturnsTwiceAttr>())
15162       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15163                                          FD->getLocation()));
15164     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15165       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15166     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15167       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15168     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15169       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15170     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15171         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15172       // Add the appropriate attribute, depending on the CUDA compilation mode
15173       // and which target the builtin belongs to. For example, during host
15174       // compilation, aux builtins are __device__, while the rest are __host__.
15175       if (getLangOpts().CUDAIsDevice !=
15176           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15177         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15178       else
15179         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15180     }
15181   }
15182 
15183   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15184 
15185   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15186   // throw, add an implicit nothrow attribute to any extern "C" function we come
15187   // across.
15188   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15189       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15190     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15191     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15192       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15193   }
15194 
15195   IdentifierInfo *Name = FD->getIdentifier();
15196   if (!Name)
15197     return;
15198   if ((!getLangOpts().CPlusPlus &&
15199        FD->getDeclContext()->isTranslationUnit()) ||
15200       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15201        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15202        LinkageSpecDecl::lang_c)) {
15203     // Okay: this could be a libc/libm/Objective-C function we know
15204     // about.
15205   } else
15206     return;
15207 
15208   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15209     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15210     // target-specific builtins, perhaps?
15211     if (!FD->hasAttr<FormatAttr>())
15212       FD->addAttr(FormatAttr::CreateImplicit(Context,
15213                                              &Context.Idents.get("printf"), 2,
15214                                              Name->isStr("vasprintf") ? 0 : 3,
15215                                              FD->getLocation()));
15216   }
15217 
15218   if (Name->isStr("__CFStringMakeConstantString")) {
15219     // We already have a __builtin___CFStringMakeConstantString,
15220     // but builds that use -fno-constant-cfstrings don't go through that.
15221     if (!FD->hasAttr<FormatArgAttr>())
15222       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15223                                                 FD->getLocation()));
15224   }
15225 }
15226 
15227 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15228                                     TypeSourceInfo *TInfo) {
15229   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15230   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15231 
15232   if (!TInfo) {
15233     assert(D.isInvalidType() && "no declarator info for valid type");
15234     TInfo = Context.getTrivialTypeSourceInfo(T);
15235   }
15236 
15237   // Scope manipulation handled by caller.
15238   TypedefDecl *NewTD =
15239       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15240                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15241 
15242   // Bail out immediately if we have an invalid declaration.
15243   if (D.isInvalidType()) {
15244     NewTD->setInvalidDecl();
15245     return NewTD;
15246   }
15247 
15248   if (D.getDeclSpec().isModulePrivateSpecified()) {
15249     if (CurContext->isFunctionOrMethod())
15250       Diag(NewTD->getLocation(), diag::err_module_private_local)
15251           << 2 << NewTD
15252           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15253           << FixItHint::CreateRemoval(
15254                  D.getDeclSpec().getModulePrivateSpecLoc());
15255     else
15256       NewTD->setModulePrivate();
15257   }
15258 
15259   // C++ [dcl.typedef]p8:
15260   //   If the typedef declaration defines an unnamed class (or
15261   //   enum), the first typedef-name declared by the declaration
15262   //   to be that class type (or enum type) is used to denote the
15263   //   class type (or enum type) for linkage purposes only.
15264   // We need to check whether the type was declared in the declaration.
15265   switch (D.getDeclSpec().getTypeSpecType()) {
15266   case TST_enum:
15267   case TST_struct:
15268   case TST_interface:
15269   case TST_union:
15270   case TST_class: {
15271     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15272     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15273     break;
15274   }
15275 
15276   default:
15277     break;
15278   }
15279 
15280   return NewTD;
15281 }
15282 
15283 /// Check that this is a valid underlying type for an enum declaration.
15284 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15285   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15286   QualType T = TI->getType();
15287 
15288   if (T->isDependentType())
15289     return false;
15290 
15291   // This doesn't use 'isIntegralType' despite the error message mentioning
15292   // integral type because isIntegralType would also allow enum types in C.
15293   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15294     if (BT->isInteger())
15295       return false;
15296 
15297   if (T->isExtIntType())
15298     return false;
15299 
15300   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15301 }
15302 
15303 /// Check whether this is a valid redeclaration of a previous enumeration.
15304 /// \return true if the redeclaration was invalid.
15305 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15306                                   QualType EnumUnderlyingTy, bool IsFixed,
15307                                   const EnumDecl *Prev) {
15308   if (IsScoped != Prev->isScoped()) {
15309     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15310       << Prev->isScoped();
15311     Diag(Prev->getLocation(), diag::note_previous_declaration);
15312     return true;
15313   }
15314 
15315   if (IsFixed && Prev->isFixed()) {
15316     if (!EnumUnderlyingTy->isDependentType() &&
15317         !Prev->getIntegerType()->isDependentType() &&
15318         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15319                                         Prev->getIntegerType())) {
15320       // TODO: Highlight the underlying type of the redeclaration.
15321       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15322         << EnumUnderlyingTy << Prev->getIntegerType();
15323       Diag(Prev->getLocation(), diag::note_previous_declaration)
15324           << Prev->getIntegerTypeRange();
15325       return true;
15326     }
15327   } else if (IsFixed != Prev->isFixed()) {
15328     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15329       << Prev->isFixed();
15330     Diag(Prev->getLocation(), diag::note_previous_declaration);
15331     return true;
15332   }
15333 
15334   return false;
15335 }
15336 
15337 /// Get diagnostic %select index for tag kind for
15338 /// redeclaration diagnostic message.
15339 /// WARNING: Indexes apply to particular diagnostics only!
15340 ///
15341 /// \returns diagnostic %select index.
15342 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15343   switch (Tag) {
15344   case TTK_Struct: return 0;
15345   case TTK_Interface: return 1;
15346   case TTK_Class:  return 2;
15347   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15348   }
15349 }
15350 
15351 /// Determine if tag kind is a class-key compatible with
15352 /// class for redeclaration (class, struct, or __interface).
15353 ///
15354 /// \returns true iff the tag kind is compatible.
15355 static bool isClassCompatTagKind(TagTypeKind Tag)
15356 {
15357   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15358 }
15359 
15360 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15361                                              TagTypeKind TTK) {
15362   if (isa<TypedefDecl>(PrevDecl))
15363     return NTK_Typedef;
15364   else if (isa<TypeAliasDecl>(PrevDecl))
15365     return NTK_TypeAlias;
15366   else if (isa<ClassTemplateDecl>(PrevDecl))
15367     return NTK_Template;
15368   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15369     return NTK_TypeAliasTemplate;
15370   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15371     return NTK_TemplateTemplateArgument;
15372   switch (TTK) {
15373   case TTK_Struct:
15374   case TTK_Interface:
15375   case TTK_Class:
15376     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15377   case TTK_Union:
15378     return NTK_NonUnion;
15379   case TTK_Enum:
15380     return NTK_NonEnum;
15381   }
15382   llvm_unreachable("invalid TTK");
15383 }
15384 
15385 /// Determine whether a tag with a given kind is acceptable
15386 /// as a redeclaration of the given tag declaration.
15387 ///
15388 /// \returns true if the new tag kind is acceptable, false otherwise.
15389 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15390                                         TagTypeKind NewTag, bool isDefinition,
15391                                         SourceLocation NewTagLoc,
15392                                         const IdentifierInfo *Name) {
15393   // C++ [dcl.type.elab]p3:
15394   //   The class-key or enum keyword present in the
15395   //   elaborated-type-specifier shall agree in kind with the
15396   //   declaration to which the name in the elaborated-type-specifier
15397   //   refers. This rule also applies to the form of
15398   //   elaborated-type-specifier that declares a class-name or
15399   //   friend class since it can be construed as referring to the
15400   //   definition of the class. Thus, in any
15401   //   elaborated-type-specifier, the enum keyword shall be used to
15402   //   refer to an enumeration (7.2), the union class-key shall be
15403   //   used to refer to a union (clause 9), and either the class or
15404   //   struct class-key shall be used to refer to a class (clause 9)
15405   //   declared using the class or struct class-key.
15406   TagTypeKind OldTag = Previous->getTagKind();
15407   if (OldTag != NewTag &&
15408       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15409     return false;
15410 
15411   // Tags are compatible, but we might still want to warn on mismatched tags.
15412   // Non-class tags can't be mismatched at this point.
15413   if (!isClassCompatTagKind(NewTag))
15414     return true;
15415 
15416   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15417   // by our warning analysis. We don't want to warn about mismatches with (eg)
15418   // declarations in system headers that are designed to be specialized, but if
15419   // a user asks us to warn, we should warn if their code contains mismatched
15420   // declarations.
15421   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15422     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15423                                       Loc);
15424   };
15425   if (IsIgnoredLoc(NewTagLoc))
15426     return true;
15427 
15428   auto IsIgnored = [&](const TagDecl *Tag) {
15429     return IsIgnoredLoc(Tag->getLocation());
15430   };
15431   while (IsIgnored(Previous)) {
15432     Previous = Previous->getPreviousDecl();
15433     if (!Previous)
15434       return true;
15435     OldTag = Previous->getTagKind();
15436   }
15437 
15438   bool isTemplate = false;
15439   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15440     isTemplate = Record->getDescribedClassTemplate();
15441 
15442   if (inTemplateInstantiation()) {
15443     if (OldTag != NewTag) {
15444       // In a template instantiation, do not offer fix-its for tag mismatches
15445       // since they usually mess up the template instead of fixing the problem.
15446       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15447         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15448         << getRedeclDiagFromTagKind(OldTag);
15449       // FIXME: Note previous location?
15450     }
15451     return true;
15452   }
15453 
15454   if (isDefinition) {
15455     // On definitions, check all previous tags and issue a fix-it for each
15456     // one that doesn't match the current tag.
15457     if (Previous->getDefinition()) {
15458       // Don't suggest fix-its for redefinitions.
15459       return true;
15460     }
15461 
15462     bool previousMismatch = false;
15463     for (const TagDecl *I : Previous->redecls()) {
15464       if (I->getTagKind() != NewTag) {
15465         // Ignore previous declarations for which the warning was disabled.
15466         if (IsIgnored(I))
15467           continue;
15468 
15469         if (!previousMismatch) {
15470           previousMismatch = true;
15471           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15472             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15473             << getRedeclDiagFromTagKind(I->getTagKind());
15474         }
15475         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15476           << getRedeclDiagFromTagKind(NewTag)
15477           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15478                TypeWithKeyword::getTagTypeKindName(NewTag));
15479       }
15480     }
15481     return true;
15482   }
15483 
15484   // Identify the prevailing tag kind: this is the kind of the definition (if
15485   // there is a non-ignored definition), or otherwise the kind of the prior
15486   // (non-ignored) declaration.
15487   const TagDecl *PrevDef = Previous->getDefinition();
15488   if (PrevDef && IsIgnored(PrevDef))
15489     PrevDef = nullptr;
15490   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15491   if (Redecl->getTagKind() != NewTag) {
15492     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15493       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15494       << getRedeclDiagFromTagKind(OldTag);
15495     Diag(Redecl->getLocation(), diag::note_previous_use);
15496 
15497     // If there is a previous definition, suggest a fix-it.
15498     if (PrevDef) {
15499       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15500         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15501         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15502              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15503     }
15504   }
15505 
15506   return true;
15507 }
15508 
15509 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15510 /// from an outer enclosing namespace or file scope inside a friend declaration.
15511 /// This should provide the commented out code in the following snippet:
15512 ///   namespace N {
15513 ///     struct X;
15514 ///     namespace M {
15515 ///       struct Y { friend struct /*N::*/ X; };
15516 ///     }
15517 ///   }
15518 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15519                                          SourceLocation NameLoc) {
15520   // While the decl is in a namespace, do repeated lookup of that name and see
15521   // if we get the same namespace back.  If we do not, continue until
15522   // translation unit scope, at which point we have a fully qualified NNS.
15523   SmallVector<IdentifierInfo *, 4> Namespaces;
15524   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15525   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15526     // This tag should be declared in a namespace, which can only be enclosed by
15527     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15528     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15529     if (!Namespace || Namespace->isAnonymousNamespace())
15530       return FixItHint();
15531     IdentifierInfo *II = Namespace->getIdentifier();
15532     Namespaces.push_back(II);
15533     NamedDecl *Lookup = SemaRef.LookupSingleName(
15534         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15535     if (Lookup == Namespace)
15536       break;
15537   }
15538 
15539   // Once we have all the namespaces, reverse them to go outermost first, and
15540   // build an NNS.
15541   SmallString<64> Insertion;
15542   llvm::raw_svector_ostream OS(Insertion);
15543   if (DC->isTranslationUnit())
15544     OS << "::";
15545   std::reverse(Namespaces.begin(), Namespaces.end());
15546   for (auto *II : Namespaces)
15547     OS << II->getName() << "::";
15548   return FixItHint::CreateInsertion(NameLoc, Insertion);
15549 }
15550 
15551 /// Determine whether a tag originally declared in context \p OldDC can
15552 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15553 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15554 /// using-declaration).
15555 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15556                                          DeclContext *NewDC) {
15557   OldDC = OldDC->getRedeclContext();
15558   NewDC = NewDC->getRedeclContext();
15559 
15560   if (OldDC->Equals(NewDC))
15561     return true;
15562 
15563   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15564   // encloses the other).
15565   if (S.getLangOpts().MSVCCompat &&
15566       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15567     return true;
15568 
15569   return false;
15570 }
15571 
15572 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15573 /// former case, Name will be non-null.  In the later case, Name will be null.
15574 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15575 /// reference/declaration/definition of a tag.
15576 ///
15577 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15578 /// trailing-type-specifier) other than one in an alias-declaration.
15579 ///
15580 /// \param SkipBody If non-null, will be set to indicate if the caller should
15581 /// skip the definition of this tag and treat it as if it were a declaration.
15582 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15583                      SourceLocation KWLoc, CXXScopeSpec &SS,
15584                      IdentifierInfo *Name, SourceLocation NameLoc,
15585                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15586                      SourceLocation ModulePrivateLoc,
15587                      MultiTemplateParamsArg TemplateParameterLists,
15588                      bool &OwnedDecl, bool &IsDependent,
15589                      SourceLocation ScopedEnumKWLoc,
15590                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15591                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15592                      SkipBodyInfo *SkipBody) {
15593   // If this is not a definition, it must have a name.
15594   IdentifierInfo *OrigName = Name;
15595   assert((Name != nullptr || TUK == TUK_Definition) &&
15596          "Nameless record must be a definition!");
15597   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15598 
15599   OwnedDecl = false;
15600   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15601   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15602 
15603   // FIXME: Check member specializations more carefully.
15604   bool isMemberSpecialization = false;
15605   bool Invalid = false;
15606 
15607   // We only need to do this matching if we have template parameters
15608   // or a scope specifier, which also conveniently avoids this work
15609   // for non-C++ cases.
15610   if (TemplateParameterLists.size() > 0 ||
15611       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15612     if (TemplateParameterList *TemplateParams =
15613             MatchTemplateParametersToScopeSpecifier(
15614                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15615                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15616       if (Kind == TTK_Enum) {
15617         Diag(KWLoc, diag::err_enum_template);
15618         return nullptr;
15619       }
15620 
15621       if (TemplateParams->size() > 0) {
15622         // This is a declaration or definition of a class template (which may
15623         // be a member of another template).
15624 
15625         if (Invalid)
15626           return nullptr;
15627 
15628         OwnedDecl = false;
15629         DeclResult Result = CheckClassTemplate(
15630             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15631             AS, ModulePrivateLoc,
15632             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15633             TemplateParameterLists.data(), SkipBody);
15634         return Result.get();
15635       } else {
15636         // The "template<>" header is extraneous.
15637         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15638           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15639         isMemberSpecialization = true;
15640       }
15641     }
15642 
15643     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15644         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15645       return nullptr;
15646   }
15647 
15648   // Figure out the underlying type if this a enum declaration. We need to do
15649   // this early, because it's needed to detect if this is an incompatible
15650   // redeclaration.
15651   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15652   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15653 
15654   if (Kind == TTK_Enum) {
15655     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15656       // No underlying type explicitly specified, or we failed to parse the
15657       // type, default to int.
15658       EnumUnderlying = Context.IntTy.getTypePtr();
15659     } else if (UnderlyingType.get()) {
15660       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15661       // integral type; any cv-qualification is ignored.
15662       TypeSourceInfo *TI = nullptr;
15663       GetTypeFromParser(UnderlyingType.get(), &TI);
15664       EnumUnderlying = TI;
15665 
15666       if (CheckEnumUnderlyingType(TI))
15667         // Recover by falling back to int.
15668         EnumUnderlying = Context.IntTy.getTypePtr();
15669 
15670       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15671                                           UPPC_FixedUnderlyingType))
15672         EnumUnderlying = Context.IntTy.getTypePtr();
15673 
15674     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15675       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15676       // of 'int'. However, if this is an unfixed forward declaration, don't set
15677       // the underlying type unless the user enables -fms-compatibility. This
15678       // makes unfixed forward declared enums incomplete and is more conforming.
15679       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15680         EnumUnderlying = Context.IntTy.getTypePtr();
15681     }
15682   }
15683 
15684   DeclContext *SearchDC = CurContext;
15685   DeclContext *DC = CurContext;
15686   bool isStdBadAlloc = false;
15687   bool isStdAlignValT = false;
15688 
15689   RedeclarationKind Redecl = forRedeclarationInCurContext();
15690   if (TUK == TUK_Friend || TUK == TUK_Reference)
15691     Redecl = NotForRedeclaration;
15692 
15693   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15694   /// implemented asks for structural equivalence checking, the returned decl
15695   /// here is passed back to the parser, allowing the tag body to be parsed.
15696   auto createTagFromNewDecl = [&]() -> TagDecl * {
15697     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15698     // If there is an identifier, use the location of the identifier as the
15699     // location of the decl, otherwise use the location of the struct/union
15700     // keyword.
15701     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15702     TagDecl *New = nullptr;
15703 
15704     if (Kind == TTK_Enum) {
15705       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15706                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15707       // If this is an undefined enum, bail.
15708       if (TUK != TUK_Definition && !Invalid)
15709         return nullptr;
15710       if (EnumUnderlying) {
15711         EnumDecl *ED = cast<EnumDecl>(New);
15712         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15713           ED->setIntegerTypeSourceInfo(TI);
15714         else
15715           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15716         ED->setPromotionType(ED->getIntegerType());
15717       }
15718     } else { // struct/union
15719       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15720                                nullptr);
15721     }
15722 
15723     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15724       // Add alignment attributes if necessary; these attributes are checked
15725       // when the ASTContext lays out the structure.
15726       //
15727       // It is important for implementing the correct semantics that this
15728       // happen here (in ActOnTag). The #pragma pack stack is
15729       // maintained as a result of parser callbacks which can occur at
15730       // many points during the parsing of a struct declaration (because
15731       // the #pragma tokens are effectively skipped over during the
15732       // parsing of the struct).
15733       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15734         AddAlignmentAttributesForRecord(RD);
15735         AddMsStructLayoutForRecord(RD);
15736       }
15737     }
15738     New->setLexicalDeclContext(CurContext);
15739     return New;
15740   };
15741 
15742   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15743   if (Name && SS.isNotEmpty()) {
15744     // We have a nested-name tag ('struct foo::bar').
15745 
15746     // Check for invalid 'foo::'.
15747     if (SS.isInvalid()) {
15748       Name = nullptr;
15749       goto CreateNewDecl;
15750     }
15751 
15752     // If this is a friend or a reference to a class in a dependent
15753     // context, don't try to make a decl for it.
15754     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15755       DC = computeDeclContext(SS, false);
15756       if (!DC) {
15757         IsDependent = true;
15758         return nullptr;
15759       }
15760     } else {
15761       DC = computeDeclContext(SS, true);
15762       if (!DC) {
15763         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15764           << SS.getRange();
15765         return nullptr;
15766       }
15767     }
15768 
15769     if (RequireCompleteDeclContext(SS, DC))
15770       return nullptr;
15771 
15772     SearchDC = DC;
15773     // Look-up name inside 'foo::'.
15774     LookupQualifiedName(Previous, DC);
15775 
15776     if (Previous.isAmbiguous())
15777       return nullptr;
15778 
15779     if (Previous.empty()) {
15780       // Name lookup did not find anything. However, if the
15781       // nested-name-specifier refers to the current instantiation,
15782       // and that current instantiation has any dependent base
15783       // classes, we might find something at instantiation time: treat
15784       // this as a dependent elaborated-type-specifier.
15785       // But this only makes any sense for reference-like lookups.
15786       if (Previous.wasNotFoundInCurrentInstantiation() &&
15787           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15788         IsDependent = true;
15789         return nullptr;
15790       }
15791 
15792       // A tag 'foo::bar' must already exist.
15793       Diag(NameLoc, diag::err_not_tag_in_scope)
15794         << Kind << Name << DC << SS.getRange();
15795       Name = nullptr;
15796       Invalid = true;
15797       goto CreateNewDecl;
15798     }
15799   } else if (Name) {
15800     // C++14 [class.mem]p14:
15801     //   If T is the name of a class, then each of the following shall have a
15802     //   name different from T:
15803     //    -- every member of class T that is itself a type
15804     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15805         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15806       return nullptr;
15807 
15808     // If this is a named struct, check to see if there was a previous forward
15809     // declaration or definition.
15810     // FIXME: We're looking into outer scopes here, even when we
15811     // shouldn't be. Doing so can result in ambiguities that we
15812     // shouldn't be diagnosing.
15813     LookupName(Previous, S);
15814 
15815     // When declaring or defining a tag, ignore ambiguities introduced
15816     // by types using'ed into this scope.
15817     if (Previous.isAmbiguous() &&
15818         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15819       LookupResult::Filter F = Previous.makeFilter();
15820       while (F.hasNext()) {
15821         NamedDecl *ND = F.next();
15822         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15823                 SearchDC->getRedeclContext()))
15824           F.erase();
15825       }
15826       F.done();
15827     }
15828 
15829     // C++11 [namespace.memdef]p3:
15830     //   If the name in a friend declaration is neither qualified nor
15831     //   a template-id and the declaration is a function or an
15832     //   elaborated-type-specifier, the lookup to determine whether
15833     //   the entity has been previously declared shall not consider
15834     //   any scopes outside the innermost enclosing namespace.
15835     //
15836     // MSVC doesn't implement the above rule for types, so a friend tag
15837     // declaration may be a redeclaration of a type declared in an enclosing
15838     // scope.  They do implement this rule for friend functions.
15839     //
15840     // Does it matter that this should be by scope instead of by
15841     // semantic context?
15842     if (!Previous.empty() && TUK == TUK_Friend) {
15843       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15844       LookupResult::Filter F = Previous.makeFilter();
15845       bool FriendSawTagOutsideEnclosingNamespace = false;
15846       while (F.hasNext()) {
15847         NamedDecl *ND = F.next();
15848         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15849         if (DC->isFileContext() &&
15850             !EnclosingNS->Encloses(ND->getDeclContext())) {
15851           if (getLangOpts().MSVCCompat)
15852             FriendSawTagOutsideEnclosingNamespace = true;
15853           else
15854             F.erase();
15855         }
15856       }
15857       F.done();
15858 
15859       // Diagnose this MSVC extension in the easy case where lookup would have
15860       // unambiguously found something outside the enclosing namespace.
15861       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15862         NamedDecl *ND = Previous.getFoundDecl();
15863         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15864             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15865       }
15866     }
15867 
15868     // Note:  there used to be some attempt at recovery here.
15869     if (Previous.isAmbiguous())
15870       return nullptr;
15871 
15872     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15873       // FIXME: This makes sure that we ignore the contexts associated
15874       // with C structs, unions, and enums when looking for a matching
15875       // tag declaration or definition. See the similar lookup tweak
15876       // in Sema::LookupName; is there a better way to deal with this?
15877       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15878         SearchDC = SearchDC->getParent();
15879     }
15880   }
15881 
15882   if (Previous.isSingleResult() &&
15883       Previous.getFoundDecl()->isTemplateParameter()) {
15884     // Maybe we will complain about the shadowed template parameter.
15885     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15886     // Just pretend that we didn't see the previous declaration.
15887     Previous.clear();
15888   }
15889 
15890   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15891       DC->Equals(getStdNamespace())) {
15892     if (Name->isStr("bad_alloc")) {
15893       // This is a declaration of or a reference to "std::bad_alloc".
15894       isStdBadAlloc = true;
15895 
15896       // If std::bad_alloc has been implicitly declared (but made invisible to
15897       // name lookup), fill in this implicit declaration as the previous
15898       // declaration, so that the declarations get chained appropriately.
15899       if (Previous.empty() && StdBadAlloc)
15900         Previous.addDecl(getStdBadAlloc());
15901     } else if (Name->isStr("align_val_t")) {
15902       isStdAlignValT = true;
15903       if (Previous.empty() && StdAlignValT)
15904         Previous.addDecl(getStdAlignValT());
15905     }
15906   }
15907 
15908   // If we didn't find a previous declaration, and this is a reference
15909   // (or friend reference), move to the correct scope.  In C++, we
15910   // also need to do a redeclaration lookup there, just in case
15911   // there's a shadow friend decl.
15912   if (Name && Previous.empty() &&
15913       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15914     if (Invalid) goto CreateNewDecl;
15915     assert(SS.isEmpty());
15916 
15917     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15918       // C++ [basic.scope.pdecl]p5:
15919       //   -- for an elaborated-type-specifier of the form
15920       //
15921       //          class-key identifier
15922       //
15923       //      if the elaborated-type-specifier is used in the
15924       //      decl-specifier-seq or parameter-declaration-clause of a
15925       //      function defined in namespace scope, the identifier is
15926       //      declared as a class-name in the namespace that contains
15927       //      the declaration; otherwise, except as a friend
15928       //      declaration, the identifier is declared in the smallest
15929       //      non-class, non-function-prototype scope that contains the
15930       //      declaration.
15931       //
15932       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15933       // C structs and unions.
15934       //
15935       // It is an error in C++ to declare (rather than define) an enum
15936       // type, including via an elaborated type specifier.  We'll
15937       // diagnose that later; for now, declare the enum in the same
15938       // scope as we would have picked for any other tag type.
15939       //
15940       // GNU C also supports this behavior as part of its incomplete
15941       // enum types extension, while GNU C++ does not.
15942       //
15943       // Find the context where we'll be declaring the tag.
15944       // FIXME: We would like to maintain the current DeclContext as the
15945       // lexical context,
15946       SearchDC = getTagInjectionContext(SearchDC);
15947 
15948       // Find the scope where we'll be declaring the tag.
15949       S = getTagInjectionScope(S, getLangOpts());
15950     } else {
15951       assert(TUK == TUK_Friend);
15952       // C++ [namespace.memdef]p3:
15953       //   If a friend declaration in a non-local class first declares a
15954       //   class or function, the friend class or function is a member of
15955       //   the innermost enclosing namespace.
15956       SearchDC = SearchDC->getEnclosingNamespaceContext();
15957     }
15958 
15959     // In C++, we need to do a redeclaration lookup to properly
15960     // diagnose some problems.
15961     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15962     // hidden declaration so that we don't get ambiguity errors when using a
15963     // type declared by an elaborated-type-specifier.  In C that is not correct
15964     // and we should instead merge compatible types found by lookup.
15965     if (getLangOpts().CPlusPlus) {
15966       // FIXME: This can perform qualified lookups into function contexts,
15967       // which are meaningless.
15968       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15969       LookupQualifiedName(Previous, SearchDC);
15970     } else {
15971       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15972       LookupName(Previous, S);
15973     }
15974   }
15975 
15976   // If we have a known previous declaration to use, then use it.
15977   if (Previous.empty() && SkipBody && SkipBody->Previous)
15978     Previous.addDecl(SkipBody->Previous);
15979 
15980   if (!Previous.empty()) {
15981     NamedDecl *PrevDecl = Previous.getFoundDecl();
15982     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15983 
15984     // It's okay to have a tag decl in the same scope as a typedef
15985     // which hides a tag decl in the same scope.  Finding this
15986     // insanity with a redeclaration lookup can only actually happen
15987     // in C++.
15988     //
15989     // This is also okay for elaborated-type-specifiers, which is
15990     // technically forbidden by the current standard but which is
15991     // okay according to the likely resolution of an open issue;
15992     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15993     if (getLangOpts().CPlusPlus) {
15994       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15995         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15996           TagDecl *Tag = TT->getDecl();
15997           if (Tag->getDeclName() == Name &&
15998               Tag->getDeclContext()->getRedeclContext()
15999                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16000             PrevDecl = Tag;
16001             Previous.clear();
16002             Previous.addDecl(Tag);
16003             Previous.resolveKind();
16004           }
16005         }
16006       }
16007     }
16008 
16009     // If this is a redeclaration of a using shadow declaration, it must
16010     // declare a tag in the same context. In MSVC mode, we allow a
16011     // redefinition if either context is within the other.
16012     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16013       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16014       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16015           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16016           !(OldTag && isAcceptableTagRedeclContext(
16017                           *this, OldTag->getDeclContext(), SearchDC))) {
16018         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16019         Diag(Shadow->getTargetDecl()->getLocation(),
16020              diag::note_using_decl_target);
16021         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
16022             << 0;
16023         // Recover by ignoring the old declaration.
16024         Previous.clear();
16025         goto CreateNewDecl;
16026       }
16027     }
16028 
16029     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16030       // If this is a use of a previous tag, or if the tag is already declared
16031       // in the same scope (so that the definition/declaration completes or
16032       // rementions the tag), reuse the decl.
16033       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16034           isDeclInScope(DirectPrevDecl, SearchDC, S,
16035                         SS.isNotEmpty() || isMemberSpecialization)) {
16036         // Make sure that this wasn't declared as an enum and now used as a
16037         // struct or something similar.
16038         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16039                                           TUK == TUK_Definition, KWLoc,
16040                                           Name)) {
16041           bool SafeToContinue
16042             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16043                Kind != TTK_Enum);
16044           if (SafeToContinue)
16045             Diag(KWLoc, diag::err_use_with_wrong_tag)
16046               << Name
16047               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16048                                               PrevTagDecl->getKindName());
16049           else
16050             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16051           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16052 
16053           if (SafeToContinue)
16054             Kind = PrevTagDecl->getTagKind();
16055           else {
16056             // Recover by making this an anonymous redefinition.
16057             Name = nullptr;
16058             Previous.clear();
16059             Invalid = true;
16060           }
16061         }
16062 
16063         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16064           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16065           if (TUK == TUK_Reference || TUK == TUK_Friend)
16066             return PrevTagDecl;
16067 
16068           QualType EnumUnderlyingTy;
16069           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16070             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16071           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16072             EnumUnderlyingTy = QualType(T, 0);
16073 
16074           // All conflicts with previous declarations are recovered by
16075           // returning the previous declaration, unless this is a definition,
16076           // in which case we want the caller to bail out.
16077           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16078                                      ScopedEnum, EnumUnderlyingTy,
16079                                      IsFixed, PrevEnum))
16080             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16081         }
16082 
16083         // C++11 [class.mem]p1:
16084         //   A member shall not be declared twice in the member-specification,
16085         //   except that a nested class or member class template can be declared
16086         //   and then later defined.
16087         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16088             S->isDeclScope(PrevDecl)) {
16089           Diag(NameLoc, diag::ext_member_redeclared);
16090           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16091         }
16092 
16093         if (!Invalid) {
16094           // If this is a use, just return the declaration we found, unless
16095           // we have attributes.
16096           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16097             if (!Attrs.empty()) {
16098               // FIXME: Diagnose these attributes. For now, we create a new
16099               // declaration to hold them.
16100             } else if (TUK == TUK_Reference &&
16101                        (PrevTagDecl->getFriendObjectKind() ==
16102                             Decl::FOK_Undeclared ||
16103                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16104                        SS.isEmpty()) {
16105               // This declaration is a reference to an existing entity, but
16106               // has different visibility from that entity: it either makes
16107               // a friend visible or it makes a type visible in a new module.
16108               // In either case, create a new declaration. We only do this if
16109               // the declaration would have meant the same thing if no prior
16110               // declaration were found, that is, if it was found in the same
16111               // scope where we would have injected a declaration.
16112               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16113                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16114                 return PrevTagDecl;
16115               // This is in the injected scope, create a new declaration in
16116               // that scope.
16117               S = getTagInjectionScope(S, getLangOpts());
16118             } else {
16119               return PrevTagDecl;
16120             }
16121           }
16122 
16123           // Diagnose attempts to redefine a tag.
16124           if (TUK == TUK_Definition) {
16125             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16126               // If we're defining a specialization and the previous definition
16127               // is from an implicit instantiation, don't emit an error
16128               // here; we'll catch this in the general case below.
16129               bool IsExplicitSpecializationAfterInstantiation = false;
16130               if (isMemberSpecialization) {
16131                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16132                   IsExplicitSpecializationAfterInstantiation =
16133                     RD->getTemplateSpecializationKind() !=
16134                     TSK_ExplicitSpecialization;
16135                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16136                   IsExplicitSpecializationAfterInstantiation =
16137                     ED->getTemplateSpecializationKind() !=
16138                     TSK_ExplicitSpecialization;
16139               }
16140 
16141               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16142               // not keep more that one definition around (merge them). However,
16143               // ensure the decl passes the structural compatibility check in
16144               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16145               NamedDecl *Hidden = nullptr;
16146               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16147                 // There is a definition of this tag, but it is not visible. We
16148                 // explicitly make use of C++'s one definition rule here, and
16149                 // assume that this definition is identical to the hidden one
16150                 // we already have. Make the existing definition visible and
16151                 // use it in place of this one.
16152                 if (!getLangOpts().CPlusPlus) {
16153                   // Postpone making the old definition visible until after we
16154                   // complete parsing the new one and do the structural
16155                   // comparison.
16156                   SkipBody->CheckSameAsPrevious = true;
16157                   SkipBody->New = createTagFromNewDecl();
16158                   SkipBody->Previous = Def;
16159                   return Def;
16160                 } else {
16161                   SkipBody->ShouldSkip = true;
16162                   SkipBody->Previous = Def;
16163                   makeMergedDefinitionVisible(Hidden);
16164                   // Carry on and handle it like a normal definition. We'll
16165                   // skip starting the definitiion later.
16166                 }
16167               } else if (!IsExplicitSpecializationAfterInstantiation) {
16168                 // A redeclaration in function prototype scope in C isn't
16169                 // visible elsewhere, so merely issue a warning.
16170                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16171                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16172                 else
16173                   Diag(NameLoc, diag::err_redefinition) << Name;
16174                 notePreviousDefinition(Def,
16175                                        NameLoc.isValid() ? NameLoc : KWLoc);
16176                 // If this is a redefinition, recover by making this
16177                 // struct be anonymous, which will make any later
16178                 // references get the previous definition.
16179                 Name = nullptr;
16180                 Previous.clear();
16181                 Invalid = true;
16182               }
16183             } else {
16184               // If the type is currently being defined, complain
16185               // about a nested redefinition.
16186               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16187               if (TD->isBeingDefined()) {
16188                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16189                 Diag(PrevTagDecl->getLocation(),
16190                      diag::note_previous_definition);
16191                 Name = nullptr;
16192                 Previous.clear();
16193                 Invalid = true;
16194               }
16195             }
16196 
16197             // Okay, this is definition of a previously declared or referenced
16198             // tag. We're going to create a new Decl for it.
16199           }
16200 
16201           // Okay, we're going to make a redeclaration.  If this is some kind
16202           // of reference, make sure we build the redeclaration in the same DC
16203           // as the original, and ignore the current access specifier.
16204           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16205             SearchDC = PrevTagDecl->getDeclContext();
16206             AS = AS_none;
16207           }
16208         }
16209         // If we get here we have (another) forward declaration or we
16210         // have a definition.  Just create a new decl.
16211 
16212       } else {
16213         // If we get here, this is a definition of a new tag type in a nested
16214         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16215         // new decl/type.  We set PrevDecl to NULL so that the entities
16216         // have distinct types.
16217         Previous.clear();
16218       }
16219       // If we get here, we're going to create a new Decl. If PrevDecl
16220       // is non-NULL, it's a definition of the tag declared by
16221       // PrevDecl. If it's NULL, we have a new definition.
16222 
16223     // Otherwise, PrevDecl is not a tag, but was found with tag
16224     // lookup.  This is only actually possible in C++, where a few
16225     // things like templates still live in the tag namespace.
16226     } else {
16227       // Use a better diagnostic if an elaborated-type-specifier
16228       // found the wrong kind of type on the first
16229       // (non-redeclaration) lookup.
16230       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16231           !Previous.isForRedeclaration()) {
16232         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16233         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16234                                                        << Kind;
16235         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16236         Invalid = true;
16237 
16238       // Otherwise, only diagnose if the declaration is in scope.
16239       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16240                                 SS.isNotEmpty() || isMemberSpecialization)) {
16241         // do nothing
16242 
16243       // Diagnose implicit declarations introduced by elaborated types.
16244       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16245         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16246         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16247         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16248         Invalid = true;
16249 
16250       // Otherwise it's a declaration.  Call out a particularly common
16251       // case here.
16252       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16253         unsigned Kind = 0;
16254         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16255         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16256           << Name << Kind << TND->getUnderlyingType();
16257         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16258         Invalid = true;
16259 
16260       // Otherwise, diagnose.
16261       } else {
16262         // The tag name clashes with something else in the target scope,
16263         // issue an error and recover by making this tag be anonymous.
16264         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16265         notePreviousDefinition(PrevDecl, NameLoc);
16266         Name = nullptr;
16267         Invalid = true;
16268       }
16269 
16270       // The existing declaration isn't relevant to us; we're in a
16271       // new scope, so clear out the previous declaration.
16272       Previous.clear();
16273     }
16274   }
16275 
16276 CreateNewDecl:
16277 
16278   TagDecl *PrevDecl = nullptr;
16279   if (Previous.isSingleResult())
16280     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16281 
16282   // If there is an identifier, use the location of the identifier as the
16283   // location of the decl, otherwise use the location of the struct/union
16284   // keyword.
16285   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16286 
16287   // Otherwise, create a new declaration. If there is a previous
16288   // declaration of the same entity, the two will be linked via
16289   // PrevDecl.
16290   TagDecl *New;
16291 
16292   if (Kind == TTK_Enum) {
16293     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16294     // enum X { A, B, C } D;    D should chain to X.
16295     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16296                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16297                            ScopedEnumUsesClassTag, IsFixed);
16298 
16299     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16300       StdAlignValT = cast<EnumDecl>(New);
16301 
16302     // If this is an undefined enum, warn.
16303     if (TUK != TUK_Definition && !Invalid) {
16304       TagDecl *Def;
16305       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16306         // C++0x: 7.2p2: opaque-enum-declaration.
16307         // Conflicts are diagnosed above. Do nothing.
16308       }
16309       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16310         Diag(Loc, diag::ext_forward_ref_enum_def)
16311           << New;
16312         Diag(Def->getLocation(), diag::note_previous_definition);
16313       } else {
16314         unsigned DiagID = diag::ext_forward_ref_enum;
16315         if (getLangOpts().MSVCCompat)
16316           DiagID = diag::ext_ms_forward_ref_enum;
16317         else if (getLangOpts().CPlusPlus)
16318           DiagID = diag::err_forward_ref_enum;
16319         Diag(Loc, DiagID);
16320       }
16321     }
16322 
16323     if (EnumUnderlying) {
16324       EnumDecl *ED = cast<EnumDecl>(New);
16325       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16326         ED->setIntegerTypeSourceInfo(TI);
16327       else
16328         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16329       ED->setPromotionType(ED->getIntegerType());
16330       assert(ED->isComplete() && "enum with type should be complete");
16331     }
16332   } else {
16333     // struct/union/class
16334 
16335     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16336     // struct X { int A; } D;    D should chain to X.
16337     if (getLangOpts().CPlusPlus) {
16338       // FIXME: Look for a way to use RecordDecl for simple structs.
16339       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16340                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16341 
16342       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16343         StdBadAlloc = cast<CXXRecordDecl>(New);
16344     } else
16345       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16346                                cast_or_null<RecordDecl>(PrevDecl));
16347   }
16348 
16349   // C++11 [dcl.type]p3:
16350   //   A type-specifier-seq shall not define a class or enumeration [...].
16351   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16352       TUK == TUK_Definition) {
16353     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16354       << Context.getTagDeclType(New);
16355     Invalid = true;
16356   }
16357 
16358   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16359       DC->getDeclKind() == Decl::Enum) {
16360     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16361       << Context.getTagDeclType(New);
16362     Invalid = true;
16363   }
16364 
16365   // Maybe add qualifier info.
16366   if (SS.isNotEmpty()) {
16367     if (SS.isSet()) {
16368       // If this is either a declaration or a definition, check the
16369       // nested-name-specifier against the current context.
16370       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16371           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16372                                        isMemberSpecialization))
16373         Invalid = true;
16374 
16375       New->setQualifierInfo(SS.getWithLocInContext(Context));
16376       if (TemplateParameterLists.size() > 0) {
16377         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16378       }
16379     }
16380     else
16381       Invalid = true;
16382   }
16383 
16384   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16385     // Add alignment attributes if necessary; these attributes are checked when
16386     // the ASTContext lays out the structure.
16387     //
16388     // It is important for implementing the correct semantics that this
16389     // happen here (in ActOnTag). The #pragma pack stack is
16390     // maintained as a result of parser callbacks which can occur at
16391     // many points during the parsing of a struct declaration (because
16392     // the #pragma tokens are effectively skipped over during the
16393     // parsing of the struct).
16394     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16395       AddAlignmentAttributesForRecord(RD);
16396       AddMsStructLayoutForRecord(RD);
16397     }
16398   }
16399 
16400   if (ModulePrivateLoc.isValid()) {
16401     if (isMemberSpecialization)
16402       Diag(New->getLocation(), diag::err_module_private_specialization)
16403         << 2
16404         << FixItHint::CreateRemoval(ModulePrivateLoc);
16405     // __module_private__ does not apply to local classes. However, we only
16406     // diagnose this as an error when the declaration specifiers are
16407     // freestanding. Here, we just ignore the __module_private__.
16408     else if (!SearchDC->isFunctionOrMethod())
16409       New->setModulePrivate();
16410   }
16411 
16412   // If this is a specialization of a member class (of a class template),
16413   // check the specialization.
16414   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16415     Invalid = true;
16416 
16417   // If we're declaring or defining a tag in function prototype scope in C,
16418   // note that this type can only be used within the function and add it to
16419   // the list of decls to inject into the function definition scope.
16420   if ((Name || Kind == TTK_Enum) &&
16421       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16422     if (getLangOpts().CPlusPlus) {
16423       // C++ [dcl.fct]p6:
16424       //   Types shall not be defined in return or parameter types.
16425       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16426         Diag(Loc, diag::err_type_defined_in_param_type)
16427             << Name;
16428         Invalid = true;
16429       }
16430     } else if (!PrevDecl) {
16431       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16432     }
16433   }
16434 
16435   if (Invalid)
16436     New->setInvalidDecl();
16437 
16438   // Set the lexical context. If the tag has a C++ scope specifier, the
16439   // lexical context will be different from the semantic context.
16440   New->setLexicalDeclContext(CurContext);
16441 
16442   // Mark this as a friend decl if applicable.
16443   // In Microsoft mode, a friend declaration also acts as a forward
16444   // declaration so we always pass true to setObjectOfFriendDecl to make
16445   // the tag name visible.
16446   if (TUK == TUK_Friend)
16447     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16448 
16449   // Set the access specifier.
16450   if (!Invalid && SearchDC->isRecord())
16451     SetMemberAccessSpecifier(New, PrevDecl, AS);
16452 
16453   if (PrevDecl)
16454     CheckRedeclarationModuleOwnership(New, PrevDecl);
16455 
16456   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16457     New->startDefinition();
16458 
16459   ProcessDeclAttributeList(S, New, Attrs);
16460   AddPragmaAttributes(S, New);
16461 
16462   // If this has an identifier, add it to the scope stack.
16463   if (TUK == TUK_Friend) {
16464     // We might be replacing an existing declaration in the lookup tables;
16465     // if so, borrow its access specifier.
16466     if (PrevDecl)
16467       New->setAccess(PrevDecl->getAccess());
16468 
16469     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16470     DC->makeDeclVisibleInContext(New);
16471     if (Name) // can be null along some error paths
16472       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16473         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16474   } else if (Name) {
16475     S = getNonFieldDeclScope(S);
16476     PushOnScopeChains(New, S, true);
16477   } else {
16478     CurContext->addDecl(New);
16479   }
16480 
16481   // If this is the C FILE type, notify the AST context.
16482   if (IdentifierInfo *II = New->getIdentifier())
16483     if (!New->isInvalidDecl() &&
16484         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16485         II->isStr("FILE"))
16486       Context.setFILEDecl(New);
16487 
16488   if (PrevDecl)
16489     mergeDeclAttributes(New, PrevDecl);
16490 
16491   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16492     inferGslOwnerPointerAttribute(CXXRD);
16493 
16494   // If there's a #pragma GCC visibility in scope, set the visibility of this
16495   // record.
16496   AddPushedVisibilityAttribute(New);
16497 
16498   if (isMemberSpecialization && !New->isInvalidDecl())
16499     CompleteMemberSpecialization(New, Previous);
16500 
16501   OwnedDecl = true;
16502   // In C++, don't return an invalid declaration. We can't recover well from
16503   // the cases where we make the type anonymous.
16504   if (Invalid && getLangOpts().CPlusPlus) {
16505     if (New->isBeingDefined())
16506       if (auto RD = dyn_cast<RecordDecl>(New))
16507         RD->completeDefinition();
16508     return nullptr;
16509   } else if (SkipBody && SkipBody->ShouldSkip) {
16510     return SkipBody->Previous;
16511   } else {
16512     return New;
16513   }
16514 }
16515 
16516 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16517   AdjustDeclIfTemplate(TagD);
16518   TagDecl *Tag = cast<TagDecl>(TagD);
16519 
16520   // Enter the tag context.
16521   PushDeclContext(S, Tag);
16522 
16523   ActOnDocumentableDecl(TagD);
16524 
16525   // If there's a #pragma GCC visibility in scope, set the visibility of this
16526   // record.
16527   AddPushedVisibilityAttribute(Tag);
16528 }
16529 
16530 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16531                                     SkipBodyInfo &SkipBody) {
16532   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16533     return false;
16534 
16535   // Make the previous decl visible.
16536   makeMergedDefinitionVisible(SkipBody.Previous);
16537   return true;
16538 }
16539 
16540 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16541   assert(isa<ObjCContainerDecl>(IDecl) &&
16542          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16543   DeclContext *OCD = cast<DeclContext>(IDecl);
16544   assert(OCD->getLexicalParent() == CurContext &&
16545       "The next DeclContext should be lexically contained in the current one.");
16546   CurContext = OCD;
16547   return IDecl;
16548 }
16549 
16550 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16551                                            SourceLocation FinalLoc,
16552                                            bool IsFinalSpelledSealed,
16553                                            SourceLocation LBraceLoc) {
16554   AdjustDeclIfTemplate(TagD);
16555   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16556 
16557   FieldCollector->StartClass();
16558 
16559   if (!Record->getIdentifier())
16560     return;
16561 
16562   if (FinalLoc.isValid())
16563     Record->addAttr(FinalAttr::Create(
16564         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16565         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16566 
16567   // C++ [class]p2:
16568   //   [...] The class-name is also inserted into the scope of the
16569   //   class itself; this is known as the injected-class-name. For
16570   //   purposes of access checking, the injected-class-name is treated
16571   //   as if it were a public member name.
16572   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16573       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16574       Record->getLocation(), Record->getIdentifier(),
16575       /*PrevDecl=*/nullptr,
16576       /*DelayTypeCreation=*/true);
16577   Context.getTypeDeclType(InjectedClassName, Record);
16578   InjectedClassName->setImplicit();
16579   InjectedClassName->setAccess(AS_public);
16580   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16581       InjectedClassName->setDescribedClassTemplate(Template);
16582   PushOnScopeChains(InjectedClassName, S);
16583   assert(InjectedClassName->isInjectedClassName() &&
16584          "Broken injected-class-name");
16585 }
16586 
16587 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16588                                     SourceRange BraceRange) {
16589   AdjustDeclIfTemplate(TagD);
16590   TagDecl *Tag = cast<TagDecl>(TagD);
16591   Tag->setBraceRange(BraceRange);
16592 
16593   // Make sure we "complete" the definition even it is invalid.
16594   if (Tag->isBeingDefined()) {
16595     assert(Tag->isInvalidDecl() && "We should already have completed it");
16596     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16597       RD->completeDefinition();
16598   }
16599 
16600   if (isa<CXXRecordDecl>(Tag)) {
16601     FieldCollector->FinishClass();
16602   }
16603 
16604   // Exit this scope of this tag's definition.
16605   PopDeclContext();
16606 
16607   if (getCurLexicalContext()->isObjCContainer() &&
16608       Tag->getDeclContext()->isFileContext())
16609     Tag->setTopLevelDeclInObjCContainer();
16610 
16611   // Notify the consumer that we've defined a tag.
16612   if (!Tag->isInvalidDecl())
16613     Consumer.HandleTagDeclDefinition(Tag);
16614 }
16615 
16616 void Sema::ActOnObjCContainerFinishDefinition() {
16617   // Exit this scope of this interface definition.
16618   PopDeclContext();
16619 }
16620 
16621 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16622   assert(DC == CurContext && "Mismatch of container contexts");
16623   OriginalLexicalContext = DC;
16624   ActOnObjCContainerFinishDefinition();
16625 }
16626 
16627 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16628   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16629   OriginalLexicalContext = nullptr;
16630 }
16631 
16632 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16633   AdjustDeclIfTemplate(TagD);
16634   TagDecl *Tag = cast<TagDecl>(TagD);
16635   Tag->setInvalidDecl();
16636 
16637   // Make sure we "complete" the definition even it is invalid.
16638   if (Tag->isBeingDefined()) {
16639     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16640       RD->completeDefinition();
16641   }
16642 
16643   // We're undoing ActOnTagStartDefinition here, not
16644   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16645   // the FieldCollector.
16646 
16647   PopDeclContext();
16648 }
16649 
16650 // Note that FieldName may be null for anonymous bitfields.
16651 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16652                                 IdentifierInfo *FieldName,
16653                                 QualType FieldTy, bool IsMsStruct,
16654                                 Expr *BitWidth, bool *ZeroWidth) {
16655   assert(BitWidth);
16656   if (BitWidth->containsErrors())
16657     return ExprError();
16658 
16659   // Default to true; that shouldn't confuse checks for emptiness
16660   if (ZeroWidth)
16661     *ZeroWidth = true;
16662 
16663   // C99 6.7.2.1p4 - verify the field type.
16664   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16665   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16666     // Handle incomplete and sizeless types with a specific error.
16667     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16668                                  diag::err_field_incomplete_or_sizeless))
16669       return ExprError();
16670     if (FieldName)
16671       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16672         << FieldName << FieldTy << BitWidth->getSourceRange();
16673     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16674       << FieldTy << BitWidth->getSourceRange();
16675   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16676                                              UPPC_BitFieldWidth))
16677     return ExprError();
16678 
16679   // If the bit-width is type- or value-dependent, don't try to check
16680   // it now.
16681   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16682     return BitWidth;
16683 
16684   llvm::APSInt Value;
16685   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16686   if (ICE.isInvalid())
16687     return ICE;
16688   BitWidth = ICE.get();
16689 
16690   if (Value != 0 && ZeroWidth)
16691     *ZeroWidth = false;
16692 
16693   // Zero-width bitfield is ok for anonymous field.
16694   if (Value == 0 && FieldName)
16695     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16696 
16697   if (Value.isSigned() && Value.isNegative()) {
16698     if (FieldName)
16699       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16700                << FieldName << Value.toString(10);
16701     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16702       << Value.toString(10);
16703   }
16704 
16705   // The size of the bit-field must not exceed our maximum permitted object
16706   // size.
16707   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16708     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16709            << !FieldName << FieldName << Value.toString(10);
16710   }
16711 
16712   if (!FieldTy->isDependentType()) {
16713     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16714     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16715     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16716 
16717     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16718     // ABI.
16719     bool CStdConstraintViolation =
16720         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16721     bool MSBitfieldViolation =
16722         Value.ugt(TypeStorageSize) &&
16723         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16724     if (CStdConstraintViolation || MSBitfieldViolation) {
16725       unsigned DiagWidth =
16726           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16727       if (FieldName)
16728         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16729                << FieldName << Value.toString(10)
16730                << !CStdConstraintViolation << DiagWidth;
16731 
16732       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16733              << Value.toString(10) << !CStdConstraintViolation
16734              << DiagWidth;
16735     }
16736 
16737     // Warn on types where the user might conceivably expect to get all
16738     // specified bits as value bits: that's all integral types other than
16739     // 'bool'.
16740     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16741       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16742           << FieldName << Value.toString(10)
16743           << (unsigned)TypeWidth;
16744     }
16745   }
16746 
16747   return BitWidth;
16748 }
16749 
16750 /// ActOnField - Each field of a C struct/union is passed into this in order
16751 /// to create a FieldDecl object for it.
16752 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16753                        Declarator &D, Expr *BitfieldWidth) {
16754   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16755                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16756                                /*InitStyle=*/ICIS_NoInit, AS_public);
16757   return Res;
16758 }
16759 
16760 /// HandleField - Analyze a field of a C struct or a C++ data member.
16761 ///
16762 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16763                              SourceLocation DeclStart,
16764                              Declarator &D, Expr *BitWidth,
16765                              InClassInitStyle InitStyle,
16766                              AccessSpecifier AS) {
16767   if (D.isDecompositionDeclarator()) {
16768     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16769     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16770       << Decomp.getSourceRange();
16771     return nullptr;
16772   }
16773 
16774   IdentifierInfo *II = D.getIdentifier();
16775   SourceLocation Loc = DeclStart;
16776   if (II) Loc = D.getIdentifierLoc();
16777 
16778   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16779   QualType T = TInfo->getType();
16780   if (getLangOpts().CPlusPlus) {
16781     CheckExtraCXXDefaultArguments(D);
16782 
16783     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16784                                         UPPC_DataMemberType)) {
16785       D.setInvalidType();
16786       T = Context.IntTy;
16787       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16788     }
16789   }
16790 
16791   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16792 
16793   if (D.getDeclSpec().isInlineSpecified())
16794     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16795         << getLangOpts().CPlusPlus17;
16796   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16797     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16798          diag::err_invalid_thread)
16799       << DeclSpec::getSpecifierName(TSCS);
16800 
16801   // Check to see if this name was declared as a member previously
16802   NamedDecl *PrevDecl = nullptr;
16803   LookupResult Previous(*this, II, Loc, LookupMemberName,
16804                         ForVisibleRedeclaration);
16805   LookupName(Previous, S);
16806   switch (Previous.getResultKind()) {
16807     case LookupResult::Found:
16808     case LookupResult::FoundUnresolvedValue:
16809       PrevDecl = Previous.getAsSingle<NamedDecl>();
16810       break;
16811 
16812     case LookupResult::FoundOverloaded:
16813       PrevDecl = Previous.getRepresentativeDecl();
16814       break;
16815 
16816     case LookupResult::NotFound:
16817     case LookupResult::NotFoundInCurrentInstantiation:
16818     case LookupResult::Ambiguous:
16819       break;
16820   }
16821   Previous.suppressDiagnostics();
16822 
16823   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16824     // Maybe we will complain about the shadowed template parameter.
16825     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16826     // Just pretend that we didn't see the previous declaration.
16827     PrevDecl = nullptr;
16828   }
16829 
16830   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16831     PrevDecl = nullptr;
16832 
16833   bool Mutable
16834     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16835   SourceLocation TSSL = D.getBeginLoc();
16836   FieldDecl *NewFD
16837     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16838                      TSSL, AS, PrevDecl, &D);
16839 
16840   if (NewFD->isInvalidDecl())
16841     Record->setInvalidDecl();
16842 
16843   if (D.getDeclSpec().isModulePrivateSpecified())
16844     NewFD->setModulePrivate();
16845 
16846   if (NewFD->isInvalidDecl() && PrevDecl) {
16847     // Don't introduce NewFD into scope; there's already something
16848     // with the same name in the same scope.
16849   } else if (II) {
16850     PushOnScopeChains(NewFD, S);
16851   } else
16852     Record->addDecl(NewFD);
16853 
16854   return NewFD;
16855 }
16856 
16857 /// Build a new FieldDecl and check its well-formedness.
16858 ///
16859 /// This routine builds a new FieldDecl given the fields name, type,
16860 /// record, etc. \p PrevDecl should refer to any previous declaration
16861 /// with the same name and in the same scope as the field to be
16862 /// created.
16863 ///
16864 /// \returns a new FieldDecl.
16865 ///
16866 /// \todo The Declarator argument is a hack. It will be removed once
16867 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16868                                 TypeSourceInfo *TInfo,
16869                                 RecordDecl *Record, SourceLocation Loc,
16870                                 bool Mutable, Expr *BitWidth,
16871                                 InClassInitStyle InitStyle,
16872                                 SourceLocation TSSL,
16873                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16874                                 Declarator *D) {
16875   IdentifierInfo *II = Name.getAsIdentifierInfo();
16876   bool InvalidDecl = false;
16877   if (D) InvalidDecl = D->isInvalidType();
16878 
16879   // If we receive a broken type, recover by assuming 'int' and
16880   // marking this declaration as invalid.
16881   if (T.isNull() || T->containsErrors()) {
16882     InvalidDecl = true;
16883     T = Context.IntTy;
16884   }
16885 
16886   QualType EltTy = Context.getBaseElementType(T);
16887   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16888     if (RequireCompleteSizedType(Loc, EltTy,
16889                                  diag::err_field_incomplete_or_sizeless)) {
16890       // Fields of incomplete type force their record to be invalid.
16891       Record->setInvalidDecl();
16892       InvalidDecl = true;
16893     } else {
16894       NamedDecl *Def;
16895       EltTy->isIncompleteType(&Def);
16896       if (Def && Def->isInvalidDecl()) {
16897         Record->setInvalidDecl();
16898         InvalidDecl = true;
16899       }
16900     }
16901   }
16902 
16903   // TR 18037 does not allow fields to be declared with address space
16904   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16905       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16906     Diag(Loc, diag::err_field_with_address_space);
16907     Record->setInvalidDecl();
16908     InvalidDecl = true;
16909   }
16910 
16911   if (LangOpts.OpenCL) {
16912     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16913     // used as structure or union field: image, sampler, event or block types.
16914     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16915         T->isBlockPointerType()) {
16916       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16917       Record->setInvalidDecl();
16918       InvalidDecl = true;
16919     }
16920     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16921     if (BitWidth) {
16922       Diag(Loc, diag::err_opencl_bitfields);
16923       InvalidDecl = true;
16924     }
16925   }
16926 
16927   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16928   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16929       T.hasQualifiers()) {
16930     InvalidDecl = true;
16931     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16932   }
16933 
16934   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16935   // than a variably modified type.
16936   if (!InvalidDecl && T->isVariablyModifiedType()) {
16937     if (!tryToFixVariablyModifiedVarType(
16938             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16939       InvalidDecl = true;
16940   }
16941 
16942   // Fields can not have abstract class types
16943   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16944                                              diag::err_abstract_type_in_decl,
16945                                              AbstractFieldType))
16946     InvalidDecl = true;
16947 
16948   bool ZeroWidth = false;
16949   if (InvalidDecl)
16950     BitWidth = nullptr;
16951   // If this is declared as a bit-field, check the bit-field.
16952   if (BitWidth) {
16953     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16954                               &ZeroWidth).get();
16955     if (!BitWidth) {
16956       InvalidDecl = true;
16957       BitWidth = nullptr;
16958       ZeroWidth = false;
16959     }
16960   }
16961 
16962   // Check that 'mutable' is consistent with the type of the declaration.
16963   if (!InvalidDecl && Mutable) {
16964     unsigned DiagID = 0;
16965     if (T->isReferenceType())
16966       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16967                                         : diag::err_mutable_reference;
16968     else if (T.isConstQualified())
16969       DiagID = diag::err_mutable_const;
16970 
16971     if (DiagID) {
16972       SourceLocation ErrLoc = Loc;
16973       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16974         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16975       Diag(ErrLoc, DiagID);
16976       if (DiagID != diag::ext_mutable_reference) {
16977         Mutable = false;
16978         InvalidDecl = true;
16979       }
16980     }
16981   }
16982 
16983   // C++11 [class.union]p8 (DR1460):
16984   //   At most one variant member of a union may have a
16985   //   brace-or-equal-initializer.
16986   if (InitStyle != ICIS_NoInit)
16987     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16988 
16989   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16990                                        BitWidth, Mutable, InitStyle);
16991   if (InvalidDecl)
16992     NewFD->setInvalidDecl();
16993 
16994   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16995     Diag(Loc, diag::err_duplicate_member) << II;
16996     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16997     NewFD->setInvalidDecl();
16998   }
16999 
17000   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17001     if (Record->isUnion()) {
17002       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17003         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17004         if (RDecl->getDefinition()) {
17005           // C++ [class.union]p1: An object of a class with a non-trivial
17006           // constructor, a non-trivial copy constructor, a non-trivial
17007           // destructor, or a non-trivial copy assignment operator
17008           // cannot be a member of a union, nor can an array of such
17009           // objects.
17010           if (CheckNontrivialField(NewFD))
17011             NewFD->setInvalidDecl();
17012         }
17013       }
17014 
17015       // C++ [class.union]p1: If a union contains a member of reference type,
17016       // the program is ill-formed, except when compiling with MSVC extensions
17017       // enabled.
17018       if (EltTy->isReferenceType()) {
17019         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17020                                     diag::ext_union_member_of_reference_type :
17021                                     diag::err_union_member_of_reference_type)
17022           << NewFD->getDeclName() << EltTy;
17023         if (!getLangOpts().MicrosoftExt)
17024           NewFD->setInvalidDecl();
17025       }
17026     }
17027   }
17028 
17029   // FIXME: We need to pass in the attributes given an AST
17030   // representation, not a parser representation.
17031   if (D) {
17032     // FIXME: The current scope is almost... but not entirely... correct here.
17033     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17034 
17035     if (NewFD->hasAttrs())
17036       CheckAlignasUnderalignment(NewFD);
17037   }
17038 
17039   // In auto-retain/release, infer strong retension for fields of
17040   // retainable type.
17041   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17042     NewFD->setInvalidDecl();
17043 
17044   if (T.isObjCGCWeak())
17045     Diag(Loc, diag::warn_attribute_weak_on_field);
17046 
17047   // PPC MMA non-pointer types are not allowed as field types.
17048   if (Context.getTargetInfo().getTriple().isPPC64() &&
17049       CheckPPCMMAType(T, NewFD->getLocation()))
17050     NewFD->setInvalidDecl();
17051 
17052   NewFD->setAccess(AS);
17053   return NewFD;
17054 }
17055 
17056 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17057   assert(FD);
17058   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17059 
17060   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17061     return false;
17062 
17063   QualType EltTy = Context.getBaseElementType(FD->getType());
17064   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17065     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17066     if (RDecl->getDefinition()) {
17067       // We check for copy constructors before constructors
17068       // because otherwise we'll never get complaints about
17069       // copy constructors.
17070 
17071       CXXSpecialMember member = CXXInvalid;
17072       // We're required to check for any non-trivial constructors. Since the
17073       // implicit default constructor is suppressed if there are any
17074       // user-declared constructors, we just need to check that there is a
17075       // trivial default constructor and a trivial copy constructor. (We don't
17076       // worry about move constructors here, since this is a C++98 check.)
17077       if (RDecl->hasNonTrivialCopyConstructor())
17078         member = CXXCopyConstructor;
17079       else if (!RDecl->hasTrivialDefaultConstructor())
17080         member = CXXDefaultConstructor;
17081       else if (RDecl->hasNonTrivialCopyAssignment())
17082         member = CXXCopyAssignment;
17083       else if (RDecl->hasNonTrivialDestructor())
17084         member = CXXDestructor;
17085 
17086       if (member != CXXInvalid) {
17087         if (!getLangOpts().CPlusPlus11 &&
17088             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17089           // Objective-C++ ARC: it is an error to have a non-trivial field of
17090           // a union. However, system headers in Objective-C programs
17091           // occasionally have Objective-C lifetime objects within unions,
17092           // and rather than cause the program to fail, we make those
17093           // members unavailable.
17094           SourceLocation Loc = FD->getLocation();
17095           if (getSourceManager().isInSystemHeader(Loc)) {
17096             if (!FD->hasAttr<UnavailableAttr>())
17097               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17098                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17099             return false;
17100           }
17101         }
17102 
17103         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17104                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17105                diag::err_illegal_union_or_anon_struct_member)
17106           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17107         DiagnoseNontrivial(RDecl, member);
17108         return !getLangOpts().CPlusPlus11;
17109       }
17110     }
17111   }
17112 
17113   return false;
17114 }
17115 
17116 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17117 ///  AST enum value.
17118 static ObjCIvarDecl::AccessControl
17119 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17120   switch (ivarVisibility) {
17121   default: llvm_unreachable("Unknown visitibility kind");
17122   case tok::objc_private: return ObjCIvarDecl::Private;
17123   case tok::objc_public: return ObjCIvarDecl::Public;
17124   case tok::objc_protected: return ObjCIvarDecl::Protected;
17125   case tok::objc_package: return ObjCIvarDecl::Package;
17126   }
17127 }
17128 
17129 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17130 /// in order to create an IvarDecl object for it.
17131 Decl *Sema::ActOnIvar(Scope *S,
17132                                 SourceLocation DeclStart,
17133                                 Declarator &D, Expr *BitfieldWidth,
17134                                 tok::ObjCKeywordKind Visibility) {
17135 
17136   IdentifierInfo *II = D.getIdentifier();
17137   Expr *BitWidth = (Expr*)BitfieldWidth;
17138   SourceLocation Loc = DeclStart;
17139   if (II) Loc = D.getIdentifierLoc();
17140 
17141   // FIXME: Unnamed fields can be handled in various different ways, for
17142   // example, unnamed unions inject all members into the struct namespace!
17143 
17144   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17145   QualType T = TInfo->getType();
17146 
17147   if (BitWidth) {
17148     // 6.7.2.1p3, 6.7.2.1p4
17149     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17150     if (!BitWidth)
17151       D.setInvalidType();
17152   } else {
17153     // Not a bitfield.
17154 
17155     // validate II.
17156 
17157   }
17158   if (T->isReferenceType()) {
17159     Diag(Loc, diag::err_ivar_reference_type);
17160     D.setInvalidType();
17161   }
17162   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17163   // than a variably modified type.
17164   else if (T->isVariablyModifiedType()) {
17165     if (!tryToFixVariablyModifiedVarType(
17166             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17167       D.setInvalidType();
17168   }
17169 
17170   // Get the visibility (access control) for this ivar.
17171   ObjCIvarDecl::AccessControl ac =
17172     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17173                                         : ObjCIvarDecl::None;
17174   // Must set ivar's DeclContext to its enclosing interface.
17175   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17176   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17177     return nullptr;
17178   ObjCContainerDecl *EnclosingContext;
17179   if (ObjCImplementationDecl *IMPDecl =
17180       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17181     if (LangOpts.ObjCRuntime.isFragile()) {
17182     // Case of ivar declared in an implementation. Context is that of its class.
17183       EnclosingContext = IMPDecl->getClassInterface();
17184       assert(EnclosingContext && "Implementation has no class interface!");
17185     }
17186     else
17187       EnclosingContext = EnclosingDecl;
17188   } else {
17189     if (ObjCCategoryDecl *CDecl =
17190         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17191       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17192         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17193         return nullptr;
17194       }
17195     }
17196     EnclosingContext = EnclosingDecl;
17197   }
17198 
17199   // Construct the decl.
17200   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17201                                              DeclStart, Loc, II, T,
17202                                              TInfo, ac, (Expr *)BitfieldWidth);
17203 
17204   if (II) {
17205     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17206                                            ForVisibleRedeclaration);
17207     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17208         && !isa<TagDecl>(PrevDecl)) {
17209       Diag(Loc, diag::err_duplicate_member) << II;
17210       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17211       NewID->setInvalidDecl();
17212     }
17213   }
17214 
17215   // Process attributes attached to the ivar.
17216   ProcessDeclAttributes(S, NewID, D);
17217 
17218   if (D.isInvalidType())
17219     NewID->setInvalidDecl();
17220 
17221   // In ARC, infer 'retaining' for ivars of retainable type.
17222   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17223     NewID->setInvalidDecl();
17224 
17225   if (D.getDeclSpec().isModulePrivateSpecified())
17226     NewID->setModulePrivate();
17227 
17228   if (II) {
17229     // FIXME: When interfaces are DeclContexts, we'll need to add
17230     // these to the interface.
17231     S->AddDecl(NewID);
17232     IdResolver.AddDecl(NewID);
17233   }
17234 
17235   if (LangOpts.ObjCRuntime.isNonFragile() &&
17236       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17237     Diag(Loc, diag::warn_ivars_in_interface);
17238 
17239   return NewID;
17240 }
17241 
17242 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17243 /// class and class extensions. For every class \@interface and class
17244 /// extension \@interface, if the last ivar is a bitfield of any type,
17245 /// then add an implicit `char :0` ivar to the end of that interface.
17246 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17247                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17248   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17249     return;
17250 
17251   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17252   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17253 
17254   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17255     return;
17256   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17257   if (!ID) {
17258     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17259       if (!CD->IsClassExtension())
17260         return;
17261     }
17262     // No need to add this to end of @implementation.
17263     else
17264       return;
17265   }
17266   // All conditions are met. Add a new bitfield to the tail end of ivars.
17267   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17268   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17269 
17270   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17271                               DeclLoc, DeclLoc, nullptr,
17272                               Context.CharTy,
17273                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17274                                                                DeclLoc),
17275                               ObjCIvarDecl::Private, BW,
17276                               true);
17277   AllIvarDecls.push_back(Ivar);
17278 }
17279 
17280 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17281                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17282                        SourceLocation RBrac,
17283                        const ParsedAttributesView &Attrs) {
17284   assert(EnclosingDecl && "missing record or interface decl");
17285 
17286   // If this is an Objective-C @implementation or category and we have
17287   // new fields here we should reset the layout of the interface since
17288   // it will now change.
17289   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17290     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17291     switch (DC->getKind()) {
17292     default: break;
17293     case Decl::ObjCCategory:
17294       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17295       break;
17296     case Decl::ObjCImplementation:
17297       Context.
17298         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17299       break;
17300     }
17301   }
17302 
17303   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17304   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17305 
17306   // Start counting up the number of named members; make sure to include
17307   // members of anonymous structs and unions in the total.
17308   unsigned NumNamedMembers = 0;
17309   if (Record) {
17310     for (const auto *I : Record->decls()) {
17311       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17312         if (IFD->getDeclName())
17313           ++NumNamedMembers;
17314     }
17315   }
17316 
17317   // Verify that all the fields are okay.
17318   SmallVector<FieldDecl*, 32> RecFields;
17319 
17320   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17321        i != end; ++i) {
17322     FieldDecl *FD = cast<FieldDecl>(*i);
17323 
17324     // Get the type for the field.
17325     const Type *FDTy = FD->getType().getTypePtr();
17326 
17327     if (!FD->isAnonymousStructOrUnion()) {
17328       // Remember all fields written by the user.
17329       RecFields.push_back(FD);
17330     }
17331 
17332     // If the field is already invalid for some reason, don't emit more
17333     // diagnostics about it.
17334     if (FD->isInvalidDecl()) {
17335       EnclosingDecl->setInvalidDecl();
17336       continue;
17337     }
17338 
17339     // C99 6.7.2.1p2:
17340     //   A structure or union shall not contain a member with
17341     //   incomplete or function type (hence, a structure shall not
17342     //   contain an instance of itself, but may contain a pointer to
17343     //   an instance of itself), except that the last member of a
17344     //   structure with more than one named member may have incomplete
17345     //   array type; such a structure (and any union containing,
17346     //   possibly recursively, a member that is such a structure)
17347     //   shall not be a member of a structure or an element of an
17348     //   array.
17349     bool IsLastField = (i + 1 == Fields.end());
17350     if (FDTy->isFunctionType()) {
17351       // Field declared as a function.
17352       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17353         << FD->getDeclName();
17354       FD->setInvalidDecl();
17355       EnclosingDecl->setInvalidDecl();
17356       continue;
17357     } else if (FDTy->isIncompleteArrayType() &&
17358                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17359       if (Record) {
17360         // Flexible array member.
17361         // Microsoft and g++ is more permissive regarding flexible array.
17362         // It will accept flexible array in union and also
17363         // as the sole element of a struct/class.
17364         unsigned DiagID = 0;
17365         if (!Record->isUnion() && !IsLastField) {
17366           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17367             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17368           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17369           FD->setInvalidDecl();
17370           EnclosingDecl->setInvalidDecl();
17371           continue;
17372         } else if (Record->isUnion())
17373           DiagID = getLangOpts().MicrosoftExt
17374                        ? diag::ext_flexible_array_union_ms
17375                        : getLangOpts().CPlusPlus
17376                              ? diag::ext_flexible_array_union_gnu
17377                              : diag::err_flexible_array_union;
17378         else if (NumNamedMembers < 1)
17379           DiagID = getLangOpts().MicrosoftExt
17380                        ? diag::ext_flexible_array_empty_aggregate_ms
17381                        : getLangOpts().CPlusPlus
17382                              ? diag::ext_flexible_array_empty_aggregate_gnu
17383                              : diag::err_flexible_array_empty_aggregate;
17384 
17385         if (DiagID)
17386           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17387                                           << Record->getTagKind();
17388         // While the layout of types that contain virtual bases is not specified
17389         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17390         // virtual bases after the derived members.  This would make a flexible
17391         // array member declared at the end of an object not adjacent to the end
17392         // of the type.
17393         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17394           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17395               << FD->getDeclName() << Record->getTagKind();
17396         if (!getLangOpts().C99)
17397           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17398             << FD->getDeclName() << Record->getTagKind();
17399 
17400         // If the element type has a non-trivial destructor, we would not
17401         // implicitly destroy the elements, so disallow it for now.
17402         //
17403         // FIXME: GCC allows this. We should probably either implicitly delete
17404         // the destructor of the containing class, or just allow this.
17405         QualType BaseElem = Context.getBaseElementType(FD->getType());
17406         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17407           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17408             << FD->getDeclName() << FD->getType();
17409           FD->setInvalidDecl();
17410           EnclosingDecl->setInvalidDecl();
17411           continue;
17412         }
17413         // Okay, we have a legal flexible array member at the end of the struct.
17414         Record->setHasFlexibleArrayMember(true);
17415       } else {
17416         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17417         // unless they are followed by another ivar. That check is done
17418         // elsewhere, after synthesized ivars are known.
17419       }
17420     } else if (!FDTy->isDependentType() &&
17421                RequireCompleteSizedType(
17422                    FD->getLocation(), FD->getType(),
17423                    diag::err_field_incomplete_or_sizeless)) {
17424       // Incomplete type
17425       FD->setInvalidDecl();
17426       EnclosingDecl->setInvalidDecl();
17427       continue;
17428     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17429       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17430         // A type which contains a flexible array member is considered to be a
17431         // flexible array member.
17432         Record->setHasFlexibleArrayMember(true);
17433         if (!Record->isUnion()) {
17434           // If this is a struct/class and this is not the last element, reject
17435           // it.  Note that GCC supports variable sized arrays in the middle of
17436           // structures.
17437           if (!IsLastField)
17438             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17439               << FD->getDeclName() << FD->getType();
17440           else {
17441             // We support flexible arrays at the end of structs in
17442             // other structs as an extension.
17443             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17444               << FD->getDeclName();
17445           }
17446         }
17447       }
17448       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17449           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17450                                  diag::err_abstract_type_in_decl,
17451                                  AbstractIvarType)) {
17452         // Ivars can not have abstract class types
17453         FD->setInvalidDecl();
17454       }
17455       if (Record && FDTTy->getDecl()->hasObjectMember())
17456         Record->setHasObjectMember(true);
17457       if (Record && FDTTy->getDecl()->hasVolatileMember())
17458         Record->setHasVolatileMember(true);
17459     } else if (FDTy->isObjCObjectType()) {
17460       /// A field cannot be an Objective-c object
17461       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17462         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17463       QualType T = Context.getObjCObjectPointerType(FD->getType());
17464       FD->setType(T);
17465     } else if (Record && Record->isUnion() &&
17466                FD->getType().hasNonTrivialObjCLifetime() &&
17467                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17468                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17469                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17470                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17471       // For backward compatibility, fields of C unions declared in system
17472       // headers that have non-trivial ObjC ownership qualifications are marked
17473       // as unavailable unless the qualifier is explicit and __strong. This can
17474       // break ABI compatibility between programs compiled with ARC and MRR, but
17475       // is a better option than rejecting programs using those unions under
17476       // ARC.
17477       FD->addAttr(UnavailableAttr::CreateImplicit(
17478           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17479           FD->getLocation()));
17480     } else if (getLangOpts().ObjC &&
17481                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17482                !Record->hasObjectMember()) {
17483       if (FD->getType()->isObjCObjectPointerType() ||
17484           FD->getType().isObjCGCStrong())
17485         Record->setHasObjectMember(true);
17486       else if (Context.getAsArrayType(FD->getType())) {
17487         QualType BaseType = Context.getBaseElementType(FD->getType());
17488         if (BaseType->isRecordType() &&
17489             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17490           Record->setHasObjectMember(true);
17491         else if (BaseType->isObjCObjectPointerType() ||
17492                  BaseType.isObjCGCStrong())
17493                Record->setHasObjectMember(true);
17494       }
17495     }
17496 
17497     if (Record && !getLangOpts().CPlusPlus &&
17498         !shouldIgnoreForRecordTriviality(FD)) {
17499       QualType FT = FD->getType();
17500       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17501         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17502         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17503             Record->isUnion())
17504           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17505       }
17506       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17507       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17508         Record->setNonTrivialToPrimitiveCopy(true);
17509         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17510           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17511       }
17512       if (FT.isDestructedType()) {
17513         Record->setNonTrivialToPrimitiveDestroy(true);
17514         Record->setParamDestroyedInCallee(true);
17515         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17516           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17517       }
17518 
17519       if (const auto *RT = FT->getAs<RecordType>()) {
17520         if (RT->getDecl()->getArgPassingRestrictions() ==
17521             RecordDecl::APK_CanNeverPassInRegs)
17522           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17523       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17524         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17525     }
17526 
17527     if (Record && FD->getType().isVolatileQualified())
17528       Record->setHasVolatileMember(true);
17529     // Keep track of the number of named members.
17530     if (FD->getIdentifier())
17531       ++NumNamedMembers;
17532   }
17533 
17534   // Okay, we successfully defined 'Record'.
17535   if (Record) {
17536     bool Completed = false;
17537     if (CXXRecord) {
17538       if (!CXXRecord->isInvalidDecl()) {
17539         // Set access bits correctly on the directly-declared conversions.
17540         for (CXXRecordDecl::conversion_iterator
17541                I = CXXRecord->conversion_begin(),
17542                E = CXXRecord->conversion_end(); I != E; ++I)
17543           I.setAccess((*I)->getAccess());
17544       }
17545 
17546       // Add any implicitly-declared members to this class.
17547       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17548 
17549       if (!CXXRecord->isDependentType()) {
17550         if (!CXXRecord->isInvalidDecl()) {
17551           // If we have virtual base classes, we may end up finding multiple
17552           // final overriders for a given virtual function. Check for this
17553           // problem now.
17554           if (CXXRecord->getNumVBases()) {
17555             CXXFinalOverriderMap FinalOverriders;
17556             CXXRecord->getFinalOverriders(FinalOverriders);
17557 
17558             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17559                                              MEnd = FinalOverriders.end();
17560                  M != MEnd; ++M) {
17561               for (OverridingMethods::iterator SO = M->second.begin(),
17562                                             SOEnd = M->second.end();
17563                    SO != SOEnd; ++SO) {
17564                 assert(SO->second.size() > 0 &&
17565                        "Virtual function without overriding functions?");
17566                 if (SO->second.size() == 1)
17567                   continue;
17568 
17569                 // C++ [class.virtual]p2:
17570                 //   In a derived class, if a virtual member function of a base
17571                 //   class subobject has more than one final overrider the
17572                 //   program is ill-formed.
17573                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17574                   << (const NamedDecl *)M->first << Record;
17575                 Diag(M->first->getLocation(),
17576                      diag::note_overridden_virtual_function);
17577                 for (OverridingMethods::overriding_iterator
17578                           OM = SO->second.begin(),
17579                        OMEnd = SO->second.end();
17580                      OM != OMEnd; ++OM)
17581                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17582                     << (const NamedDecl *)M->first << OM->Method->getParent();
17583 
17584                 Record->setInvalidDecl();
17585               }
17586             }
17587             CXXRecord->completeDefinition(&FinalOverriders);
17588             Completed = true;
17589           }
17590         }
17591       }
17592     }
17593 
17594     if (!Completed)
17595       Record->completeDefinition();
17596 
17597     // Handle attributes before checking the layout.
17598     ProcessDeclAttributeList(S, Record, Attrs);
17599 
17600     // We may have deferred checking for a deleted destructor. Check now.
17601     if (CXXRecord) {
17602       auto *Dtor = CXXRecord->getDestructor();
17603       if (Dtor && Dtor->isImplicit() &&
17604           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17605         CXXRecord->setImplicitDestructorIsDeleted();
17606         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17607       }
17608     }
17609 
17610     if (Record->hasAttrs()) {
17611       CheckAlignasUnderalignment(Record);
17612 
17613       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17614         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17615                                            IA->getRange(), IA->getBestCase(),
17616                                            IA->getInheritanceModel());
17617     }
17618 
17619     // Check if the structure/union declaration is a type that can have zero
17620     // size in C. For C this is a language extension, for C++ it may cause
17621     // compatibility problems.
17622     bool CheckForZeroSize;
17623     if (!getLangOpts().CPlusPlus) {
17624       CheckForZeroSize = true;
17625     } else {
17626       // For C++ filter out types that cannot be referenced in C code.
17627       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17628       CheckForZeroSize =
17629           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17630           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17631           CXXRecord->isCLike();
17632     }
17633     if (CheckForZeroSize) {
17634       bool ZeroSize = true;
17635       bool IsEmpty = true;
17636       unsigned NonBitFields = 0;
17637       for (RecordDecl::field_iterator I = Record->field_begin(),
17638                                       E = Record->field_end();
17639            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17640         IsEmpty = false;
17641         if (I->isUnnamedBitfield()) {
17642           if (!I->isZeroLengthBitField(Context))
17643             ZeroSize = false;
17644         } else {
17645           ++NonBitFields;
17646           QualType FieldType = I->getType();
17647           if (FieldType->isIncompleteType() ||
17648               !Context.getTypeSizeInChars(FieldType).isZero())
17649             ZeroSize = false;
17650         }
17651       }
17652 
17653       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17654       // allowed in C++, but warn if its declaration is inside
17655       // extern "C" block.
17656       if (ZeroSize) {
17657         Diag(RecLoc, getLangOpts().CPlusPlus ?
17658                          diag::warn_zero_size_struct_union_in_extern_c :
17659                          diag::warn_zero_size_struct_union_compat)
17660           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17661       }
17662 
17663       // Structs without named members are extension in C (C99 6.7.2.1p7),
17664       // but are accepted by GCC.
17665       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17666         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17667                                diag::ext_no_named_members_in_struct_union)
17668           << Record->isUnion();
17669       }
17670     }
17671   } else {
17672     ObjCIvarDecl **ClsFields =
17673       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17674     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17675       ID->setEndOfDefinitionLoc(RBrac);
17676       // Add ivar's to class's DeclContext.
17677       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17678         ClsFields[i]->setLexicalDeclContext(ID);
17679         ID->addDecl(ClsFields[i]);
17680       }
17681       // Must enforce the rule that ivars in the base classes may not be
17682       // duplicates.
17683       if (ID->getSuperClass())
17684         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17685     } else if (ObjCImplementationDecl *IMPDecl =
17686                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17687       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17688       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17689         // Ivar declared in @implementation never belongs to the implementation.
17690         // Only it is in implementation's lexical context.
17691         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17692       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17693       IMPDecl->setIvarLBraceLoc(LBrac);
17694       IMPDecl->setIvarRBraceLoc(RBrac);
17695     } else if (ObjCCategoryDecl *CDecl =
17696                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17697       // case of ivars in class extension; all other cases have been
17698       // reported as errors elsewhere.
17699       // FIXME. Class extension does not have a LocEnd field.
17700       // CDecl->setLocEnd(RBrac);
17701       // Add ivar's to class extension's DeclContext.
17702       // Diagnose redeclaration of private ivars.
17703       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17704       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17705         if (IDecl) {
17706           if (const ObjCIvarDecl *ClsIvar =
17707               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17708             Diag(ClsFields[i]->getLocation(),
17709                  diag::err_duplicate_ivar_declaration);
17710             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17711             continue;
17712           }
17713           for (const auto *Ext : IDecl->known_extensions()) {
17714             if (const ObjCIvarDecl *ClsExtIvar
17715                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17716               Diag(ClsFields[i]->getLocation(),
17717                    diag::err_duplicate_ivar_declaration);
17718               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17719               continue;
17720             }
17721           }
17722         }
17723         ClsFields[i]->setLexicalDeclContext(CDecl);
17724         CDecl->addDecl(ClsFields[i]);
17725       }
17726       CDecl->setIvarLBraceLoc(LBrac);
17727       CDecl->setIvarRBraceLoc(RBrac);
17728     }
17729   }
17730 }
17731 
17732 /// Determine whether the given integral value is representable within
17733 /// the given type T.
17734 static bool isRepresentableIntegerValue(ASTContext &Context,
17735                                         llvm::APSInt &Value,
17736                                         QualType T) {
17737   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17738          "Integral type required!");
17739   unsigned BitWidth = Context.getIntWidth(T);
17740 
17741   if (Value.isUnsigned() || Value.isNonNegative()) {
17742     if (T->isSignedIntegerOrEnumerationType())
17743       --BitWidth;
17744     return Value.getActiveBits() <= BitWidth;
17745   }
17746   return Value.getMinSignedBits() <= BitWidth;
17747 }
17748 
17749 // Given an integral type, return the next larger integral type
17750 // (or a NULL type of no such type exists).
17751 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17752   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17753   // enum checking below.
17754   assert((T->isIntegralType(Context) ||
17755          T->isEnumeralType()) && "Integral type required!");
17756   const unsigned NumTypes = 4;
17757   QualType SignedIntegralTypes[NumTypes] = {
17758     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17759   };
17760   QualType UnsignedIntegralTypes[NumTypes] = {
17761     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17762     Context.UnsignedLongLongTy
17763   };
17764 
17765   unsigned BitWidth = Context.getTypeSize(T);
17766   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17767                                                         : UnsignedIntegralTypes;
17768   for (unsigned I = 0; I != NumTypes; ++I)
17769     if (Context.getTypeSize(Types[I]) > BitWidth)
17770       return Types[I];
17771 
17772   return QualType();
17773 }
17774 
17775 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17776                                           EnumConstantDecl *LastEnumConst,
17777                                           SourceLocation IdLoc,
17778                                           IdentifierInfo *Id,
17779                                           Expr *Val) {
17780   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17781   llvm::APSInt EnumVal(IntWidth);
17782   QualType EltTy;
17783 
17784   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17785     Val = nullptr;
17786 
17787   if (Val)
17788     Val = DefaultLvalueConversion(Val).get();
17789 
17790   if (Val) {
17791     if (Enum->isDependentType() || Val->isTypeDependent())
17792       EltTy = Context.DependentTy;
17793     else {
17794       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17795       // underlying type, but do allow it in all other contexts.
17796       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17797         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17798         // constant-expression in the enumerator-definition shall be a converted
17799         // constant expression of the underlying type.
17800         EltTy = Enum->getIntegerType();
17801         ExprResult Converted =
17802           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17803                                            CCEK_Enumerator);
17804         if (Converted.isInvalid())
17805           Val = nullptr;
17806         else
17807           Val = Converted.get();
17808       } else if (!Val->isValueDependent() &&
17809                  !(Val =
17810                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17811                            .get())) {
17812         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17813       } else {
17814         if (Enum->isComplete()) {
17815           EltTy = Enum->getIntegerType();
17816 
17817           // In Obj-C and Microsoft mode, require the enumeration value to be
17818           // representable in the underlying type of the enumeration. In C++11,
17819           // we perform a non-narrowing conversion as part of converted constant
17820           // expression checking.
17821           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17822             if (Context.getTargetInfo()
17823                     .getTriple()
17824                     .isWindowsMSVCEnvironment()) {
17825               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17826             } else {
17827               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17828             }
17829           }
17830 
17831           // Cast to the underlying type.
17832           Val = ImpCastExprToType(Val, EltTy,
17833                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17834                                                          : CK_IntegralCast)
17835                     .get();
17836         } else if (getLangOpts().CPlusPlus) {
17837           // C++11 [dcl.enum]p5:
17838           //   If the underlying type is not fixed, the type of each enumerator
17839           //   is the type of its initializing value:
17840           //     - If an initializer is specified for an enumerator, the
17841           //       initializing value has the same type as the expression.
17842           EltTy = Val->getType();
17843         } else {
17844           // C99 6.7.2.2p2:
17845           //   The expression that defines the value of an enumeration constant
17846           //   shall be an integer constant expression that has a value
17847           //   representable as an int.
17848 
17849           // Complain if the value is not representable in an int.
17850           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17851             Diag(IdLoc, diag::ext_enum_value_not_int)
17852               << EnumVal.toString(10) << Val->getSourceRange()
17853               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17854           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17855             // Force the type of the expression to 'int'.
17856             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17857           }
17858           EltTy = Val->getType();
17859         }
17860       }
17861     }
17862   }
17863 
17864   if (!Val) {
17865     if (Enum->isDependentType())
17866       EltTy = Context.DependentTy;
17867     else if (!LastEnumConst) {
17868       // C++0x [dcl.enum]p5:
17869       //   If the underlying type is not fixed, the type of each enumerator
17870       //   is the type of its initializing value:
17871       //     - If no initializer is specified for the first enumerator, the
17872       //       initializing value has an unspecified integral type.
17873       //
17874       // GCC uses 'int' for its unspecified integral type, as does
17875       // C99 6.7.2.2p3.
17876       if (Enum->isFixed()) {
17877         EltTy = Enum->getIntegerType();
17878       }
17879       else {
17880         EltTy = Context.IntTy;
17881       }
17882     } else {
17883       // Assign the last value + 1.
17884       EnumVal = LastEnumConst->getInitVal();
17885       ++EnumVal;
17886       EltTy = LastEnumConst->getType();
17887 
17888       // Check for overflow on increment.
17889       if (EnumVal < LastEnumConst->getInitVal()) {
17890         // C++0x [dcl.enum]p5:
17891         //   If the underlying type is not fixed, the type of each enumerator
17892         //   is the type of its initializing value:
17893         //
17894         //     - Otherwise the type of the initializing value is the same as
17895         //       the type of the initializing value of the preceding enumerator
17896         //       unless the incremented value is not representable in that type,
17897         //       in which case the type is an unspecified integral type
17898         //       sufficient to contain the incremented value. If no such type
17899         //       exists, the program is ill-formed.
17900         QualType T = getNextLargerIntegralType(Context, EltTy);
17901         if (T.isNull() || Enum->isFixed()) {
17902           // There is no integral type larger enough to represent this
17903           // value. Complain, then allow the value to wrap around.
17904           EnumVal = LastEnumConst->getInitVal();
17905           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17906           ++EnumVal;
17907           if (Enum->isFixed())
17908             // When the underlying type is fixed, this is ill-formed.
17909             Diag(IdLoc, diag::err_enumerator_wrapped)
17910               << EnumVal.toString(10)
17911               << EltTy;
17912           else
17913             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17914               << EnumVal.toString(10);
17915         } else {
17916           EltTy = T;
17917         }
17918 
17919         // Retrieve the last enumerator's value, extent that type to the
17920         // type that is supposed to be large enough to represent the incremented
17921         // value, then increment.
17922         EnumVal = LastEnumConst->getInitVal();
17923         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17924         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17925         ++EnumVal;
17926 
17927         // If we're not in C++, diagnose the overflow of enumerator values,
17928         // which in C99 means that the enumerator value is not representable in
17929         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17930         // permits enumerator values that are representable in some larger
17931         // integral type.
17932         if (!getLangOpts().CPlusPlus && !T.isNull())
17933           Diag(IdLoc, diag::warn_enum_value_overflow);
17934       } else if (!getLangOpts().CPlusPlus &&
17935                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17936         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17937         Diag(IdLoc, diag::ext_enum_value_not_int)
17938           << EnumVal.toString(10) << 1;
17939       }
17940     }
17941   }
17942 
17943   if (!EltTy->isDependentType()) {
17944     // Make the enumerator value match the signedness and size of the
17945     // enumerator's type.
17946     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17947     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17948   }
17949 
17950   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17951                                   Val, EnumVal);
17952 }
17953 
17954 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17955                                                 SourceLocation IILoc) {
17956   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17957       !getLangOpts().CPlusPlus)
17958     return SkipBodyInfo();
17959 
17960   // We have an anonymous enum definition. Look up the first enumerator to
17961   // determine if we should merge the definition with an existing one and
17962   // skip the body.
17963   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17964                                          forRedeclarationInCurContext());
17965   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17966   if (!PrevECD)
17967     return SkipBodyInfo();
17968 
17969   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17970   NamedDecl *Hidden;
17971   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17972     SkipBodyInfo Skip;
17973     Skip.Previous = Hidden;
17974     return Skip;
17975   }
17976 
17977   return SkipBodyInfo();
17978 }
17979 
17980 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17981                               SourceLocation IdLoc, IdentifierInfo *Id,
17982                               const ParsedAttributesView &Attrs,
17983                               SourceLocation EqualLoc, Expr *Val) {
17984   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17985   EnumConstantDecl *LastEnumConst =
17986     cast_or_null<EnumConstantDecl>(lastEnumConst);
17987 
17988   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17989   // we find one that is.
17990   S = getNonFieldDeclScope(S);
17991 
17992   // Verify that there isn't already something declared with this name in this
17993   // scope.
17994   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17995   LookupName(R, S);
17996   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17997 
17998   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17999     // Maybe we will complain about the shadowed template parameter.
18000     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18001     // Just pretend that we didn't see the previous declaration.
18002     PrevDecl = nullptr;
18003   }
18004 
18005   // C++ [class.mem]p15:
18006   // If T is the name of a class, then each of the following shall have a name
18007   // different from T:
18008   // - every enumerator of every member of class T that is an unscoped
18009   // enumerated type
18010   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18011     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18012                             DeclarationNameInfo(Id, IdLoc));
18013 
18014   EnumConstantDecl *New =
18015     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18016   if (!New)
18017     return nullptr;
18018 
18019   if (PrevDecl) {
18020     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18021       // Check for other kinds of shadowing not already handled.
18022       CheckShadow(New, PrevDecl, R);
18023     }
18024 
18025     // When in C++, we may get a TagDecl with the same name; in this case the
18026     // enum constant will 'hide' the tag.
18027     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18028            "Received TagDecl when not in C++!");
18029     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18030       if (isa<EnumConstantDecl>(PrevDecl))
18031         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18032       else
18033         Diag(IdLoc, diag::err_redefinition) << Id;
18034       notePreviousDefinition(PrevDecl, IdLoc);
18035       return nullptr;
18036     }
18037   }
18038 
18039   // Process attributes.
18040   ProcessDeclAttributeList(S, New, Attrs);
18041   AddPragmaAttributes(S, New);
18042 
18043   // Register this decl in the current scope stack.
18044   New->setAccess(TheEnumDecl->getAccess());
18045   PushOnScopeChains(New, S);
18046 
18047   ActOnDocumentableDecl(New);
18048 
18049   return New;
18050 }
18051 
18052 // Returns true when the enum initial expression does not trigger the
18053 // duplicate enum warning.  A few common cases are exempted as follows:
18054 // Element2 = Element1
18055 // Element2 = Element1 + 1
18056 // Element2 = Element1 - 1
18057 // Where Element2 and Element1 are from the same enum.
18058 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18059   Expr *InitExpr = ECD->getInitExpr();
18060   if (!InitExpr)
18061     return true;
18062   InitExpr = InitExpr->IgnoreImpCasts();
18063 
18064   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18065     if (!BO->isAdditiveOp())
18066       return true;
18067     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18068     if (!IL)
18069       return true;
18070     if (IL->getValue() != 1)
18071       return true;
18072 
18073     InitExpr = BO->getLHS();
18074   }
18075 
18076   // This checks if the elements are from the same enum.
18077   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18078   if (!DRE)
18079     return true;
18080 
18081   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18082   if (!EnumConstant)
18083     return true;
18084 
18085   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18086       Enum)
18087     return true;
18088 
18089   return false;
18090 }
18091 
18092 // Emits a warning when an element is implicitly set a value that
18093 // a previous element has already been set to.
18094 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18095                                         EnumDecl *Enum, QualType EnumType) {
18096   // Avoid anonymous enums
18097   if (!Enum->getIdentifier())
18098     return;
18099 
18100   // Only check for small enums.
18101   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18102     return;
18103 
18104   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18105     return;
18106 
18107   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18108   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18109 
18110   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18111 
18112   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18113   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18114 
18115   // Use int64_t as a key to avoid needing special handling for map keys.
18116   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18117     llvm::APSInt Val = D->getInitVal();
18118     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18119   };
18120 
18121   DuplicatesVector DupVector;
18122   ValueToVectorMap EnumMap;
18123 
18124   // Populate the EnumMap with all values represented by enum constants without
18125   // an initializer.
18126   for (auto *Element : Elements) {
18127     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18128 
18129     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18130     // this constant.  Skip this enum since it may be ill-formed.
18131     if (!ECD) {
18132       return;
18133     }
18134 
18135     // Constants with initalizers are handled in the next loop.
18136     if (ECD->getInitExpr())
18137       continue;
18138 
18139     // Duplicate values are handled in the next loop.
18140     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18141   }
18142 
18143   if (EnumMap.size() == 0)
18144     return;
18145 
18146   // Create vectors for any values that has duplicates.
18147   for (auto *Element : Elements) {
18148     // The last loop returned if any constant was null.
18149     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18150     if (!ValidDuplicateEnum(ECD, Enum))
18151       continue;
18152 
18153     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18154     if (Iter == EnumMap.end())
18155       continue;
18156 
18157     DeclOrVector& Entry = Iter->second;
18158     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18159       // Ensure constants are different.
18160       if (D == ECD)
18161         continue;
18162 
18163       // Create new vector and push values onto it.
18164       auto Vec = std::make_unique<ECDVector>();
18165       Vec->push_back(D);
18166       Vec->push_back(ECD);
18167 
18168       // Update entry to point to the duplicates vector.
18169       Entry = Vec.get();
18170 
18171       // Store the vector somewhere we can consult later for quick emission of
18172       // diagnostics.
18173       DupVector.emplace_back(std::move(Vec));
18174       continue;
18175     }
18176 
18177     ECDVector *Vec = Entry.get<ECDVector*>();
18178     // Make sure constants are not added more than once.
18179     if (*Vec->begin() == ECD)
18180       continue;
18181 
18182     Vec->push_back(ECD);
18183   }
18184 
18185   // Emit diagnostics.
18186   for (const auto &Vec : DupVector) {
18187     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18188 
18189     // Emit warning for one enum constant.
18190     auto *FirstECD = Vec->front();
18191     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18192       << FirstECD << FirstECD->getInitVal().toString(10)
18193       << FirstECD->getSourceRange();
18194 
18195     // Emit one note for each of the remaining enum constants with
18196     // the same value.
18197     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18198       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18199         << ECD << ECD->getInitVal().toString(10)
18200         << ECD->getSourceRange();
18201   }
18202 }
18203 
18204 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18205                              bool AllowMask) const {
18206   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18207   assert(ED->isCompleteDefinition() && "expected enum definition");
18208 
18209   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18210   llvm::APInt &FlagBits = R.first->second;
18211 
18212   if (R.second) {
18213     for (auto *E : ED->enumerators()) {
18214       const auto &EVal = E->getInitVal();
18215       // Only single-bit enumerators introduce new flag values.
18216       if (EVal.isPowerOf2())
18217         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18218     }
18219   }
18220 
18221   // A value is in a flag enum if either its bits are a subset of the enum's
18222   // flag bits (the first condition) or we are allowing masks and the same is
18223   // true of its complement (the second condition). When masks are allowed, we
18224   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18225   //
18226   // While it's true that any value could be used as a mask, the assumption is
18227   // that a mask will have all of the insignificant bits set. Anything else is
18228   // likely a logic error.
18229   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18230   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18231 }
18232 
18233 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18234                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18235                          const ParsedAttributesView &Attrs) {
18236   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18237   QualType EnumType = Context.getTypeDeclType(Enum);
18238 
18239   ProcessDeclAttributeList(S, Enum, Attrs);
18240 
18241   if (Enum->isDependentType()) {
18242     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18243       EnumConstantDecl *ECD =
18244         cast_or_null<EnumConstantDecl>(Elements[i]);
18245       if (!ECD) continue;
18246 
18247       ECD->setType(EnumType);
18248     }
18249 
18250     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18251     return;
18252   }
18253 
18254   // TODO: If the result value doesn't fit in an int, it must be a long or long
18255   // long value.  ISO C does not support this, but GCC does as an extension,
18256   // emit a warning.
18257   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18258   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18259   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18260 
18261   // Verify that all the values are okay, compute the size of the values, and
18262   // reverse the list.
18263   unsigned NumNegativeBits = 0;
18264   unsigned NumPositiveBits = 0;
18265 
18266   // Keep track of whether all elements have type int.
18267   bool AllElementsInt = true;
18268 
18269   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18270     EnumConstantDecl *ECD =
18271       cast_or_null<EnumConstantDecl>(Elements[i]);
18272     if (!ECD) continue;  // Already issued a diagnostic.
18273 
18274     const llvm::APSInt &InitVal = ECD->getInitVal();
18275 
18276     // Keep track of the size of positive and negative values.
18277     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18278       NumPositiveBits = std::max(NumPositiveBits,
18279                                  (unsigned)InitVal.getActiveBits());
18280     else
18281       NumNegativeBits = std::max(NumNegativeBits,
18282                                  (unsigned)InitVal.getMinSignedBits());
18283 
18284     // Keep track of whether every enum element has type int (very common).
18285     if (AllElementsInt)
18286       AllElementsInt = ECD->getType() == Context.IntTy;
18287   }
18288 
18289   // Figure out the type that should be used for this enum.
18290   QualType BestType;
18291   unsigned BestWidth;
18292 
18293   // C++0x N3000 [conv.prom]p3:
18294   //   An rvalue of an unscoped enumeration type whose underlying
18295   //   type is not fixed can be converted to an rvalue of the first
18296   //   of the following types that can represent all the values of
18297   //   the enumeration: int, unsigned int, long int, unsigned long
18298   //   int, long long int, or unsigned long long int.
18299   // C99 6.4.4.3p2:
18300   //   An identifier declared as an enumeration constant has type int.
18301   // The C99 rule is modified by a gcc extension
18302   QualType BestPromotionType;
18303 
18304   bool Packed = Enum->hasAttr<PackedAttr>();
18305   // -fshort-enums is the equivalent to specifying the packed attribute on all
18306   // enum definitions.
18307   if (LangOpts.ShortEnums)
18308     Packed = true;
18309 
18310   // If the enum already has a type because it is fixed or dictated by the
18311   // target, promote that type instead of analyzing the enumerators.
18312   if (Enum->isComplete()) {
18313     BestType = Enum->getIntegerType();
18314     if (BestType->isPromotableIntegerType())
18315       BestPromotionType = Context.getPromotedIntegerType(BestType);
18316     else
18317       BestPromotionType = BestType;
18318 
18319     BestWidth = Context.getIntWidth(BestType);
18320   }
18321   else if (NumNegativeBits) {
18322     // If there is a negative value, figure out the smallest integer type (of
18323     // int/long/longlong) that fits.
18324     // If it's packed, check also if it fits a char or a short.
18325     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18326       BestType = Context.SignedCharTy;
18327       BestWidth = CharWidth;
18328     } else if (Packed && NumNegativeBits <= ShortWidth &&
18329                NumPositiveBits < ShortWidth) {
18330       BestType = Context.ShortTy;
18331       BestWidth = ShortWidth;
18332     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18333       BestType = Context.IntTy;
18334       BestWidth = IntWidth;
18335     } else {
18336       BestWidth = Context.getTargetInfo().getLongWidth();
18337 
18338       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18339         BestType = Context.LongTy;
18340       } else {
18341         BestWidth = Context.getTargetInfo().getLongLongWidth();
18342 
18343         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18344           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18345         BestType = Context.LongLongTy;
18346       }
18347     }
18348     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18349   } else {
18350     // If there is no negative value, figure out the smallest type that fits
18351     // all of the enumerator values.
18352     // If it's packed, check also if it fits a char or a short.
18353     if (Packed && NumPositiveBits <= CharWidth) {
18354       BestType = Context.UnsignedCharTy;
18355       BestPromotionType = Context.IntTy;
18356       BestWidth = CharWidth;
18357     } else if (Packed && NumPositiveBits <= ShortWidth) {
18358       BestType = Context.UnsignedShortTy;
18359       BestPromotionType = Context.IntTy;
18360       BestWidth = ShortWidth;
18361     } else if (NumPositiveBits <= IntWidth) {
18362       BestType = Context.UnsignedIntTy;
18363       BestWidth = IntWidth;
18364       BestPromotionType
18365         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18366                            ? Context.UnsignedIntTy : Context.IntTy;
18367     } else if (NumPositiveBits <=
18368                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18369       BestType = Context.UnsignedLongTy;
18370       BestPromotionType
18371         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18372                            ? Context.UnsignedLongTy : Context.LongTy;
18373     } else {
18374       BestWidth = Context.getTargetInfo().getLongLongWidth();
18375       assert(NumPositiveBits <= BestWidth &&
18376              "How could an initializer get larger than ULL?");
18377       BestType = Context.UnsignedLongLongTy;
18378       BestPromotionType
18379         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18380                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18381     }
18382   }
18383 
18384   // Loop over all of the enumerator constants, changing their types to match
18385   // the type of the enum if needed.
18386   for (auto *D : Elements) {
18387     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18388     if (!ECD) continue;  // Already issued a diagnostic.
18389 
18390     // Standard C says the enumerators have int type, but we allow, as an
18391     // extension, the enumerators to be larger than int size.  If each
18392     // enumerator value fits in an int, type it as an int, otherwise type it the
18393     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18394     // that X has type 'int', not 'unsigned'.
18395 
18396     // Determine whether the value fits into an int.
18397     llvm::APSInt InitVal = ECD->getInitVal();
18398 
18399     // If it fits into an integer type, force it.  Otherwise force it to match
18400     // the enum decl type.
18401     QualType NewTy;
18402     unsigned NewWidth;
18403     bool NewSign;
18404     if (!getLangOpts().CPlusPlus &&
18405         !Enum->isFixed() &&
18406         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18407       NewTy = Context.IntTy;
18408       NewWidth = IntWidth;
18409       NewSign = true;
18410     } else if (ECD->getType() == BestType) {
18411       // Already the right type!
18412       if (getLangOpts().CPlusPlus)
18413         // C++ [dcl.enum]p4: Following the closing brace of an
18414         // enum-specifier, each enumerator has the type of its
18415         // enumeration.
18416         ECD->setType(EnumType);
18417       continue;
18418     } else {
18419       NewTy = BestType;
18420       NewWidth = BestWidth;
18421       NewSign = BestType->isSignedIntegerOrEnumerationType();
18422     }
18423 
18424     // Adjust the APSInt value.
18425     InitVal = InitVal.extOrTrunc(NewWidth);
18426     InitVal.setIsSigned(NewSign);
18427     ECD->setInitVal(InitVal);
18428 
18429     // Adjust the Expr initializer and type.
18430     if (ECD->getInitExpr() &&
18431         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18432       ECD->setInitExpr(ImplicitCastExpr::Create(
18433           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18434           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18435     if (getLangOpts().CPlusPlus)
18436       // C++ [dcl.enum]p4: Following the closing brace of an
18437       // enum-specifier, each enumerator has the type of its
18438       // enumeration.
18439       ECD->setType(EnumType);
18440     else
18441       ECD->setType(NewTy);
18442   }
18443 
18444   Enum->completeDefinition(BestType, BestPromotionType,
18445                            NumPositiveBits, NumNegativeBits);
18446 
18447   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18448 
18449   if (Enum->isClosedFlag()) {
18450     for (Decl *D : Elements) {
18451       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18452       if (!ECD) continue;  // Already issued a diagnostic.
18453 
18454       llvm::APSInt InitVal = ECD->getInitVal();
18455       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18456           !IsValueInFlagEnum(Enum, InitVal, true))
18457         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18458           << ECD << Enum;
18459     }
18460   }
18461 
18462   // Now that the enum type is defined, ensure it's not been underaligned.
18463   if (Enum->hasAttrs())
18464     CheckAlignasUnderalignment(Enum);
18465 }
18466 
18467 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18468                                   SourceLocation StartLoc,
18469                                   SourceLocation EndLoc) {
18470   StringLiteral *AsmString = cast<StringLiteral>(expr);
18471 
18472   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18473                                                    AsmString, StartLoc,
18474                                                    EndLoc);
18475   CurContext->addDecl(New);
18476   return New;
18477 }
18478 
18479 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18480                                       IdentifierInfo* AliasName,
18481                                       SourceLocation PragmaLoc,
18482                                       SourceLocation NameLoc,
18483                                       SourceLocation AliasNameLoc) {
18484   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18485                                          LookupOrdinaryName);
18486   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18487                            AttributeCommonInfo::AS_Pragma);
18488   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18489       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18490 
18491   // If a declaration that:
18492   // 1) declares a function or a variable
18493   // 2) has external linkage
18494   // already exists, add a label attribute to it.
18495   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18496     if (isDeclExternC(PrevDecl))
18497       PrevDecl->addAttr(Attr);
18498     else
18499       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18500           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18501   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18502   } else
18503     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18504 }
18505 
18506 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18507                              SourceLocation PragmaLoc,
18508                              SourceLocation NameLoc) {
18509   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18510 
18511   if (PrevDecl) {
18512     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18513   } else {
18514     (void)WeakUndeclaredIdentifiers.insert(
18515       std::pair<IdentifierInfo*,WeakInfo>
18516         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18517   }
18518 }
18519 
18520 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18521                                 IdentifierInfo* AliasName,
18522                                 SourceLocation PragmaLoc,
18523                                 SourceLocation NameLoc,
18524                                 SourceLocation AliasNameLoc) {
18525   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18526                                     LookupOrdinaryName);
18527   WeakInfo W = WeakInfo(Name, NameLoc);
18528 
18529   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18530     if (!PrevDecl->hasAttr<AliasAttr>())
18531       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18532         DeclApplyPragmaWeak(TUScope, ND, W);
18533   } else {
18534     (void)WeakUndeclaredIdentifiers.insert(
18535       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18536   }
18537 }
18538 
18539 Decl *Sema::getObjCDeclContext() const {
18540   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18541 }
18542 
18543 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18544                                                      bool Final) {
18545   assert(FD && "Expected non-null FunctionDecl");
18546 
18547   // SYCL functions can be template, so we check if they have appropriate
18548   // attribute prior to checking if it is a template.
18549   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18550     return FunctionEmissionStatus::Emitted;
18551 
18552   // Templates are emitted when they're instantiated.
18553   if (FD->isDependentContext())
18554     return FunctionEmissionStatus::TemplateDiscarded;
18555 
18556   // Check whether this function is an externally visible definition.
18557   auto IsEmittedForExternalSymbol = [this, FD]() {
18558     // We have to check the GVA linkage of the function's *definition* -- if we
18559     // only have a declaration, we don't know whether or not the function will
18560     // be emitted, because (say) the definition could include "inline".
18561     FunctionDecl *Def = FD->getDefinition();
18562 
18563     return Def && !isDiscardableGVALinkage(
18564                       getASTContext().GetGVALinkageForFunction(Def));
18565   };
18566 
18567   if (LangOpts.OpenMPIsDevice) {
18568     // In OpenMP device mode we will not emit host only functions, or functions
18569     // we don't need due to their linkage.
18570     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18571         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18572     // DevTy may be changed later by
18573     //  #pragma omp declare target to(*) device_type(*).
18574     // Therefore DevTyhaving no value does not imply host. The emission status
18575     // will be checked again at the end of compilation unit with Final = true.
18576     if (DevTy.hasValue())
18577       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18578         return FunctionEmissionStatus::OMPDiscarded;
18579     // If we have an explicit value for the device type, or we are in a target
18580     // declare context, we need to emit all extern and used symbols.
18581     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18582       if (IsEmittedForExternalSymbol())
18583         return FunctionEmissionStatus::Emitted;
18584     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18585     // we'll omit it.
18586     if (Final)
18587       return FunctionEmissionStatus::OMPDiscarded;
18588   } else if (LangOpts.OpenMP > 45) {
18589     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18590     // function. In 5.0, no_host was introduced which might cause a function to
18591     // be ommitted.
18592     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18593         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18594     if (DevTy.hasValue())
18595       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18596         return FunctionEmissionStatus::OMPDiscarded;
18597   }
18598 
18599   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18600     return FunctionEmissionStatus::Emitted;
18601 
18602   if (LangOpts.CUDA) {
18603     // When compiling for device, host functions are never emitted.  Similarly,
18604     // when compiling for host, device and global functions are never emitted.
18605     // (Technically, we do emit a host-side stub for global functions, but this
18606     // doesn't count for our purposes here.)
18607     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18608     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18609       return FunctionEmissionStatus::CUDADiscarded;
18610     if (!LangOpts.CUDAIsDevice &&
18611         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18612       return FunctionEmissionStatus::CUDADiscarded;
18613 
18614     if (IsEmittedForExternalSymbol())
18615       return FunctionEmissionStatus::Emitted;
18616   }
18617 
18618   // Otherwise, the function is known-emitted if it's in our set of
18619   // known-emitted functions.
18620   return FunctionEmissionStatus::Unknown;
18621 }
18622 
18623 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18624   // Host-side references to a __global__ function refer to the stub, so the
18625   // function itself is never emitted and therefore should not be marked.
18626   // If we have host fn calls kernel fn calls host+device, the HD function
18627   // does not get instantiated on the host. We model this by omitting at the
18628   // call to the kernel from the callgraph. This ensures that, when compiling
18629   // for host, only HD functions actually called from the host get marked as
18630   // known-emitted.
18631   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18632          IdentifyCUDATarget(Callee) == CFT_Global;
18633 }
18634