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/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439         if (!IIDecl ||
440             (*Res)->getLocation().getRawEncoding() <
441               IIDecl->getLocation().getRawEncoding())
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() &&
1482       !D->getDeclContext()->getRedeclContext()->Equals(
1483         D->getLexicalDeclContext()->getRedeclContext()) &&
1484       !D->getLexicalDeclContext()->isFunctionOrMethod())
1485     return;
1486 
1487   // Template instantiations should also not be pushed into scope.
1488   if (isa<FunctionDecl>(D) &&
1489       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1490     return;
1491 
1492   // If this replaces anything in the current scope,
1493   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1494                                IEnd = IdResolver.end();
1495   for (; I != IEnd; ++I) {
1496     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1497       S->RemoveDecl(*I);
1498       IdResolver.RemoveDecl(*I);
1499 
1500       // Should only need to replace one decl.
1501       break;
1502     }
1503   }
1504 
1505   S->AddDecl(D);
1506 
1507   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1508     // Implicitly-generated labels may end up getting generated in an order that
1509     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1510     // the label at the appropriate place in the identifier chain.
1511     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1512       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1513       if (IDC == CurContext) {
1514         if (!S->isDeclScope(*I))
1515           continue;
1516       } else if (IDC->Encloses(CurContext))
1517         break;
1518     }
1519 
1520     IdResolver.InsertDeclAfter(I, D);
1521   } else {
1522     IdResolver.AddDecl(D);
1523   }
1524 }
1525 
1526 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1527                          bool AllowInlineNamespace) {
1528   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1529 }
1530 
1531 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1532   DeclContext *TargetDC = DC->getPrimaryContext();
1533   do {
1534     if (DeclContext *ScopeDC = S->getEntity())
1535       if (ScopeDC->getPrimaryContext() == TargetDC)
1536         return S;
1537   } while ((S = S->getParent()));
1538 
1539   return nullptr;
1540 }
1541 
1542 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1543                                             DeclContext*,
1544                                             ASTContext&);
1545 
1546 /// Filters out lookup results that don't fall within the given scope
1547 /// as determined by isDeclInScope.
1548 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1549                                 bool ConsiderLinkage,
1550                                 bool AllowInlineNamespace) {
1551   LookupResult::Filter F = R.makeFilter();
1552   while (F.hasNext()) {
1553     NamedDecl *D = F.next();
1554 
1555     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1556       continue;
1557 
1558     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1559       continue;
1560 
1561     F.erase();
1562   }
1563 
1564   F.done();
1565 }
1566 
1567 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1568 /// have compatible owning modules.
1569 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1570   // FIXME: The Modules TS is not clear about how friend declarations are
1571   // to be treated. It's not meaningful to have different owning modules for
1572   // linkage in redeclarations of the same entity, so for now allow the
1573   // redeclaration and change the owning modules to match.
1574   if (New->getFriendObjectKind() &&
1575       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1576     New->setLocalOwningModule(Old->getOwningModule());
1577     makeMergedDefinitionVisible(New);
1578     return false;
1579   }
1580 
1581   Module *NewM = New->getOwningModule();
1582   Module *OldM = Old->getOwningModule();
1583 
1584   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1585     NewM = NewM->Parent;
1586   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1587     OldM = OldM->Parent;
1588 
1589   if (NewM == OldM)
1590     return false;
1591 
1592   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1593   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1594   if (NewIsModuleInterface || OldIsModuleInterface) {
1595     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1596     //   if a declaration of D [...] appears in the purview of a module, all
1597     //   other such declarations shall appear in the purview of the same module
1598     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1599       << New
1600       << NewIsModuleInterface
1601       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1602       << OldIsModuleInterface
1603       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1604     Diag(Old->getLocation(), diag::note_previous_declaration);
1605     New->setInvalidDecl();
1606     return true;
1607   }
1608 
1609   return false;
1610 }
1611 
1612 static bool isUsingDecl(NamedDecl *D) {
1613   return isa<UsingShadowDecl>(D) ||
1614          isa<UnresolvedUsingTypenameDecl>(D) ||
1615          isa<UnresolvedUsingValueDecl>(D);
1616 }
1617 
1618 /// Removes using shadow declarations from the lookup results.
1619 static void RemoveUsingDecls(LookupResult &R) {
1620   LookupResult::Filter F = R.makeFilter();
1621   while (F.hasNext())
1622     if (isUsingDecl(F.next()))
1623       F.erase();
1624 
1625   F.done();
1626 }
1627 
1628 /// Check for this common pattern:
1629 /// @code
1630 /// class S {
1631 ///   S(const S&); // DO NOT IMPLEMENT
1632 ///   void operator=(const S&); // DO NOT IMPLEMENT
1633 /// };
1634 /// @endcode
1635 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1636   // FIXME: Should check for private access too but access is set after we get
1637   // the decl here.
1638   if (D->doesThisDeclarationHaveABody())
1639     return false;
1640 
1641   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1642     return CD->isCopyConstructor();
1643   return D->isCopyAssignmentOperator();
1644 }
1645 
1646 // We need this to handle
1647 //
1648 // typedef struct {
1649 //   void *foo() { return 0; }
1650 // } A;
1651 //
1652 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1653 // for example. If 'A', foo will have external linkage. If we have '*A',
1654 // foo will have no linkage. Since we can't know until we get to the end
1655 // of the typedef, this function finds out if D might have non-external linkage.
1656 // Callers should verify at the end of the TU if it D has external linkage or
1657 // not.
1658 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1659   const DeclContext *DC = D->getDeclContext();
1660   while (!DC->isTranslationUnit()) {
1661     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1662       if (!RD->hasNameForLinkage())
1663         return true;
1664     }
1665     DC = DC->getParent();
1666   }
1667 
1668   return !D->isExternallyVisible();
1669 }
1670 
1671 // FIXME: This needs to be refactored; some other isInMainFile users want
1672 // these semantics.
1673 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1674   if (S.TUKind != TU_Complete)
1675     return false;
1676   return S.SourceMgr.isInMainFile(Loc);
1677 }
1678 
1679 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1680   assert(D);
1681 
1682   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1683     return false;
1684 
1685   // Ignore all entities declared within templates, and out-of-line definitions
1686   // of members of class templates.
1687   if (D->getDeclContext()->isDependentContext() ||
1688       D->getLexicalDeclContext()->isDependentContext())
1689     return false;
1690 
1691   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1692     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1693       return false;
1694     // A non-out-of-line declaration of a member specialization was implicitly
1695     // instantiated; it's the out-of-line declaration that we're interested in.
1696     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1697         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1698       return false;
1699 
1700     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1701       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1702         return false;
1703     } else {
1704       // 'static inline' functions are defined in headers; don't warn.
1705       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1706         return false;
1707     }
1708 
1709     if (FD->doesThisDeclarationHaveABody() &&
1710         Context.DeclMustBeEmitted(FD))
1711       return false;
1712   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713     // Constants and utility variables are defined in headers with internal
1714     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1715     // like "inline".)
1716     if (!isMainFileLoc(*this, VD->getLocation()))
1717       return false;
1718 
1719     if (Context.DeclMustBeEmitted(VD))
1720       return false;
1721 
1722     if (VD->isStaticDataMember() &&
1723         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1724       return false;
1725     if (VD->isStaticDataMember() &&
1726         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1727         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1728       return false;
1729 
1730     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1731       return false;
1732   } else {
1733     return false;
1734   }
1735 
1736   // Only warn for unused decls internal to the translation unit.
1737   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1738   // for inline functions defined in the main source file, for instance.
1739   return mightHaveNonExternalLinkage(D);
1740 }
1741 
1742 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1743   if (!D)
1744     return;
1745 
1746   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1747     const FunctionDecl *First = FD->getFirstDecl();
1748     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1749       return; // First should already be in the vector.
1750   }
1751 
1752   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753     const VarDecl *First = VD->getFirstDecl();
1754     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1755       return; // First should already be in the vector.
1756   }
1757 
1758   if (ShouldWarnIfUnusedFileScopedDecl(D))
1759     UnusedFileScopedDecls.push_back(D);
1760 }
1761 
1762 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1763   if (D->isInvalidDecl())
1764     return false;
1765 
1766   bool Referenced = false;
1767   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1768     // For a decomposition declaration, warn if none of the bindings are
1769     // referenced, instead of if the variable itself is referenced (which
1770     // it is, by the bindings' expressions).
1771     for (auto *BD : DD->bindings()) {
1772       if (BD->isReferenced()) {
1773         Referenced = true;
1774         break;
1775       }
1776     }
1777   } else if (!D->getDeclName()) {
1778     return false;
1779   } else if (D->isReferenced() || D->isUsed()) {
1780     Referenced = true;
1781   }
1782 
1783   if (Referenced || D->hasAttr<UnusedAttr>() ||
1784       D->hasAttr<ObjCPreciseLifetimeAttr>())
1785     return false;
1786 
1787   if (isa<LabelDecl>(D))
1788     return true;
1789 
1790   // Except for labels, we only care about unused decls that are local to
1791   // functions.
1792   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1793   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1794     // For dependent types, the diagnostic is deferred.
1795     WithinFunction =
1796         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1797   if (!WithinFunction)
1798     return false;
1799 
1800   if (isa<TypedefNameDecl>(D))
1801     return true;
1802 
1803   // White-list anything that isn't a local variable.
1804   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1805     return false;
1806 
1807   // Types of valid local variables should be complete, so this should succeed.
1808   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1809 
1810     // White-list anything with an __attribute__((unused)) type.
1811     const auto *Ty = VD->getType().getTypePtr();
1812 
1813     // Only look at the outermost level of typedef.
1814     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1815       if (TT->getDecl()->hasAttr<UnusedAttr>())
1816         return false;
1817     }
1818 
1819     // If we failed to complete the type for some reason, or if the type is
1820     // dependent, don't diagnose the variable.
1821     if (Ty->isIncompleteType() || Ty->isDependentType())
1822       return false;
1823 
1824     // Look at the element type to ensure that the warning behaviour is
1825     // consistent for both scalars and arrays.
1826     Ty = Ty->getBaseElementTypeUnsafe();
1827 
1828     if (const TagType *TT = Ty->getAs<TagType>()) {
1829       const TagDecl *Tag = TT->getDecl();
1830       if (Tag->hasAttr<UnusedAttr>())
1831         return false;
1832 
1833       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1834         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1835           return false;
1836 
1837         if (const Expr *Init = VD->getInit()) {
1838           if (const ExprWithCleanups *Cleanups =
1839                   dyn_cast<ExprWithCleanups>(Init))
1840             Init = Cleanups->getSubExpr();
1841           const CXXConstructExpr *Construct =
1842             dyn_cast<CXXConstructExpr>(Init);
1843           if (Construct && !Construct->isElidable()) {
1844             CXXConstructorDecl *CD = Construct->getConstructor();
1845             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1846                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1847               return false;
1848           }
1849 
1850           // Suppress the warning if we don't know how this is constructed, and
1851           // it could possibly be non-trivial constructor.
1852           if (Init->isTypeDependent())
1853             for (const CXXConstructorDecl *Ctor : RD->ctors())
1854               if (!Ctor->isTrivial())
1855                 return false;
1856         }
1857       }
1858     }
1859 
1860     // TODO: __attribute__((unused)) templates?
1861   }
1862 
1863   return true;
1864 }
1865 
1866 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1867                                      FixItHint &Hint) {
1868   if (isa<LabelDecl>(D)) {
1869     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1870         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1871         true);
1872     if (AfterColon.isInvalid())
1873       return;
1874     Hint = FixItHint::CreateRemoval(
1875         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1876   }
1877 }
1878 
1879 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1880   if (D->getTypeForDecl()->isDependentType())
1881     return;
1882 
1883   for (auto *TmpD : D->decls()) {
1884     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1885       DiagnoseUnusedDecl(T);
1886     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1887       DiagnoseUnusedNestedTypedefs(R);
1888   }
1889 }
1890 
1891 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1892 /// unless they are marked attr(unused).
1893 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1894   if (!ShouldDiagnoseUnusedDecl(D))
1895     return;
1896 
1897   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1898     // typedefs can be referenced later on, so the diagnostics are emitted
1899     // at end-of-translation-unit.
1900     UnusedLocalTypedefNameCandidates.insert(TD);
1901     return;
1902   }
1903 
1904   FixItHint Hint;
1905   GenerateFixForUnusedDecl(D, Context, Hint);
1906 
1907   unsigned DiagID;
1908   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1909     DiagID = diag::warn_unused_exception_param;
1910   else if (isa<LabelDecl>(D))
1911     DiagID = diag::warn_unused_label;
1912   else
1913     DiagID = diag::warn_unused_variable;
1914 
1915   Diag(D->getLocation(), DiagID) << D << Hint;
1916 }
1917 
1918 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1919   // Verify that we have no forward references left.  If so, there was a goto
1920   // or address of a label taken, but no definition of it.  Label fwd
1921   // definitions are indicated with a null substmt which is also not a resolved
1922   // MS inline assembly label name.
1923   bool Diagnose = false;
1924   if (L->isMSAsmLabel())
1925     Diagnose = !L->isResolvedMSAsmLabel();
1926   else
1927     Diagnose = L->getStmt() == nullptr;
1928   if (Diagnose)
1929     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1930 }
1931 
1932 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1933   S->mergeNRVOIntoParent();
1934 
1935   if (S->decl_empty()) return;
1936   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1937          "Scope shouldn't contain decls!");
1938 
1939   for (auto *TmpD : S->decls()) {
1940     assert(TmpD && "This decl didn't get pushed??");
1941 
1942     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1943     NamedDecl *D = cast<NamedDecl>(TmpD);
1944 
1945     // Diagnose unused variables in this scope.
1946     if (!S->hasUnrecoverableErrorOccurred()) {
1947       DiagnoseUnusedDecl(D);
1948       if (const auto *RD = dyn_cast<RecordDecl>(D))
1949         DiagnoseUnusedNestedTypedefs(RD);
1950     }
1951 
1952     if (!D->getDeclName()) continue;
1953 
1954     // If this was a forward reference to a label, verify it was defined.
1955     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1956       CheckPoppedLabel(LD, *this);
1957 
1958     // Remove this name from our lexical scope, and warn on it if we haven't
1959     // already.
1960     IdResolver.RemoveDecl(D);
1961     auto ShadowI = ShadowingDecls.find(D);
1962     if (ShadowI != ShadowingDecls.end()) {
1963       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1964         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1965             << D << FD << FD->getParent();
1966         Diag(FD->getLocation(), diag::note_previous_declaration);
1967       }
1968       ShadowingDecls.erase(ShadowI);
1969     }
1970   }
1971 }
1972 
1973 /// Look for an Objective-C class in the translation unit.
1974 ///
1975 /// \param Id The name of the Objective-C class we're looking for. If
1976 /// typo-correction fixes this name, the Id will be updated
1977 /// to the fixed name.
1978 ///
1979 /// \param IdLoc The location of the name in the translation unit.
1980 ///
1981 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1982 /// if there is no class with the given name.
1983 ///
1984 /// \returns The declaration of the named Objective-C class, or NULL if the
1985 /// class could not be found.
1986 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1987                                               SourceLocation IdLoc,
1988                                               bool DoTypoCorrection) {
1989   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1990   // creation from this context.
1991   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1992 
1993   if (!IDecl && DoTypoCorrection) {
1994     // Perform typo correction at the given location, but only if we
1995     // find an Objective-C class name.
1996     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1997     if (TypoCorrection C =
1998             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1999                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2000       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2001       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2002       Id = IDecl->getIdentifier();
2003     }
2004   }
2005   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2006   // This routine must always return a class definition, if any.
2007   if (Def && Def->getDefinition())
2008       Def = Def->getDefinition();
2009   return Def;
2010 }
2011 
2012 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2013 /// from S, where a non-field would be declared. This routine copes
2014 /// with the difference between C and C++ scoping rules in structs and
2015 /// unions. For example, the following code is well-formed in C but
2016 /// ill-formed in C++:
2017 /// @code
2018 /// struct S6 {
2019 ///   enum { BAR } e;
2020 /// };
2021 ///
2022 /// void test_S6() {
2023 ///   struct S6 a;
2024 ///   a.e = BAR;
2025 /// }
2026 /// @endcode
2027 /// For the declaration of BAR, this routine will return a different
2028 /// scope. The scope S will be the scope of the unnamed enumeration
2029 /// within S6. In C++, this routine will return the scope associated
2030 /// with S6, because the enumeration's scope is a transparent
2031 /// context but structures can contain non-field names. In C, this
2032 /// routine will return the translation unit scope, since the
2033 /// enumeration's scope is a transparent context and structures cannot
2034 /// contain non-field names.
2035 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2036   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2037          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2038          (S->isClassScope() && !getLangOpts().CPlusPlus))
2039     S = S->getParent();
2040   return S;
2041 }
2042 
2043 /// Looks up the declaration of "struct objc_super" and
2044 /// saves it for later use in building builtin declaration of
2045 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2046 /// pre-existing declaration exists no action takes place.
2047 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2048                                         IdentifierInfo *II) {
2049   if (!II->isStr("objc_msgSendSuper"))
2050     return;
2051   ASTContext &Context = ThisSema.Context;
2052 
2053   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2054                       SourceLocation(), Sema::LookupTagName);
2055   ThisSema.LookupName(Result, S);
2056   if (Result.getResultKind() == LookupResult::Found)
2057     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2058       Context.setObjCSuperType(Context.getTagDeclType(TD));
2059 }
2060 
2061 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2062                                ASTContext::GetBuiltinTypeError Error) {
2063   switch (Error) {
2064   case ASTContext::GE_None:
2065     return "";
2066   case ASTContext::GE_Missing_type:
2067     return BuiltinInfo.getHeaderName(ID);
2068   case ASTContext::GE_Missing_stdio:
2069     return "stdio.h";
2070   case ASTContext::GE_Missing_setjmp:
2071     return "setjmp.h";
2072   case ASTContext::GE_Missing_ucontext:
2073     return "ucontext.h";
2074   }
2075   llvm_unreachable("unhandled error kind");
2076 }
2077 
2078 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2079 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2080 /// if we're creating this built-in in anticipation of redeclaring the
2081 /// built-in.
2082 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2083                                      Scope *S, bool ForRedeclaration,
2084                                      SourceLocation Loc) {
2085   LookupPredefedObjCSuperType(*this, S, II);
2086 
2087   ASTContext::GetBuiltinTypeError Error;
2088   QualType R = Context.GetBuiltinType(ID, Error);
2089   if (Error) {
2090     if (!ForRedeclaration)
2091       return nullptr;
2092 
2093     // If we have a builtin without an associated type we should not emit a
2094     // warning when we were not able to find a type for it.
2095     if (Error == ASTContext::GE_Missing_type)
2096       return nullptr;
2097 
2098     // If we could not find a type for setjmp it is because the jmp_buf type was
2099     // not defined prior to the setjmp declaration.
2100     if (Error == ASTContext::GE_Missing_setjmp) {
2101       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2102           << Context.BuiltinInfo.getName(ID);
2103       return nullptr;
2104     }
2105 
2106     // Generally, we emit a warning that the declaration requires the
2107     // appropriate header.
2108     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2109         << getHeaderName(Context.BuiltinInfo, ID, Error)
2110         << Context.BuiltinInfo.getName(ID);
2111     return nullptr;
2112   }
2113 
2114   if (!ForRedeclaration &&
2115       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2116        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2117     Diag(Loc, diag::ext_implicit_lib_function_decl)
2118         << Context.BuiltinInfo.getName(ID) << R;
2119     if (Context.BuiltinInfo.getHeaderName(ID) &&
2120         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2121       Diag(Loc, diag::note_include_header_or_declare)
2122           << Context.BuiltinInfo.getHeaderName(ID)
2123           << Context.BuiltinInfo.getName(ID);
2124   }
2125 
2126   if (R.isNull())
2127     return nullptr;
2128 
2129   DeclContext *Parent = Context.getTranslationUnitDecl();
2130   if (getLangOpts().CPlusPlus) {
2131     LinkageSpecDecl *CLinkageDecl =
2132         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2133                                 LinkageSpecDecl::lang_c, false);
2134     CLinkageDecl->setImplicit();
2135     Parent->addDecl(CLinkageDecl);
2136     Parent = CLinkageDecl;
2137   }
2138 
2139   FunctionDecl *New = FunctionDecl::Create(Context,
2140                                            Parent,
2141                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2142                                            SC_Extern,
2143                                            false,
2144                                            R->isFunctionProtoType());
2145   New->setImplicit();
2146 
2147   // Create Decl objects for each parameter, adding them to the
2148   // FunctionDecl.
2149   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2150     SmallVector<ParmVarDecl*, 16> Params;
2151     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2152       ParmVarDecl *parm =
2153           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2154                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2155                               SC_None, nullptr);
2156       parm->setScopeInfo(0, i);
2157       Params.push_back(parm);
2158     }
2159     New->setParams(Params);
2160   }
2161 
2162   AddKnownFunctionAttributes(New);
2163   RegisterLocallyScopedExternCDecl(New, S);
2164 
2165   // TUScope is the translation-unit scope to insert this function into.
2166   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2167   // relate Scopes to DeclContexts, and probably eliminate CurContext
2168   // entirely, but we're not there yet.
2169   DeclContext *SavedContext = CurContext;
2170   CurContext = Parent;
2171   PushOnScopeChains(New, TUScope);
2172   CurContext = SavedContext;
2173   return New;
2174 }
2175 
2176 /// Typedef declarations don't have linkage, but they still denote the same
2177 /// entity if their types are the same.
2178 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2179 /// isSameEntity.
2180 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2181                                                      TypedefNameDecl *Decl,
2182                                                      LookupResult &Previous) {
2183   // This is only interesting when modules are enabled.
2184   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2185     return;
2186 
2187   // Empty sets are uninteresting.
2188   if (Previous.empty())
2189     return;
2190 
2191   LookupResult::Filter Filter = Previous.makeFilter();
2192   while (Filter.hasNext()) {
2193     NamedDecl *Old = Filter.next();
2194 
2195     // Non-hidden declarations are never ignored.
2196     if (S.isVisible(Old))
2197       continue;
2198 
2199     // Declarations of the same entity are not ignored, even if they have
2200     // different linkages.
2201     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2202       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2203                                 Decl->getUnderlyingType()))
2204         continue;
2205 
2206       // If both declarations give a tag declaration a typedef name for linkage
2207       // purposes, then they declare the same entity.
2208       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2209           Decl->getAnonDeclWithTypedefName())
2210         continue;
2211     }
2212 
2213     Filter.erase();
2214   }
2215 
2216   Filter.done();
2217 }
2218 
2219 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2220   QualType OldType;
2221   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2222     OldType = OldTypedef->getUnderlyingType();
2223   else
2224     OldType = Context.getTypeDeclType(Old);
2225   QualType NewType = New->getUnderlyingType();
2226 
2227   if (NewType->isVariablyModifiedType()) {
2228     // Must not redefine a typedef with a variably-modified type.
2229     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2230     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2231       << Kind << NewType;
2232     if (Old->getLocation().isValid())
2233       notePreviousDefinition(Old, New->getLocation());
2234     New->setInvalidDecl();
2235     return true;
2236   }
2237 
2238   if (OldType != NewType &&
2239       !OldType->isDependentType() &&
2240       !NewType->isDependentType() &&
2241       !Context.hasSameType(OldType, NewType)) {
2242     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2243     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2244       << Kind << NewType << OldType;
2245     if (Old->getLocation().isValid())
2246       notePreviousDefinition(Old, New->getLocation());
2247     New->setInvalidDecl();
2248     return true;
2249   }
2250   return false;
2251 }
2252 
2253 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2254 /// same name and scope as a previous declaration 'Old'.  Figure out
2255 /// how to resolve this situation, merging decls or emitting
2256 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2257 ///
2258 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2259                                 LookupResult &OldDecls) {
2260   // If the new decl is known invalid already, don't bother doing any
2261   // merging checks.
2262   if (New->isInvalidDecl()) return;
2263 
2264   // Allow multiple definitions for ObjC built-in typedefs.
2265   // FIXME: Verify the underlying types are equivalent!
2266   if (getLangOpts().ObjC) {
2267     const IdentifierInfo *TypeID = New->getIdentifier();
2268     switch (TypeID->getLength()) {
2269     default: break;
2270     case 2:
2271       {
2272         if (!TypeID->isStr("id"))
2273           break;
2274         QualType T = New->getUnderlyingType();
2275         if (!T->isPointerType())
2276           break;
2277         if (!T->isVoidPointerType()) {
2278           QualType PT = T->castAs<PointerType>()->getPointeeType();
2279           if (!PT->isStructureType())
2280             break;
2281         }
2282         Context.setObjCIdRedefinitionType(T);
2283         // Install the built-in type for 'id', ignoring the current definition.
2284         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2285         return;
2286       }
2287     case 5:
2288       if (!TypeID->isStr("Class"))
2289         break;
2290       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2291       // Install the built-in type for 'Class', ignoring the current definition.
2292       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2293       return;
2294     case 3:
2295       if (!TypeID->isStr("SEL"))
2296         break;
2297       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2298       // Install the built-in type for 'SEL', ignoring the current definition.
2299       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2300       return;
2301     }
2302     // Fall through - the typedef name was not a builtin type.
2303   }
2304 
2305   // Verify the old decl was also a type.
2306   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2307   if (!Old) {
2308     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2309       << New->getDeclName();
2310 
2311     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2312     if (OldD->getLocation().isValid())
2313       notePreviousDefinition(OldD, New->getLocation());
2314 
2315     return New->setInvalidDecl();
2316   }
2317 
2318   // If the old declaration is invalid, just give up here.
2319   if (Old->isInvalidDecl())
2320     return New->setInvalidDecl();
2321 
2322   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2323     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2324     auto *NewTag = New->getAnonDeclWithTypedefName();
2325     NamedDecl *Hidden = nullptr;
2326     if (OldTag && NewTag &&
2327         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2328         !hasVisibleDefinition(OldTag, &Hidden)) {
2329       // There is a definition of this tag, but it is not visible. Use it
2330       // instead of our tag.
2331       New->setTypeForDecl(OldTD->getTypeForDecl());
2332       if (OldTD->isModed())
2333         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2334                                     OldTD->getUnderlyingType());
2335       else
2336         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2337 
2338       // Make the old tag definition visible.
2339       makeMergedDefinitionVisible(Hidden);
2340 
2341       // If this was an unscoped enumeration, yank all of its enumerators
2342       // out of the scope.
2343       if (isa<EnumDecl>(NewTag)) {
2344         Scope *EnumScope = getNonFieldDeclScope(S);
2345         for (auto *D : NewTag->decls()) {
2346           auto *ED = cast<EnumConstantDecl>(D);
2347           assert(EnumScope->isDeclScope(ED));
2348           EnumScope->RemoveDecl(ED);
2349           IdResolver.RemoveDecl(ED);
2350           ED->getLexicalDeclContext()->removeDecl(ED);
2351         }
2352       }
2353     }
2354   }
2355 
2356   // If the typedef types are not identical, reject them in all languages and
2357   // with any extensions enabled.
2358   if (isIncompatibleTypedef(Old, New))
2359     return;
2360 
2361   // The types match.  Link up the redeclaration chain and merge attributes if
2362   // the old declaration was a typedef.
2363   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2364     New->setPreviousDecl(Typedef);
2365     mergeDeclAttributes(New, Old);
2366   }
2367 
2368   if (getLangOpts().MicrosoftExt)
2369     return;
2370 
2371   if (getLangOpts().CPlusPlus) {
2372     // C++ [dcl.typedef]p2:
2373     //   In a given non-class scope, a typedef specifier can be used to
2374     //   redefine the name of any type declared in that scope to refer
2375     //   to the type to which it already refers.
2376     if (!isa<CXXRecordDecl>(CurContext))
2377       return;
2378 
2379     // C++0x [dcl.typedef]p4:
2380     //   In a given class scope, a typedef specifier can be used to redefine
2381     //   any class-name declared in that scope that is not also a typedef-name
2382     //   to refer to the type to which it already refers.
2383     //
2384     // This wording came in via DR424, which was a correction to the
2385     // wording in DR56, which accidentally banned code like:
2386     //
2387     //   struct S {
2388     //     typedef struct A { } A;
2389     //   };
2390     //
2391     // in the C++03 standard. We implement the C++0x semantics, which
2392     // allow the above but disallow
2393     //
2394     //   struct S {
2395     //     typedef int I;
2396     //     typedef int I;
2397     //   };
2398     //
2399     // since that was the intent of DR56.
2400     if (!isa<TypedefNameDecl>(Old))
2401       return;
2402 
2403     Diag(New->getLocation(), diag::err_redefinition)
2404       << New->getDeclName();
2405     notePreviousDefinition(Old, New->getLocation());
2406     return New->setInvalidDecl();
2407   }
2408 
2409   // Modules always permit redefinition of typedefs, as does C11.
2410   if (getLangOpts().Modules || getLangOpts().C11)
2411     return;
2412 
2413   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2414   // is normally mapped to an error, but can be controlled with
2415   // -Wtypedef-redefinition.  If either the original or the redefinition is
2416   // in a system header, don't emit this for compatibility with GCC.
2417   if (getDiagnostics().getSuppressSystemWarnings() &&
2418       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2419       (Old->isImplicit() ||
2420        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2421        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2422     return;
2423 
2424   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2425     << New->getDeclName();
2426   notePreviousDefinition(Old, New->getLocation());
2427 }
2428 
2429 /// DeclhasAttr - returns true if decl Declaration already has the target
2430 /// attribute.
2431 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2432   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2433   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2434   for (const auto *i : D->attrs())
2435     if (i->getKind() == A->getKind()) {
2436       if (Ann) {
2437         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2438           return true;
2439         continue;
2440       }
2441       // FIXME: Don't hardcode this check
2442       if (OA && isa<OwnershipAttr>(i))
2443         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2444       return true;
2445     }
2446 
2447   return false;
2448 }
2449 
2450 static bool isAttributeTargetADefinition(Decl *D) {
2451   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2452     return VD->isThisDeclarationADefinition();
2453   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2454     return TD->isCompleteDefinition() || TD->isBeingDefined();
2455   return true;
2456 }
2457 
2458 /// Merge alignment attributes from \p Old to \p New, taking into account the
2459 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2460 ///
2461 /// \return \c true if any attributes were added to \p New.
2462 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2463   // Look for alignas attributes on Old, and pick out whichever attribute
2464   // specifies the strictest alignment requirement.
2465   AlignedAttr *OldAlignasAttr = nullptr;
2466   AlignedAttr *OldStrictestAlignAttr = nullptr;
2467   unsigned OldAlign = 0;
2468   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2469     // FIXME: We have no way of representing inherited dependent alignments
2470     // in a case like:
2471     //   template<int A, int B> struct alignas(A) X;
2472     //   template<int A, int B> struct alignas(B) X {};
2473     // For now, we just ignore any alignas attributes which are not on the
2474     // definition in such a case.
2475     if (I->isAlignmentDependent())
2476       return false;
2477 
2478     if (I->isAlignas())
2479       OldAlignasAttr = I;
2480 
2481     unsigned Align = I->getAlignment(S.Context);
2482     if (Align > OldAlign) {
2483       OldAlign = Align;
2484       OldStrictestAlignAttr = I;
2485     }
2486   }
2487 
2488   // Look for alignas attributes on New.
2489   AlignedAttr *NewAlignasAttr = nullptr;
2490   unsigned NewAlign = 0;
2491   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2492     if (I->isAlignmentDependent())
2493       return false;
2494 
2495     if (I->isAlignas())
2496       NewAlignasAttr = I;
2497 
2498     unsigned Align = I->getAlignment(S.Context);
2499     if (Align > NewAlign)
2500       NewAlign = Align;
2501   }
2502 
2503   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2504     // Both declarations have 'alignas' attributes. We require them to match.
2505     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2506     // fall short. (If two declarations both have alignas, they must both match
2507     // every definition, and so must match each other if there is a definition.)
2508 
2509     // If either declaration only contains 'alignas(0)' specifiers, then it
2510     // specifies the natural alignment for the type.
2511     if (OldAlign == 0 || NewAlign == 0) {
2512       QualType Ty;
2513       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2514         Ty = VD->getType();
2515       else
2516         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2517 
2518       if (OldAlign == 0)
2519         OldAlign = S.Context.getTypeAlign(Ty);
2520       if (NewAlign == 0)
2521         NewAlign = S.Context.getTypeAlign(Ty);
2522     }
2523 
2524     if (OldAlign != NewAlign) {
2525       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2526         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2527         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2528       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2529     }
2530   }
2531 
2532   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2533     // C++11 [dcl.align]p6:
2534     //   if any declaration of an entity has an alignment-specifier,
2535     //   every defining declaration of that entity shall specify an
2536     //   equivalent alignment.
2537     // C11 6.7.5/7:
2538     //   If the definition of an object does not have an alignment
2539     //   specifier, any other declaration of that object shall also
2540     //   have no alignment specifier.
2541     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2542       << OldAlignasAttr;
2543     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2544       << OldAlignasAttr;
2545   }
2546 
2547   bool AnyAdded = false;
2548 
2549   // Ensure we have an attribute representing the strictest alignment.
2550   if (OldAlign > NewAlign) {
2551     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2552     Clone->setInherited(true);
2553     New->addAttr(Clone);
2554     AnyAdded = true;
2555   }
2556 
2557   // Ensure we have an alignas attribute if the old declaration had one.
2558   if (OldAlignasAttr && !NewAlignasAttr &&
2559       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2560     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2561     Clone->setInherited(true);
2562     New->addAttr(Clone);
2563     AnyAdded = true;
2564   }
2565 
2566   return AnyAdded;
2567 }
2568 
2569 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2570                                const InheritableAttr *Attr,
2571                                Sema::AvailabilityMergeKind AMK) {
2572   // This function copies an attribute Attr from a previous declaration to the
2573   // new declaration D if the new declaration doesn't itself have that attribute
2574   // yet or if that attribute allows duplicates.
2575   // If you're adding a new attribute that requires logic different from
2576   // "use explicit attribute on decl if present, else use attribute from
2577   // previous decl", for example if the attribute needs to be consistent
2578   // between redeclarations, you need to call a custom merge function here.
2579   InheritableAttr *NewAttr = nullptr;
2580   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2581     NewAttr = S.mergeAvailabilityAttr(
2582         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2583         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2584         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2585         AA->getPriority());
2586   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2587     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2588   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2589     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2590   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2591     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2592   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2593     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2594   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2595     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2596                                 FA->getFirstArg());
2597   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2598     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2599   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2600     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2601   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2602     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2603                                        IA->getInheritanceModel());
2604   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2605     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2606                                       &S.Context.Idents.get(AA->getSpelling()));
2607   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2608            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2609             isa<CUDAGlobalAttr>(Attr))) {
2610     // CUDA target attributes are part of function signature for
2611     // overloading purposes and must not be merged.
2612     return false;
2613   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2614     NewAttr = S.mergeMinSizeAttr(D, *MA);
2615   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2616     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2617   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2618     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2619   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2620     NewAttr = S.mergeCommonAttr(D, *CommonA);
2621   else if (isa<AlignedAttr>(Attr))
2622     // AlignedAttrs are handled separately, because we need to handle all
2623     // such attributes on a declaration at the same time.
2624     NewAttr = nullptr;
2625   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2626            (AMK == Sema::AMK_Override ||
2627             AMK == Sema::AMK_ProtocolImplementation))
2628     NewAttr = nullptr;
2629   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2630     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2631   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2632     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2633   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2634     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2635   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2636     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2637   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2638     NewAttr = S.mergeImportNameAttr(D, *INA);
2639   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2640     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2641 
2642   if (NewAttr) {
2643     NewAttr->setInherited(true);
2644     D->addAttr(NewAttr);
2645     if (isa<MSInheritanceAttr>(NewAttr))
2646       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2647     return true;
2648   }
2649 
2650   return false;
2651 }
2652 
2653 static const NamedDecl *getDefinition(const Decl *D) {
2654   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2655     return TD->getDefinition();
2656   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2657     const VarDecl *Def = VD->getDefinition();
2658     if (Def)
2659       return Def;
2660     return VD->getActingDefinition();
2661   }
2662   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2663     return FD->getDefinition();
2664   return nullptr;
2665 }
2666 
2667 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2668   for (const auto *Attribute : D->attrs())
2669     if (Attribute->getKind() == Kind)
2670       return true;
2671   return false;
2672 }
2673 
2674 /// checkNewAttributesAfterDef - If we already have a definition, check that
2675 /// there are no new attributes in this declaration.
2676 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2677   if (!New->hasAttrs())
2678     return;
2679 
2680   const NamedDecl *Def = getDefinition(Old);
2681   if (!Def || Def == New)
2682     return;
2683 
2684   AttrVec &NewAttributes = New->getAttrs();
2685   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2686     const Attr *NewAttribute = NewAttributes[I];
2687 
2688     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2689       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2690         Sema::SkipBodyInfo SkipBody;
2691         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2692 
2693         // If we're skipping this definition, drop the "alias" attribute.
2694         if (SkipBody.ShouldSkip) {
2695           NewAttributes.erase(NewAttributes.begin() + I);
2696           --E;
2697           continue;
2698         }
2699       } else {
2700         VarDecl *VD = cast<VarDecl>(New);
2701         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2702                                 VarDecl::TentativeDefinition
2703                             ? diag::err_alias_after_tentative
2704                             : diag::err_redefinition;
2705         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2706         if (Diag == diag::err_redefinition)
2707           S.notePreviousDefinition(Def, VD->getLocation());
2708         else
2709           S.Diag(Def->getLocation(), diag::note_previous_definition);
2710         VD->setInvalidDecl();
2711       }
2712       ++I;
2713       continue;
2714     }
2715 
2716     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2717       // Tentative definitions are only interesting for the alias check above.
2718       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2719         ++I;
2720         continue;
2721       }
2722     }
2723 
2724     if (hasAttribute(Def, NewAttribute->getKind())) {
2725       ++I;
2726       continue; // regular attr merging will take care of validating this.
2727     }
2728 
2729     if (isa<C11NoReturnAttr>(NewAttribute)) {
2730       // C's _Noreturn is allowed to be added to a function after it is defined.
2731       ++I;
2732       continue;
2733     } else if (isa<UuidAttr>(NewAttribute)) {
2734       // msvc will allow a subsequent definition to add an uuid to a class
2735       ++I;
2736       continue;
2737     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2738       if (AA->isAlignas()) {
2739         // C++11 [dcl.align]p6:
2740         //   if any declaration of an entity has an alignment-specifier,
2741         //   every defining declaration of that entity shall specify an
2742         //   equivalent alignment.
2743         // C11 6.7.5/7:
2744         //   If the definition of an object does not have an alignment
2745         //   specifier, any other declaration of that object shall also
2746         //   have no alignment specifier.
2747         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2748           << AA;
2749         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2750           << AA;
2751         NewAttributes.erase(NewAttributes.begin() + I);
2752         --E;
2753         continue;
2754       }
2755     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2756       // If there is a C definition followed by a redeclaration with this
2757       // attribute then there are two different definitions. In C++, prefer the
2758       // standard diagnostics.
2759       if (!S.getLangOpts().CPlusPlus) {
2760         S.Diag(NewAttribute->getLocation(),
2761                diag::err_loader_uninitialized_redeclaration);
2762         S.Diag(Def->getLocation(), diag::note_previous_definition);
2763         NewAttributes.erase(NewAttributes.begin() + I);
2764         --E;
2765         continue;
2766       }
2767     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2768                cast<VarDecl>(New)->isInline() &&
2769                !cast<VarDecl>(New)->isInlineSpecified()) {
2770       // Don't warn about applying selectany to implicitly inline variables.
2771       // Older compilers and language modes would require the use of selectany
2772       // to make such variables inline, and it would have no effect if we
2773       // honored it.
2774       ++I;
2775       continue;
2776     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2777       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2778       // declarations after defintions.
2779       ++I;
2780       continue;
2781     }
2782 
2783     S.Diag(NewAttribute->getLocation(),
2784            diag::warn_attribute_precede_definition);
2785     S.Diag(Def->getLocation(), diag::note_previous_definition);
2786     NewAttributes.erase(NewAttributes.begin() + I);
2787     --E;
2788   }
2789 }
2790 
2791 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2792                                      const ConstInitAttr *CIAttr,
2793                                      bool AttrBeforeInit) {
2794   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2795 
2796   // Figure out a good way to write this specifier on the old declaration.
2797   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2798   // enough of the attribute list spelling information to extract that without
2799   // heroics.
2800   std::string SuitableSpelling;
2801   if (S.getLangOpts().CPlusPlus20)
2802     SuitableSpelling = std::string(
2803         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2804   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2805     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2806         InsertLoc, {tok::l_square, tok::l_square,
2807                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2808                     S.PP.getIdentifierInfo("require_constant_initialization"),
2809                     tok::r_square, tok::r_square}));
2810   if (SuitableSpelling.empty())
2811     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2812         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2813                     S.PP.getIdentifierInfo("require_constant_initialization"),
2814                     tok::r_paren, tok::r_paren}));
2815   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2816     SuitableSpelling = "constinit";
2817   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2818     SuitableSpelling = "[[clang::require_constant_initialization]]";
2819   if (SuitableSpelling.empty())
2820     SuitableSpelling = "__attribute__((require_constant_initialization))";
2821   SuitableSpelling += " ";
2822 
2823   if (AttrBeforeInit) {
2824     // extern constinit int a;
2825     // int a = 0; // error (missing 'constinit'), accepted as extension
2826     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2827     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2828         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2829     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2830   } else {
2831     // int a = 0;
2832     // constinit extern int a; // error (missing 'constinit')
2833     S.Diag(CIAttr->getLocation(),
2834            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2835                                  : diag::warn_require_const_init_added_too_late)
2836         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2837     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2838         << CIAttr->isConstinit()
2839         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2840   }
2841 }
2842 
2843 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2844 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2845                                AvailabilityMergeKind AMK) {
2846   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2847     UsedAttr *NewAttr = OldAttr->clone(Context);
2848     NewAttr->setInherited(true);
2849     New->addAttr(NewAttr);
2850   }
2851 
2852   if (!Old->hasAttrs() && !New->hasAttrs())
2853     return;
2854 
2855   // [dcl.constinit]p1:
2856   //   If the [constinit] specifier is applied to any declaration of a
2857   //   variable, it shall be applied to the initializing declaration.
2858   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2859   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2860   if (bool(OldConstInit) != bool(NewConstInit)) {
2861     const auto *OldVD = cast<VarDecl>(Old);
2862     auto *NewVD = cast<VarDecl>(New);
2863 
2864     // Find the initializing declaration. Note that we might not have linked
2865     // the new declaration into the redeclaration chain yet.
2866     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2867     if (!InitDecl &&
2868         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2869       InitDecl = NewVD;
2870 
2871     if (InitDecl == NewVD) {
2872       // This is the initializing declaration. If it would inherit 'constinit',
2873       // that's ill-formed. (Note that we do not apply this to the attribute
2874       // form).
2875       if (OldConstInit && OldConstInit->isConstinit())
2876         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2877                                  /*AttrBeforeInit=*/true);
2878     } else if (NewConstInit) {
2879       // This is the first time we've been told that this declaration should
2880       // have a constant initializer. If we already saw the initializing
2881       // declaration, this is too late.
2882       if (InitDecl && InitDecl != NewVD) {
2883         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2884                                  /*AttrBeforeInit=*/false);
2885         NewVD->dropAttr<ConstInitAttr>();
2886       }
2887     }
2888   }
2889 
2890   // Attributes declared post-definition are currently ignored.
2891   checkNewAttributesAfterDef(*this, New, Old);
2892 
2893   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2894     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2895       if (!OldA->isEquivalent(NewA)) {
2896         // This redeclaration changes __asm__ label.
2897         Diag(New->getLocation(), diag::err_different_asm_label);
2898         Diag(OldA->getLocation(), diag::note_previous_declaration);
2899       }
2900     } else if (Old->isUsed()) {
2901       // This redeclaration adds an __asm__ label to a declaration that has
2902       // already been ODR-used.
2903       Diag(New->getLocation(), diag::err_late_asm_label_name)
2904         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2905     }
2906   }
2907 
2908   // Re-declaration cannot add abi_tag's.
2909   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2910     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2911       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2912         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2913                       NewTag) == OldAbiTagAttr->tags_end()) {
2914           Diag(NewAbiTagAttr->getLocation(),
2915                diag::err_new_abi_tag_on_redeclaration)
2916               << NewTag;
2917           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2918         }
2919       }
2920     } else {
2921       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2922       Diag(Old->getLocation(), diag::note_previous_declaration);
2923     }
2924   }
2925 
2926   // This redeclaration adds a section attribute.
2927   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2928     if (auto *VD = dyn_cast<VarDecl>(New)) {
2929       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2930         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2931         Diag(Old->getLocation(), diag::note_previous_declaration);
2932       }
2933     }
2934   }
2935 
2936   // Redeclaration adds code-seg attribute.
2937   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2938   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2939       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2940     Diag(New->getLocation(), diag::warn_mismatched_section)
2941          << 0 /*codeseg*/;
2942     Diag(Old->getLocation(), diag::note_previous_declaration);
2943   }
2944 
2945   if (!Old->hasAttrs())
2946     return;
2947 
2948   bool foundAny = New->hasAttrs();
2949 
2950   // Ensure that any moving of objects within the allocated map is done before
2951   // we process them.
2952   if (!foundAny) New->setAttrs(AttrVec());
2953 
2954   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2955     // Ignore deprecated/unavailable/availability attributes if requested.
2956     AvailabilityMergeKind LocalAMK = AMK_None;
2957     if (isa<DeprecatedAttr>(I) ||
2958         isa<UnavailableAttr>(I) ||
2959         isa<AvailabilityAttr>(I)) {
2960       switch (AMK) {
2961       case AMK_None:
2962         continue;
2963 
2964       case AMK_Redeclaration:
2965       case AMK_Override:
2966       case AMK_ProtocolImplementation:
2967         LocalAMK = AMK;
2968         break;
2969       }
2970     }
2971 
2972     // Already handled.
2973     if (isa<UsedAttr>(I))
2974       continue;
2975 
2976     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2977       foundAny = true;
2978   }
2979 
2980   if (mergeAlignedAttrs(*this, New, Old))
2981     foundAny = true;
2982 
2983   if (!foundAny) New->dropAttrs();
2984 }
2985 
2986 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2987 /// to the new one.
2988 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2989                                      const ParmVarDecl *oldDecl,
2990                                      Sema &S) {
2991   // C++11 [dcl.attr.depend]p2:
2992   //   The first declaration of a function shall specify the
2993   //   carries_dependency attribute for its declarator-id if any declaration
2994   //   of the function specifies the carries_dependency attribute.
2995   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2996   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2997     S.Diag(CDA->getLocation(),
2998            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2999     // Find the first declaration of the parameter.
3000     // FIXME: Should we build redeclaration chains for function parameters?
3001     const FunctionDecl *FirstFD =
3002       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3003     const ParmVarDecl *FirstVD =
3004       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3005     S.Diag(FirstVD->getLocation(),
3006            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3007   }
3008 
3009   if (!oldDecl->hasAttrs())
3010     return;
3011 
3012   bool foundAny = newDecl->hasAttrs();
3013 
3014   // Ensure that any moving of objects within the allocated map is
3015   // done before we process them.
3016   if (!foundAny) newDecl->setAttrs(AttrVec());
3017 
3018   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3019     if (!DeclHasAttr(newDecl, I)) {
3020       InheritableAttr *newAttr =
3021         cast<InheritableParamAttr>(I->clone(S.Context));
3022       newAttr->setInherited(true);
3023       newDecl->addAttr(newAttr);
3024       foundAny = true;
3025     }
3026   }
3027 
3028   if (!foundAny) newDecl->dropAttrs();
3029 }
3030 
3031 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3032                                 const ParmVarDecl *OldParam,
3033                                 Sema &S) {
3034   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3035     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3036       if (*Oldnullability != *Newnullability) {
3037         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3038           << DiagNullabilityKind(
3039                *Newnullability,
3040                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3041                 != 0))
3042           << DiagNullabilityKind(
3043                *Oldnullability,
3044                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3045                 != 0));
3046         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3047       }
3048     } else {
3049       QualType NewT = NewParam->getType();
3050       NewT = S.Context.getAttributedType(
3051                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3052                          NewT, NewT);
3053       NewParam->setType(NewT);
3054     }
3055   }
3056 }
3057 
3058 namespace {
3059 
3060 /// Used in MergeFunctionDecl to keep track of function parameters in
3061 /// C.
3062 struct GNUCompatibleParamWarning {
3063   ParmVarDecl *OldParm;
3064   ParmVarDecl *NewParm;
3065   QualType PromotedType;
3066 };
3067 
3068 } // end anonymous namespace
3069 
3070 // Determine whether the previous declaration was a definition, implicit
3071 // declaration, or a declaration.
3072 template <typename T>
3073 static std::pair<diag::kind, SourceLocation>
3074 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3075   diag::kind PrevDiag;
3076   SourceLocation OldLocation = Old->getLocation();
3077   if (Old->isThisDeclarationADefinition())
3078     PrevDiag = diag::note_previous_definition;
3079   else if (Old->isImplicit()) {
3080     PrevDiag = diag::note_previous_implicit_declaration;
3081     if (OldLocation.isInvalid())
3082       OldLocation = New->getLocation();
3083   } else
3084     PrevDiag = diag::note_previous_declaration;
3085   return std::make_pair(PrevDiag, OldLocation);
3086 }
3087 
3088 /// canRedefineFunction - checks if a function can be redefined. Currently,
3089 /// only extern inline functions can be redefined, and even then only in
3090 /// GNU89 mode.
3091 static bool canRedefineFunction(const FunctionDecl *FD,
3092                                 const LangOptions& LangOpts) {
3093   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3094           !LangOpts.CPlusPlus &&
3095           FD->isInlineSpecified() &&
3096           FD->getStorageClass() == SC_Extern);
3097 }
3098 
3099 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3100   const AttributedType *AT = T->getAs<AttributedType>();
3101   while (AT && !AT->isCallingConv())
3102     AT = AT->getModifiedType()->getAs<AttributedType>();
3103   return AT;
3104 }
3105 
3106 template <typename T>
3107 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3108   const DeclContext *DC = Old->getDeclContext();
3109   if (DC->isRecord())
3110     return false;
3111 
3112   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3113   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3114     return true;
3115   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3116     return true;
3117   return false;
3118 }
3119 
3120 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3121 static bool isExternC(VarTemplateDecl *) { return false; }
3122 
3123 /// Check whether a redeclaration of an entity introduced by a
3124 /// using-declaration is valid, given that we know it's not an overload
3125 /// (nor a hidden tag declaration).
3126 template<typename ExpectedDecl>
3127 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3128                                    ExpectedDecl *New) {
3129   // C++11 [basic.scope.declarative]p4:
3130   //   Given a set of declarations in a single declarative region, each of
3131   //   which specifies the same unqualified name,
3132   //   -- they shall all refer to the same entity, or all refer to functions
3133   //      and function templates; or
3134   //   -- exactly one declaration shall declare a class name or enumeration
3135   //      name that is not a typedef name and the other declarations shall all
3136   //      refer to the same variable or enumerator, or all refer to functions
3137   //      and function templates; in this case the class name or enumeration
3138   //      name is hidden (3.3.10).
3139 
3140   // C++11 [namespace.udecl]p14:
3141   //   If a function declaration in namespace scope or block scope has the
3142   //   same name and the same parameter-type-list as a function introduced
3143   //   by a using-declaration, and the declarations do not declare the same
3144   //   function, the program is ill-formed.
3145 
3146   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3147   if (Old &&
3148       !Old->getDeclContext()->getRedeclContext()->Equals(
3149           New->getDeclContext()->getRedeclContext()) &&
3150       !(isExternC(Old) && isExternC(New)))
3151     Old = nullptr;
3152 
3153   if (!Old) {
3154     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3155     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3156     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3157     return true;
3158   }
3159   return false;
3160 }
3161 
3162 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3163                                             const FunctionDecl *B) {
3164   assert(A->getNumParams() == B->getNumParams());
3165 
3166   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3167     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3168     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3169     if (AttrA == AttrB)
3170       return true;
3171     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3172            AttrA->isDynamic() == AttrB->isDynamic();
3173   };
3174 
3175   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3176 }
3177 
3178 /// If necessary, adjust the semantic declaration context for a qualified
3179 /// declaration to name the correct inline namespace within the qualifier.
3180 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3181                                                DeclaratorDecl *OldD) {
3182   // The only case where we need to update the DeclContext is when
3183   // redeclaration lookup for a qualified name finds a declaration
3184   // in an inline namespace within the context named by the qualifier:
3185   //
3186   //   inline namespace N { int f(); }
3187   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3188   //
3189   // For unqualified declarations, the semantic context *can* change
3190   // along the redeclaration chain (for local extern declarations,
3191   // extern "C" declarations, and friend declarations in particular).
3192   if (!NewD->getQualifier())
3193     return;
3194 
3195   // NewD is probably already in the right context.
3196   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3197   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3198   if (NamedDC->Equals(SemaDC))
3199     return;
3200 
3201   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3202           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3203          "unexpected context for redeclaration");
3204 
3205   auto *LexDC = NewD->getLexicalDeclContext();
3206   auto FixSemaDC = [=](NamedDecl *D) {
3207     if (!D)
3208       return;
3209     D->setDeclContext(SemaDC);
3210     D->setLexicalDeclContext(LexDC);
3211   };
3212 
3213   FixSemaDC(NewD);
3214   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3215     FixSemaDC(FD->getDescribedFunctionTemplate());
3216   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3217     FixSemaDC(VD->getDescribedVarTemplate());
3218 }
3219 
3220 /// MergeFunctionDecl - We just parsed a function 'New' from
3221 /// declarator D which has the same name and scope as a previous
3222 /// declaration 'Old'.  Figure out how to resolve this situation,
3223 /// merging decls or emitting diagnostics as appropriate.
3224 ///
3225 /// In C++, New and Old must be declarations that are not
3226 /// overloaded. Use IsOverload to determine whether New and Old are
3227 /// overloaded, and to select the Old declaration that New should be
3228 /// merged with.
3229 ///
3230 /// Returns true if there was an error, false otherwise.
3231 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3232                              Scope *S, bool MergeTypeWithOld) {
3233   // Verify the old decl was also a function.
3234   FunctionDecl *Old = OldD->getAsFunction();
3235   if (!Old) {
3236     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3237       if (New->getFriendObjectKind()) {
3238         Diag(New->getLocation(), diag::err_using_decl_friend);
3239         Diag(Shadow->getTargetDecl()->getLocation(),
3240              diag::note_using_decl_target);
3241         Diag(Shadow->getUsingDecl()->getLocation(),
3242              diag::note_using_decl) << 0;
3243         return true;
3244       }
3245 
3246       // Check whether the two declarations might declare the same function.
3247       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3248         return true;
3249       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3250     } else {
3251       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3252         << New->getDeclName();
3253       notePreviousDefinition(OldD, New->getLocation());
3254       return true;
3255     }
3256   }
3257 
3258   // If the old declaration is invalid, just give up here.
3259   if (Old->isInvalidDecl())
3260     return true;
3261 
3262   // Disallow redeclaration of some builtins.
3263   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3264     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3265     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3266         << Old << Old->getType();
3267     return true;
3268   }
3269 
3270   diag::kind PrevDiag;
3271   SourceLocation OldLocation;
3272   std::tie(PrevDiag, OldLocation) =
3273       getNoteDiagForInvalidRedeclaration(Old, New);
3274 
3275   // Don't complain about this if we're in GNU89 mode and the old function
3276   // is an extern inline function.
3277   // Don't complain about specializations. They are not supposed to have
3278   // storage classes.
3279   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3280       New->getStorageClass() == SC_Static &&
3281       Old->hasExternalFormalLinkage() &&
3282       !New->getTemplateSpecializationInfo() &&
3283       !canRedefineFunction(Old, getLangOpts())) {
3284     if (getLangOpts().MicrosoftExt) {
3285       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3286       Diag(OldLocation, PrevDiag);
3287     } else {
3288       Diag(New->getLocation(), diag::err_static_non_static) << New;
3289       Diag(OldLocation, PrevDiag);
3290       return true;
3291     }
3292   }
3293 
3294   if (New->hasAttr<InternalLinkageAttr>() &&
3295       !Old->hasAttr<InternalLinkageAttr>()) {
3296     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3297         << New->getDeclName();
3298     notePreviousDefinition(Old, New->getLocation());
3299     New->dropAttr<InternalLinkageAttr>();
3300   }
3301 
3302   if (CheckRedeclarationModuleOwnership(New, Old))
3303     return true;
3304 
3305   if (!getLangOpts().CPlusPlus) {
3306     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3307     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3308       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3309         << New << OldOvl;
3310 
3311       // Try our best to find a decl that actually has the overloadable
3312       // attribute for the note. In most cases (e.g. programs with only one
3313       // broken declaration/definition), this won't matter.
3314       //
3315       // FIXME: We could do this if we juggled some extra state in
3316       // OverloadableAttr, rather than just removing it.
3317       const Decl *DiagOld = Old;
3318       if (OldOvl) {
3319         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3320           const auto *A = D->getAttr<OverloadableAttr>();
3321           return A && !A->isImplicit();
3322         });
3323         // If we've implicitly added *all* of the overloadable attrs to this
3324         // chain, emitting a "previous redecl" note is pointless.
3325         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3326       }
3327 
3328       if (DiagOld)
3329         Diag(DiagOld->getLocation(),
3330              diag::note_attribute_overloadable_prev_overload)
3331           << OldOvl;
3332 
3333       if (OldOvl)
3334         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3335       else
3336         New->dropAttr<OverloadableAttr>();
3337     }
3338   }
3339 
3340   // If a function is first declared with a calling convention, but is later
3341   // declared or defined without one, all following decls assume the calling
3342   // convention of the first.
3343   //
3344   // It's OK if a function is first declared without a calling convention,
3345   // but is later declared or defined with the default calling convention.
3346   //
3347   // To test if either decl has an explicit calling convention, we look for
3348   // AttributedType sugar nodes on the type as written.  If they are missing or
3349   // were canonicalized away, we assume the calling convention was implicit.
3350   //
3351   // Note also that we DO NOT return at this point, because we still have
3352   // other tests to run.
3353   QualType OldQType = Context.getCanonicalType(Old->getType());
3354   QualType NewQType = Context.getCanonicalType(New->getType());
3355   const FunctionType *OldType = cast<FunctionType>(OldQType);
3356   const FunctionType *NewType = cast<FunctionType>(NewQType);
3357   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3358   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3359   bool RequiresAdjustment = false;
3360 
3361   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3362     FunctionDecl *First = Old->getFirstDecl();
3363     const FunctionType *FT =
3364         First->getType().getCanonicalType()->castAs<FunctionType>();
3365     FunctionType::ExtInfo FI = FT->getExtInfo();
3366     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3367     if (!NewCCExplicit) {
3368       // Inherit the CC from the previous declaration if it was specified
3369       // there but not here.
3370       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3371       RequiresAdjustment = true;
3372     } else if (New->getBuiltinID()) {
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 
3806       // If this is a global redeclaration, just forget hereafter
3807       // about the "builtin-ness" of the function.
3808       //
3809       // Doing this for local extern declarations is problematic.  If
3810       // the builtin declaration remains visible, a second invalid
3811       // local declaration will produce a hard error; if it doesn't
3812       // remain visible, a single bogus local redeclaration (which is
3813       // actually only a warning) could break all the downstream code.
3814       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3815         New->getIdentifier()->revertBuiltin();
3816 
3817       return false;
3818     }
3819 
3820     PrevDiag = diag::note_previous_builtin_declaration;
3821   }
3822 
3823   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3824   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3825   return true;
3826 }
3827 
3828 /// Completes the merge of two function declarations that are
3829 /// known to be compatible.
3830 ///
3831 /// This routine handles the merging of attributes and other
3832 /// properties of function declarations from the old declaration to
3833 /// the new declaration, once we know that New is in fact a
3834 /// redeclaration of Old.
3835 ///
3836 /// \returns false
3837 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3838                                         Scope *S, bool MergeTypeWithOld) {
3839   // Merge the attributes
3840   mergeDeclAttributes(New, Old);
3841 
3842   // Merge "pure" flag.
3843   if (Old->isPure())
3844     New->setPure();
3845 
3846   // Merge "used" flag.
3847   if (Old->getMostRecentDecl()->isUsed(false))
3848     New->setIsUsed();
3849 
3850   // Merge attributes from the parameters.  These can mismatch with K&R
3851   // declarations.
3852   if (New->getNumParams() == Old->getNumParams())
3853       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3854         ParmVarDecl *NewParam = New->getParamDecl(i);
3855         ParmVarDecl *OldParam = Old->getParamDecl(i);
3856         mergeParamDeclAttributes(NewParam, OldParam, *this);
3857         mergeParamDeclTypes(NewParam, OldParam, *this);
3858       }
3859 
3860   if (getLangOpts().CPlusPlus)
3861     return MergeCXXFunctionDecl(New, Old, S);
3862 
3863   // Merge the function types so the we get the composite types for the return
3864   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3865   // was visible.
3866   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3867   if (!Merged.isNull() && MergeTypeWithOld)
3868     New->setType(Merged);
3869 
3870   return false;
3871 }
3872 
3873 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3874                                 ObjCMethodDecl *oldMethod) {
3875   // Merge the attributes, including deprecated/unavailable
3876   AvailabilityMergeKind MergeKind =
3877     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3878       ? AMK_ProtocolImplementation
3879       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3880                                                        : AMK_Override;
3881 
3882   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3883 
3884   // Merge attributes from the parameters.
3885   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3886                                        oe = oldMethod->param_end();
3887   for (ObjCMethodDecl::param_iterator
3888          ni = newMethod->param_begin(), ne = newMethod->param_end();
3889        ni != ne && oi != oe; ++ni, ++oi)
3890     mergeParamDeclAttributes(*ni, *oi, *this);
3891 
3892   CheckObjCMethodOverride(newMethod, oldMethod);
3893 }
3894 
3895 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3896   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3897 
3898   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3899          ? diag::err_redefinition_different_type
3900          : diag::err_redeclaration_different_type)
3901     << New->getDeclName() << New->getType() << Old->getType();
3902 
3903   diag::kind PrevDiag;
3904   SourceLocation OldLocation;
3905   std::tie(PrevDiag, OldLocation)
3906     = getNoteDiagForInvalidRedeclaration(Old, New);
3907   S.Diag(OldLocation, PrevDiag);
3908   New->setInvalidDecl();
3909 }
3910 
3911 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3912 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3913 /// emitting diagnostics as appropriate.
3914 ///
3915 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3916 /// to here in AddInitializerToDecl. We can't check them before the initializer
3917 /// is attached.
3918 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3919                              bool MergeTypeWithOld) {
3920   if (New->isInvalidDecl() || Old->isInvalidDecl())
3921     return;
3922 
3923   QualType MergedT;
3924   if (getLangOpts().CPlusPlus) {
3925     if (New->getType()->isUndeducedType()) {
3926       // We don't know what the new type is until the initializer is attached.
3927       return;
3928     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3929       // These could still be something that needs exception specs checked.
3930       return MergeVarDeclExceptionSpecs(New, Old);
3931     }
3932     // C++ [basic.link]p10:
3933     //   [...] the types specified by all declarations referring to a given
3934     //   object or function shall be identical, except that declarations for an
3935     //   array object can specify array types that differ by the presence or
3936     //   absence of a major array bound (8.3.4).
3937     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3938       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3939       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3940 
3941       // We are merging a variable declaration New into Old. If it has an array
3942       // bound, and that bound differs from Old's bound, we should diagnose the
3943       // mismatch.
3944       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3945         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3946              PrevVD = PrevVD->getPreviousDecl()) {
3947           QualType PrevVDTy = PrevVD->getType();
3948           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3949             continue;
3950 
3951           if (!Context.hasSameType(New->getType(), PrevVDTy))
3952             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3953         }
3954       }
3955 
3956       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3957         if (Context.hasSameType(OldArray->getElementType(),
3958                                 NewArray->getElementType()))
3959           MergedT = New->getType();
3960       }
3961       // FIXME: Check visibility. New is hidden but has a complete type. If New
3962       // has no array bound, it should not inherit one from Old, if Old is not
3963       // visible.
3964       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3965         if (Context.hasSameType(OldArray->getElementType(),
3966                                 NewArray->getElementType()))
3967           MergedT = Old->getType();
3968       }
3969     }
3970     else if (New->getType()->isObjCObjectPointerType() &&
3971                Old->getType()->isObjCObjectPointerType()) {
3972       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3973                                               Old->getType());
3974     }
3975   } else {
3976     // C 6.2.7p2:
3977     //   All declarations that refer to the same object or function shall have
3978     //   compatible type.
3979     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3980   }
3981   if (MergedT.isNull()) {
3982     // It's OK if we couldn't merge types if either type is dependent, for a
3983     // block-scope variable. In other cases (static data members of class
3984     // templates, variable templates, ...), we require the types to be
3985     // equivalent.
3986     // FIXME: The C++ standard doesn't say anything about this.
3987     if ((New->getType()->isDependentType() ||
3988          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3989       // If the old type was dependent, we can't merge with it, so the new type
3990       // becomes dependent for now. We'll reproduce the original type when we
3991       // instantiate the TypeSourceInfo for the variable.
3992       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3993         New->setType(Context.DependentTy);
3994       return;
3995     }
3996     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3997   }
3998 
3999   // Don't actually update the type on the new declaration if the old
4000   // declaration was an extern declaration in a different scope.
4001   if (MergeTypeWithOld)
4002     New->setType(MergedT);
4003 }
4004 
4005 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4006                                   LookupResult &Previous) {
4007   // C11 6.2.7p4:
4008   //   For an identifier with internal or external linkage declared
4009   //   in a scope in which a prior declaration of that identifier is
4010   //   visible, if the prior declaration specifies internal or
4011   //   external linkage, the type of the identifier at the later
4012   //   declaration becomes the composite type.
4013   //
4014   // If the variable isn't visible, we do not merge with its type.
4015   if (Previous.isShadowed())
4016     return false;
4017 
4018   if (S.getLangOpts().CPlusPlus) {
4019     // C++11 [dcl.array]p3:
4020     //   If there is a preceding declaration of the entity in the same
4021     //   scope in which the bound was specified, an omitted array bound
4022     //   is taken to be the same as in that earlier declaration.
4023     return NewVD->isPreviousDeclInSameBlockScope() ||
4024            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4025             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4026   } else {
4027     // If the old declaration was function-local, don't merge with its
4028     // type unless we're in the same function.
4029     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4030            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4031   }
4032 }
4033 
4034 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4035 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4036 /// situation, merging decls or emitting diagnostics as appropriate.
4037 ///
4038 /// Tentative definition rules (C99 6.9.2p2) are checked by
4039 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4040 /// definitions here, since the initializer hasn't been attached.
4041 ///
4042 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4043   // If the new decl is already invalid, don't do any other checking.
4044   if (New->isInvalidDecl())
4045     return;
4046 
4047   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4048     return;
4049 
4050   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4051 
4052   // Verify the old decl was also a variable or variable template.
4053   VarDecl *Old = nullptr;
4054   VarTemplateDecl *OldTemplate = nullptr;
4055   if (Previous.isSingleResult()) {
4056     if (NewTemplate) {
4057       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4058       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4059 
4060       if (auto *Shadow =
4061               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4062         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4063           return New->setInvalidDecl();
4064     } else {
4065       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4066 
4067       if (auto *Shadow =
4068               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4069         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4070           return New->setInvalidDecl();
4071     }
4072   }
4073   if (!Old) {
4074     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4075         << New->getDeclName();
4076     notePreviousDefinition(Previous.getRepresentativeDecl(),
4077                            New->getLocation());
4078     return New->setInvalidDecl();
4079   }
4080 
4081   // Ensure the template parameters are compatible.
4082   if (NewTemplate &&
4083       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4084                                       OldTemplate->getTemplateParameters(),
4085                                       /*Complain=*/true, TPL_TemplateMatch))
4086     return New->setInvalidDecl();
4087 
4088   // C++ [class.mem]p1:
4089   //   A member shall not be declared twice in the member-specification [...]
4090   //
4091   // Here, we need only consider static data members.
4092   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4093     Diag(New->getLocation(), diag::err_duplicate_member)
4094       << New->getIdentifier();
4095     Diag(Old->getLocation(), diag::note_previous_declaration);
4096     New->setInvalidDecl();
4097   }
4098 
4099   mergeDeclAttributes(New, Old);
4100   // Warn if an already-declared variable is made a weak_import in a subsequent
4101   // declaration
4102   if (New->hasAttr<WeakImportAttr>() &&
4103       Old->getStorageClass() == SC_None &&
4104       !Old->hasAttr<WeakImportAttr>()) {
4105     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4106     notePreviousDefinition(Old, New->getLocation());
4107     // Remove weak_import attribute on new declaration.
4108     New->dropAttr<WeakImportAttr>();
4109   }
4110 
4111   if (New->hasAttr<InternalLinkageAttr>() &&
4112       !Old->hasAttr<InternalLinkageAttr>()) {
4113     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4114         << New->getDeclName();
4115     notePreviousDefinition(Old, New->getLocation());
4116     New->dropAttr<InternalLinkageAttr>();
4117   }
4118 
4119   // Merge the types.
4120   VarDecl *MostRecent = Old->getMostRecentDecl();
4121   if (MostRecent != Old) {
4122     MergeVarDeclTypes(New, MostRecent,
4123                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4124     if (New->isInvalidDecl())
4125       return;
4126   }
4127 
4128   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4129   if (New->isInvalidDecl())
4130     return;
4131 
4132   diag::kind PrevDiag;
4133   SourceLocation OldLocation;
4134   std::tie(PrevDiag, OldLocation) =
4135       getNoteDiagForInvalidRedeclaration(Old, New);
4136 
4137   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4138   if (New->getStorageClass() == SC_Static &&
4139       !New->isStaticDataMember() &&
4140       Old->hasExternalFormalLinkage()) {
4141     if (getLangOpts().MicrosoftExt) {
4142       Diag(New->getLocation(), diag::ext_static_non_static)
4143           << New->getDeclName();
4144       Diag(OldLocation, PrevDiag);
4145     } else {
4146       Diag(New->getLocation(), diag::err_static_non_static)
4147           << New->getDeclName();
4148       Diag(OldLocation, PrevDiag);
4149       return New->setInvalidDecl();
4150     }
4151   }
4152   // C99 6.2.2p4:
4153   //   For an identifier declared with the storage-class specifier
4154   //   extern in a scope in which a prior declaration of that
4155   //   identifier is visible,23) if the prior declaration specifies
4156   //   internal or external linkage, the linkage of the identifier at
4157   //   the later declaration is the same as the linkage specified at
4158   //   the prior declaration. If no prior declaration is visible, or
4159   //   if the prior declaration specifies no linkage, then the
4160   //   identifier has external linkage.
4161   if (New->hasExternalStorage() && Old->hasLinkage())
4162     /* Okay */;
4163   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4164            !New->isStaticDataMember() &&
4165            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4166     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4167     Diag(OldLocation, PrevDiag);
4168     return New->setInvalidDecl();
4169   }
4170 
4171   // Check if extern is followed by non-extern and vice-versa.
4172   if (New->hasExternalStorage() &&
4173       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4174     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4175     Diag(OldLocation, PrevDiag);
4176     return New->setInvalidDecl();
4177   }
4178   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4179       !New->hasExternalStorage()) {
4180     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4181     Diag(OldLocation, PrevDiag);
4182     return New->setInvalidDecl();
4183   }
4184 
4185   if (CheckRedeclarationModuleOwnership(New, Old))
4186     return;
4187 
4188   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4189 
4190   // FIXME: The test for external storage here seems wrong? We still
4191   // need to check for mismatches.
4192   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4193       // Don't complain about out-of-line definitions of static members.
4194       !(Old->getLexicalDeclContext()->isRecord() &&
4195         !New->getLexicalDeclContext()->isRecord())) {
4196     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4197     Diag(OldLocation, PrevDiag);
4198     return New->setInvalidDecl();
4199   }
4200 
4201   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4202     if (VarDecl *Def = Old->getDefinition()) {
4203       // C++1z [dcl.fcn.spec]p4:
4204       //   If the definition of a variable appears in a translation unit before
4205       //   its first declaration as inline, the program is ill-formed.
4206       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4207       Diag(Def->getLocation(), diag::note_previous_definition);
4208     }
4209   }
4210 
4211   // If this redeclaration makes the variable inline, we may need to add it to
4212   // UndefinedButUsed.
4213   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4214       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4215     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4216                                            SourceLocation()));
4217 
4218   if (New->getTLSKind() != Old->getTLSKind()) {
4219     if (!Old->getTLSKind()) {
4220       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4221       Diag(OldLocation, PrevDiag);
4222     } else if (!New->getTLSKind()) {
4223       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4224       Diag(OldLocation, PrevDiag);
4225     } else {
4226       // Do not allow redeclaration to change the variable between requiring
4227       // static and dynamic initialization.
4228       // FIXME: GCC allows this, but uses the TLS keyword on the first
4229       // declaration to determine the kind. Do we need to be compatible here?
4230       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4231         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4232       Diag(OldLocation, PrevDiag);
4233     }
4234   }
4235 
4236   // C++ doesn't have tentative definitions, so go right ahead and check here.
4237   if (getLangOpts().CPlusPlus &&
4238       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4239     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4240         Old->getCanonicalDecl()->isConstexpr()) {
4241       // This definition won't be a definition any more once it's been merged.
4242       Diag(New->getLocation(),
4243            diag::warn_deprecated_redundant_constexpr_static_def);
4244     } else if (VarDecl *Def = Old->getDefinition()) {
4245       if (checkVarDeclRedefinition(Def, New))
4246         return;
4247     }
4248   }
4249 
4250   if (haveIncompatibleLanguageLinkages(Old, New)) {
4251     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4252     Diag(OldLocation, PrevDiag);
4253     New->setInvalidDecl();
4254     return;
4255   }
4256 
4257   // Merge "used" flag.
4258   if (Old->getMostRecentDecl()->isUsed(false))
4259     New->setIsUsed();
4260 
4261   // Keep a chain of previous declarations.
4262   New->setPreviousDecl(Old);
4263   if (NewTemplate)
4264     NewTemplate->setPreviousDecl(OldTemplate);
4265   adjustDeclContextForDeclaratorDecl(New, Old);
4266 
4267   // Inherit access appropriately.
4268   New->setAccess(Old->getAccess());
4269   if (NewTemplate)
4270     NewTemplate->setAccess(New->getAccess());
4271 
4272   if (Old->isInline())
4273     New->setImplicitlyInline();
4274 }
4275 
4276 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4277   SourceManager &SrcMgr = getSourceManager();
4278   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4279   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4280   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4281   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4282   auto &HSI = PP.getHeaderSearchInfo();
4283   StringRef HdrFilename =
4284       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4285 
4286   auto noteFromModuleOrInclude = [&](Module *Mod,
4287                                      SourceLocation IncLoc) -> bool {
4288     // Redefinition errors with modules are common with non modular mapped
4289     // headers, example: a non-modular header H in module A that also gets
4290     // included directly in a TU. Pointing twice to the same header/definition
4291     // is confusing, try to get better diagnostics when modules is on.
4292     if (IncLoc.isValid()) {
4293       if (Mod) {
4294         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4295             << HdrFilename.str() << Mod->getFullModuleName();
4296         if (!Mod->DefinitionLoc.isInvalid())
4297           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4298               << Mod->getFullModuleName();
4299       } else {
4300         Diag(IncLoc, diag::note_redefinition_include_same_file)
4301             << HdrFilename.str();
4302       }
4303       return true;
4304     }
4305 
4306     return false;
4307   };
4308 
4309   // Is it the same file and same offset? Provide more information on why
4310   // this leads to a redefinition error.
4311   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4312     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4313     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4314     bool EmittedDiag =
4315         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4316     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4317 
4318     // If the header has no guards, emit a note suggesting one.
4319     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4320       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4321 
4322     if (EmittedDiag)
4323       return;
4324   }
4325 
4326   // Redefinition coming from different files or couldn't do better above.
4327   if (Old->getLocation().isValid())
4328     Diag(Old->getLocation(), diag::note_previous_definition);
4329 }
4330 
4331 /// We've just determined that \p Old and \p New both appear to be definitions
4332 /// of the same variable. Either diagnose or fix the problem.
4333 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4334   if (!hasVisibleDefinition(Old) &&
4335       (New->getFormalLinkage() == InternalLinkage ||
4336        New->isInline() ||
4337        New->getDescribedVarTemplate() ||
4338        New->getNumTemplateParameterLists() ||
4339        New->getDeclContext()->isDependentContext())) {
4340     // The previous definition is hidden, and multiple definitions are
4341     // permitted (in separate TUs). Demote this to a declaration.
4342     New->demoteThisDefinitionToDeclaration();
4343 
4344     // Make the canonical definition visible.
4345     if (auto *OldTD = Old->getDescribedVarTemplate())
4346       makeMergedDefinitionVisible(OldTD);
4347     makeMergedDefinitionVisible(Old);
4348     return false;
4349   } else {
4350     Diag(New->getLocation(), diag::err_redefinition) << New;
4351     notePreviousDefinition(Old, New->getLocation());
4352     New->setInvalidDecl();
4353     return true;
4354   }
4355 }
4356 
4357 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4358 /// no declarator (e.g. "struct foo;") is parsed.
4359 Decl *
4360 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4361                                  RecordDecl *&AnonRecord) {
4362   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4363                                     AnonRecord);
4364 }
4365 
4366 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4367 // disambiguate entities defined in different scopes.
4368 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4369 // compatibility.
4370 // We will pick our mangling number depending on which version of MSVC is being
4371 // targeted.
4372 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4373   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4374              ? S->getMSCurManglingNumber()
4375              : S->getMSLastManglingNumber();
4376 }
4377 
4378 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4379   if (!Context.getLangOpts().CPlusPlus)
4380     return;
4381 
4382   if (isa<CXXRecordDecl>(Tag->getParent())) {
4383     // If this tag is the direct child of a class, number it if
4384     // it is anonymous.
4385     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4386       return;
4387     MangleNumberingContext &MCtx =
4388         Context.getManglingNumberContext(Tag->getParent());
4389     Context.setManglingNumber(
4390         Tag, MCtx.getManglingNumber(
4391                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4392     return;
4393   }
4394 
4395   // If this tag isn't a direct child of a class, number it if it is local.
4396   MangleNumberingContext *MCtx;
4397   Decl *ManglingContextDecl;
4398   std::tie(MCtx, ManglingContextDecl) =
4399       getCurrentMangleNumberContext(Tag->getDeclContext());
4400   if (MCtx) {
4401     Context.setManglingNumber(
4402         Tag, MCtx->getManglingNumber(
4403                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4404   }
4405 }
4406 
4407 namespace {
4408 struct NonCLikeKind {
4409   enum {
4410     None,
4411     BaseClass,
4412     DefaultMemberInit,
4413     Lambda,
4414     Friend,
4415     OtherMember,
4416     Invalid,
4417   } Kind = None;
4418   SourceRange Range;
4419 
4420   explicit operator bool() { return Kind != None; }
4421 };
4422 }
4423 
4424 /// Determine whether a class is C-like, according to the rules of C++
4425 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4426 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4427   if (RD->isInvalidDecl())
4428     return {NonCLikeKind::Invalid, {}};
4429 
4430   // C++ [dcl.typedef]p9: [P1766R1]
4431   //   An unnamed class with a typedef name for linkage purposes shall not
4432   //
4433   //    -- have any base classes
4434   if (RD->getNumBases())
4435     return {NonCLikeKind::BaseClass,
4436             SourceRange(RD->bases_begin()->getBeginLoc(),
4437                         RD->bases_end()[-1].getEndLoc())};
4438   bool Invalid = false;
4439   for (Decl *D : RD->decls()) {
4440     // Don't complain about things we already diagnosed.
4441     if (D->isInvalidDecl()) {
4442       Invalid = true;
4443       continue;
4444     }
4445 
4446     //  -- have any [...] default member initializers
4447     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4448       if (FD->hasInClassInitializer()) {
4449         auto *Init = FD->getInClassInitializer();
4450         return {NonCLikeKind::DefaultMemberInit,
4451                 Init ? Init->getSourceRange() : D->getSourceRange()};
4452       }
4453       continue;
4454     }
4455 
4456     // FIXME: We don't allow friend declarations. This violates the wording of
4457     // P1766, but not the intent.
4458     if (isa<FriendDecl>(D))
4459       return {NonCLikeKind::Friend, D->getSourceRange()};
4460 
4461     //  -- declare any members other than non-static data members, member
4462     //     enumerations, or member classes,
4463     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4464         isa<EnumDecl>(D))
4465       continue;
4466     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4467     if (!MemberRD) {
4468       if (D->isImplicit())
4469         continue;
4470       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4471     }
4472 
4473     //  -- contain a lambda-expression,
4474     if (MemberRD->isLambda())
4475       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4476 
4477     //  and all member classes shall also satisfy these requirements
4478     //  (recursively).
4479     if (MemberRD->isThisDeclarationADefinition()) {
4480       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4481         return Kind;
4482     }
4483   }
4484 
4485   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4486 }
4487 
4488 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4489                                         TypedefNameDecl *NewTD) {
4490   if (TagFromDeclSpec->isInvalidDecl())
4491     return;
4492 
4493   // Do nothing if the tag already has a name for linkage purposes.
4494   if (TagFromDeclSpec->hasNameForLinkage())
4495     return;
4496 
4497   // A well-formed anonymous tag must always be a TUK_Definition.
4498   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4499 
4500   // The type must match the tag exactly;  no qualifiers allowed.
4501   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4502                            Context.getTagDeclType(TagFromDeclSpec))) {
4503     if (getLangOpts().CPlusPlus)
4504       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4505     return;
4506   }
4507 
4508   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4509   //   An unnamed class with a typedef name for linkage purposes shall [be
4510   //   C-like].
4511   //
4512   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4513   // shouldn't happen, but there are constructs that the language rule doesn't
4514   // disallow for which we can't reasonably avoid computing linkage early.
4515   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4516   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4517                              : NonCLikeKind();
4518   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4519   if (NonCLike || ChangesLinkage) {
4520     if (NonCLike.Kind == NonCLikeKind::Invalid)
4521       return;
4522 
4523     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4524     if (ChangesLinkage) {
4525       // If the linkage changes, we can't accept this as an extension.
4526       if (NonCLike.Kind == NonCLikeKind::None)
4527         DiagID = diag::err_typedef_changes_linkage;
4528       else
4529         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4530     }
4531 
4532     SourceLocation FixitLoc =
4533         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4534     llvm::SmallString<40> TextToInsert;
4535     TextToInsert += ' ';
4536     TextToInsert += NewTD->getIdentifier()->getName();
4537 
4538     Diag(FixitLoc, DiagID)
4539       << isa<TypeAliasDecl>(NewTD)
4540       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4541     if (NonCLike.Kind != NonCLikeKind::None) {
4542       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4543         << NonCLike.Kind - 1 << NonCLike.Range;
4544     }
4545     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4546       << NewTD << isa<TypeAliasDecl>(NewTD);
4547 
4548     if (ChangesLinkage)
4549       return;
4550   }
4551 
4552   // Otherwise, set this as the anon-decl typedef for the tag.
4553   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4554 }
4555 
4556 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4557   switch (T) {
4558   case DeclSpec::TST_class:
4559     return 0;
4560   case DeclSpec::TST_struct:
4561     return 1;
4562   case DeclSpec::TST_interface:
4563     return 2;
4564   case DeclSpec::TST_union:
4565     return 3;
4566   case DeclSpec::TST_enum:
4567     return 4;
4568   default:
4569     llvm_unreachable("unexpected type specifier");
4570   }
4571 }
4572 
4573 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4574 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4575 /// parameters to cope with template friend declarations.
4576 Decl *
4577 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4578                                  MultiTemplateParamsArg TemplateParams,
4579                                  bool IsExplicitInstantiation,
4580                                  RecordDecl *&AnonRecord) {
4581   Decl *TagD = nullptr;
4582   TagDecl *Tag = nullptr;
4583   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4584       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4585       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4586       DS.getTypeSpecType() == DeclSpec::TST_union ||
4587       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4588     TagD = DS.getRepAsDecl();
4589 
4590     if (!TagD) // We probably had an error
4591       return nullptr;
4592 
4593     // Note that the above type specs guarantee that the
4594     // type rep is a Decl, whereas in many of the others
4595     // it's a Type.
4596     if (isa<TagDecl>(TagD))
4597       Tag = cast<TagDecl>(TagD);
4598     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4599       Tag = CTD->getTemplatedDecl();
4600   }
4601 
4602   if (Tag) {
4603     handleTagNumbering(Tag, S);
4604     Tag->setFreeStanding();
4605     if (Tag->isInvalidDecl())
4606       return Tag;
4607   }
4608 
4609   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4610     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4611     // or incomplete types shall not be restrict-qualified."
4612     if (TypeQuals & DeclSpec::TQ_restrict)
4613       Diag(DS.getRestrictSpecLoc(),
4614            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4615            << DS.getSourceRange();
4616   }
4617 
4618   if (DS.isInlineSpecified())
4619     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4620         << getLangOpts().CPlusPlus17;
4621 
4622   if (DS.hasConstexprSpecifier()) {
4623     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4624     // and definitions of functions and variables.
4625     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4626     // the declaration of a function or function template
4627     if (Tag)
4628       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4629           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4630           << DS.getConstexprSpecifier();
4631     else
4632       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4633           << DS.getConstexprSpecifier();
4634     // Don't emit warnings after this error.
4635     return TagD;
4636   }
4637 
4638   DiagnoseFunctionSpecifiers(DS);
4639 
4640   if (DS.isFriendSpecified()) {
4641     // If we're dealing with a decl but not a TagDecl, assume that
4642     // whatever routines created it handled the friendship aspect.
4643     if (TagD && !Tag)
4644       return nullptr;
4645     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4646   }
4647 
4648   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4649   bool IsExplicitSpecialization =
4650     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4651   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4652       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4653       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4654     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4655     // nested-name-specifier unless it is an explicit instantiation
4656     // or an explicit specialization.
4657     //
4658     // FIXME: We allow class template partial specializations here too, per the
4659     // obvious intent of DR1819.
4660     //
4661     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4662     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4663         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4664     return nullptr;
4665   }
4666 
4667   // Track whether this decl-specifier declares anything.
4668   bool DeclaresAnything = true;
4669 
4670   // Handle anonymous struct definitions.
4671   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4672     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4673         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4674       if (getLangOpts().CPlusPlus ||
4675           Record->getDeclContext()->isRecord()) {
4676         // If CurContext is a DeclContext that can contain statements,
4677         // RecursiveASTVisitor won't visit the decls that
4678         // BuildAnonymousStructOrUnion() will put into CurContext.
4679         // Also store them here so that they can be part of the
4680         // DeclStmt that gets created in this case.
4681         // FIXME: Also return the IndirectFieldDecls created by
4682         // BuildAnonymousStructOr union, for the same reason?
4683         if (CurContext->isFunctionOrMethod())
4684           AnonRecord = Record;
4685         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4686                                            Context.getPrintingPolicy());
4687       }
4688 
4689       DeclaresAnything = false;
4690     }
4691   }
4692 
4693   // C11 6.7.2.1p2:
4694   //   A struct-declaration that does not declare an anonymous structure or
4695   //   anonymous union shall contain a struct-declarator-list.
4696   //
4697   // This rule also existed in C89 and C99; the grammar for struct-declaration
4698   // did not permit a struct-declaration without a struct-declarator-list.
4699   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4700       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4701     // Check for Microsoft C extension: anonymous struct/union member.
4702     // Handle 2 kinds of anonymous struct/union:
4703     //   struct STRUCT;
4704     //   union UNION;
4705     // and
4706     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4707     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4708     if ((Tag && Tag->getDeclName()) ||
4709         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4710       RecordDecl *Record = nullptr;
4711       if (Tag)
4712         Record = dyn_cast<RecordDecl>(Tag);
4713       else if (const RecordType *RT =
4714                    DS.getRepAsType().get()->getAsStructureType())
4715         Record = RT->getDecl();
4716       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4717         Record = UT->getDecl();
4718 
4719       if (Record && getLangOpts().MicrosoftExt) {
4720         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4721             << Record->isUnion() << DS.getSourceRange();
4722         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4723       }
4724 
4725       DeclaresAnything = false;
4726     }
4727   }
4728 
4729   // Skip all the checks below if we have a type error.
4730   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4731       (TagD && TagD->isInvalidDecl()))
4732     return TagD;
4733 
4734   if (getLangOpts().CPlusPlus &&
4735       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4736     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4737       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4738           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4739         DeclaresAnything = false;
4740 
4741   if (!DS.isMissingDeclaratorOk()) {
4742     // Customize diagnostic for a typedef missing a name.
4743     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4744       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4745           << DS.getSourceRange();
4746     else
4747       DeclaresAnything = false;
4748   }
4749 
4750   if (DS.isModulePrivateSpecified() &&
4751       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4752     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4753       << Tag->getTagKind()
4754       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4755 
4756   ActOnDocumentableDecl(TagD);
4757 
4758   // C 6.7/2:
4759   //   A declaration [...] shall declare at least a declarator [...], a tag,
4760   //   or the members of an enumeration.
4761   // C++ [dcl.dcl]p3:
4762   //   [If there are no declarators], and except for the declaration of an
4763   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4764   //   names into the program, or shall redeclare a name introduced by a
4765   //   previous declaration.
4766   if (!DeclaresAnything) {
4767     // In C, we allow this as a (popular) extension / bug. Don't bother
4768     // producing further diagnostics for redundant qualifiers after this.
4769     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4770                                ? diag::err_no_declarators
4771                                : diag::ext_no_declarators)
4772         << DS.getSourceRange();
4773     return TagD;
4774   }
4775 
4776   // C++ [dcl.stc]p1:
4777   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4778   //   init-declarator-list of the declaration shall not be empty.
4779   // C++ [dcl.fct.spec]p1:
4780   //   If a cv-qualifier appears in a decl-specifier-seq, the
4781   //   init-declarator-list of the declaration shall not be empty.
4782   //
4783   // Spurious qualifiers here appear to be valid in C.
4784   unsigned DiagID = diag::warn_standalone_specifier;
4785   if (getLangOpts().CPlusPlus)
4786     DiagID = diag::ext_standalone_specifier;
4787 
4788   // Note that a linkage-specification sets a storage class, but
4789   // 'extern "C" struct foo;' is actually valid and not theoretically
4790   // useless.
4791   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4792     if (SCS == DeclSpec::SCS_mutable)
4793       // Since mutable is not a viable storage class specifier in C, there is
4794       // no reason to treat it as an extension. Instead, diagnose as an error.
4795       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4796     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4797       Diag(DS.getStorageClassSpecLoc(), DiagID)
4798         << DeclSpec::getSpecifierName(SCS);
4799   }
4800 
4801   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4802     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4803       << DeclSpec::getSpecifierName(TSCS);
4804   if (DS.getTypeQualifiers()) {
4805     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4806       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4807     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4808       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4809     // Restrict is covered above.
4810     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4811       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4812     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4813       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4814   }
4815 
4816   // Warn about ignored type attributes, for example:
4817   // __attribute__((aligned)) struct A;
4818   // Attributes should be placed after tag to apply to type declaration.
4819   if (!DS.getAttributes().empty()) {
4820     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4821     if (TypeSpecType == DeclSpec::TST_class ||
4822         TypeSpecType == DeclSpec::TST_struct ||
4823         TypeSpecType == DeclSpec::TST_interface ||
4824         TypeSpecType == DeclSpec::TST_union ||
4825         TypeSpecType == DeclSpec::TST_enum) {
4826       for (const ParsedAttr &AL : DS.getAttributes())
4827         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4828             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4829     }
4830   }
4831 
4832   return TagD;
4833 }
4834 
4835 /// We are trying to inject an anonymous member into the given scope;
4836 /// check if there's an existing declaration that can't be overloaded.
4837 ///
4838 /// \return true if this is a forbidden redeclaration
4839 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4840                                          Scope *S,
4841                                          DeclContext *Owner,
4842                                          DeclarationName Name,
4843                                          SourceLocation NameLoc,
4844                                          bool IsUnion) {
4845   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4846                  Sema::ForVisibleRedeclaration);
4847   if (!SemaRef.LookupName(R, S)) return false;
4848 
4849   // Pick a representative declaration.
4850   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4851   assert(PrevDecl && "Expected a non-null Decl");
4852 
4853   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4854     return false;
4855 
4856   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4857     << IsUnion << Name;
4858   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4859 
4860   return true;
4861 }
4862 
4863 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4864 /// anonymous struct or union AnonRecord into the owning context Owner
4865 /// and scope S. This routine will be invoked just after we realize
4866 /// that an unnamed union or struct is actually an anonymous union or
4867 /// struct, e.g.,
4868 ///
4869 /// @code
4870 /// union {
4871 ///   int i;
4872 ///   float f;
4873 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4874 ///    // f into the surrounding scope.x
4875 /// @endcode
4876 ///
4877 /// This routine is recursive, injecting the names of nested anonymous
4878 /// structs/unions into the owning context and scope as well.
4879 static bool
4880 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4881                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4882                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4883   bool Invalid = false;
4884 
4885   // Look every FieldDecl and IndirectFieldDecl with a name.
4886   for (auto *D : AnonRecord->decls()) {
4887     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4888         cast<NamedDecl>(D)->getDeclName()) {
4889       ValueDecl *VD = cast<ValueDecl>(D);
4890       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4891                                        VD->getLocation(),
4892                                        AnonRecord->isUnion())) {
4893         // C++ [class.union]p2:
4894         //   The names of the members of an anonymous union shall be
4895         //   distinct from the names of any other entity in the
4896         //   scope in which the anonymous union is declared.
4897         Invalid = true;
4898       } else {
4899         // C++ [class.union]p2:
4900         //   For the purpose of name lookup, after the anonymous union
4901         //   definition, the members of the anonymous union are
4902         //   considered to have been defined in the scope in which the
4903         //   anonymous union is declared.
4904         unsigned OldChainingSize = Chaining.size();
4905         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4906           Chaining.append(IF->chain_begin(), IF->chain_end());
4907         else
4908           Chaining.push_back(VD);
4909 
4910         assert(Chaining.size() >= 2);
4911         NamedDecl **NamedChain =
4912           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4913         for (unsigned i = 0; i < Chaining.size(); i++)
4914           NamedChain[i] = Chaining[i];
4915 
4916         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4917             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4918             VD->getType(), {NamedChain, Chaining.size()});
4919 
4920         for (const auto *Attr : VD->attrs())
4921           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4922 
4923         IndirectField->setAccess(AS);
4924         IndirectField->setImplicit();
4925         SemaRef.PushOnScopeChains(IndirectField, S);
4926 
4927         // That includes picking up the appropriate access specifier.
4928         if (AS != AS_none) IndirectField->setAccess(AS);
4929 
4930         Chaining.resize(OldChainingSize);
4931       }
4932     }
4933   }
4934 
4935   return Invalid;
4936 }
4937 
4938 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4939 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4940 /// illegal input values are mapped to SC_None.
4941 static StorageClass
4942 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4943   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4944   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4945          "Parser allowed 'typedef' as storage class VarDecl.");
4946   switch (StorageClassSpec) {
4947   case DeclSpec::SCS_unspecified:    return SC_None;
4948   case DeclSpec::SCS_extern:
4949     if (DS.isExternInLinkageSpec())
4950       return SC_None;
4951     return SC_Extern;
4952   case DeclSpec::SCS_static:         return SC_Static;
4953   case DeclSpec::SCS_auto:           return SC_Auto;
4954   case DeclSpec::SCS_register:       return SC_Register;
4955   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4956     // Illegal SCSs map to None: error reporting is up to the caller.
4957   case DeclSpec::SCS_mutable:        // Fall through.
4958   case DeclSpec::SCS_typedef:        return SC_None;
4959   }
4960   llvm_unreachable("unknown storage class specifier");
4961 }
4962 
4963 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4964   assert(Record->hasInClassInitializer());
4965 
4966   for (const auto *I : Record->decls()) {
4967     const auto *FD = dyn_cast<FieldDecl>(I);
4968     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4969       FD = IFD->getAnonField();
4970     if (FD && FD->hasInClassInitializer())
4971       return FD->getLocation();
4972   }
4973 
4974   llvm_unreachable("couldn't find in-class initializer");
4975 }
4976 
4977 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4978                                       SourceLocation DefaultInitLoc) {
4979   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4980     return;
4981 
4982   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4983   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4984 }
4985 
4986 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4987                                       CXXRecordDecl *AnonUnion) {
4988   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4989     return;
4990 
4991   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4992 }
4993 
4994 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4995 /// anonymous structure or union. Anonymous unions are a C++ feature
4996 /// (C++ [class.union]) and a C11 feature; anonymous structures
4997 /// are a C11 feature and GNU C++ extension.
4998 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4999                                         AccessSpecifier AS,
5000                                         RecordDecl *Record,
5001                                         const PrintingPolicy &Policy) {
5002   DeclContext *Owner = Record->getDeclContext();
5003 
5004   // Diagnose whether this anonymous struct/union is an extension.
5005   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5006     Diag(Record->getLocation(), diag::ext_anonymous_union);
5007   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5008     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5009   else if (!Record->isUnion() && !getLangOpts().C11)
5010     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5011 
5012   // C and C++ require different kinds of checks for anonymous
5013   // structs/unions.
5014   bool Invalid = false;
5015   if (getLangOpts().CPlusPlus) {
5016     const char *PrevSpec = nullptr;
5017     if (Record->isUnion()) {
5018       // C++ [class.union]p6:
5019       // C++17 [class.union.anon]p2:
5020       //   Anonymous unions declared in a named namespace or in the
5021       //   global namespace shall be declared static.
5022       unsigned DiagID;
5023       DeclContext *OwnerScope = Owner->getRedeclContext();
5024       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5025           (OwnerScope->isTranslationUnit() ||
5026            (OwnerScope->isNamespace() &&
5027             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5028         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5029           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5030 
5031         // Recover by adding 'static'.
5032         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5033                                PrevSpec, DiagID, Policy);
5034       }
5035       // C++ [class.union]p6:
5036       //   A storage class is not allowed in a declaration of an
5037       //   anonymous union in a class scope.
5038       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5039                isa<RecordDecl>(Owner)) {
5040         Diag(DS.getStorageClassSpecLoc(),
5041              diag::err_anonymous_union_with_storage_spec)
5042           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5043 
5044         // Recover by removing the storage specifier.
5045         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5046                                SourceLocation(),
5047                                PrevSpec, DiagID, Context.getPrintingPolicy());
5048       }
5049     }
5050 
5051     // Ignore const/volatile/restrict qualifiers.
5052     if (DS.getTypeQualifiers()) {
5053       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5054         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5055           << Record->isUnion() << "const"
5056           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5057       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5058         Diag(DS.getVolatileSpecLoc(),
5059              diag::ext_anonymous_struct_union_qualified)
5060           << Record->isUnion() << "volatile"
5061           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5062       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5063         Diag(DS.getRestrictSpecLoc(),
5064              diag::ext_anonymous_struct_union_qualified)
5065           << Record->isUnion() << "restrict"
5066           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5067       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5068         Diag(DS.getAtomicSpecLoc(),
5069              diag::ext_anonymous_struct_union_qualified)
5070           << Record->isUnion() << "_Atomic"
5071           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5072       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5073         Diag(DS.getUnalignedSpecLoc(),
5074              diag::ext_anonymous_struct_union_qualified)
5075           << Record->isUnion() << "__unaligned"
5076           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5077 
5078       DS.ClearTypeQualifiers();
5079     }
5080 
5081     // C++ [class.union]p2:
5082     //   The member-specification of an anonymous union shall only
5083     //   define non-static data members. [Note: nested types and
5084     //   functions cannot be declared within an anonymous union. ]
5085     for (auto *Mem : Record->decls()) {
5086       // Ignore invalid declarations; we already diagnosed them.
5087       if (Mem->isInvalidDecl())
5088         continue;
5089 
5090       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5091         // C++ [class.union]p3:
5092         //   An anonymous union shall not have private or protected
5093         //   members (clause 11).
5094         assert(FD->getAccess() != AS_none);
5095         if (FD->getAccess() != AS_public) {
5096           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5097             << Record->isUnion() << (FD->getAccess() == AS_protected);
5098           Invalid = true;
5099         }
5100 
5101         // C++ [class.union]p1
5102         //   An object of a class with a non-trivial constructor, a non-trivial
5103         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5104         //   assignment operator cannot be a member of a union, nor can an
5105         //   array of such objects.
5106         if (CheckNontrivialField(FD))
5107           Invalid = true;
5108       } else if (Mem->isImplicit()) {
5109         // Any implicit members are fine.
5110       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5111         // This is a type that showed up in an
5112         // elaborated-type-specifier inside the anonymous struct or
5113         // union, but which actually declares a type outside of the
5114         // anonymous struct or union. It's okay.
5115       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5116         if (!MemRecord->isAnonymousStructOrUnion() &&
5117             MemRecord->getDeclName()) {
5118           // Visual C++ allows type definition in anonymous struct or union.
5119           if (getLangOpts().MicrosoftExt)
5120             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5121               << Record->isUnion();
5122           else {
5123             // This is a nested type declaration.
5124             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5125               << Record->isUnion();
5126             Invalid = true;
5127           }
5128         } else {
5129           // This is an anonymous type definition within another anonymous type.
5130           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5131           // not part of standard C++.
5132           Diag(MemRecord->getLocation(),
5133                diag::ext_anonymous_record_with_anonymous_type)
5134             << Record->isUnion();
5135         }
5136       } else if (isa<AccessSpecDecl>(Mem)) {
5137         // Any access specifier is fine.
5138       } else if (isa<StaticAssertDecl>(Mem)) {
5139         // In C++1z, static_assert declarations are also fine.
5140       } else {
5141         // We have something that isn't a non-static data
5142         // member. Complain about it.
5143         unsigned DK = diag::err_anonymous_record_bad_member;
5144         if (isa<TypeDecl>(Mem))
5145           DK = diag::err_anonymous_record_with_type;
5146         else if (isa<FunctionDecl>(Mem))
5147           DK = diag::err_anonymous_record_with_function;
5148         else if (isa<VarDecl>(Mem))
5149           DK = diag::err_anonymous_record_with_static;
5150 
5151         // Visual C++ allows type definition in anonymous struct or union.
5152         if (getLangOpts().MicrosoftExt &&
5153             DK == diag::err_anonymous_record_with_type)
5154           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5155             << Record->isUnion();
5156         else {
5157           Diag(Mem->getLocation(), DK) << Record->isUnion();
5158           Invalid = true;
5159         }
5160       }
5161     }
5162 
5163     // C++11 [class.union]p8 (DR1460):
5164     //   At most one variant member of a union may have a
5165     //   brace-or-equal-initializer.
5166     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5167         Owner->isRecord())
5168       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5169                                 cast<CXXRecordDecl>(Record));
5170   }
5171 
5172   if (!Record->isUnion() && !Owner->isRecord()) {
5173     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5174       << getLangOpts().CPlusPlus;
5175     Invalid = true;
5176   }
5177 
5178   // C++ [dcl.dcl]p3:
5179   //   [If there are no declarators], and except for the declaration of an
5180   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5181   //   names into the program
5182   // C++ [class.mem]p2:
5183   //   each such member-declaration shall either declare at least one member
5184   //   name of the class or declare at least one unnamed bit-field
5185   //
5186   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5187   if (getLangOpts().CPlusPlus && Record->field_empty())
5188     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5189 
5190   // Mock up a declarator.
5191   Declarator Dc(DS, DeclaratorContext::MemberContext);
5192   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5193   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5194 
5195   // Create a declaration for this anonymous struct/union.
5196   NamedDecl *Anon = nullptr;
5197   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5198     Anon = FieldDecl::Create(
5199         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5200         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5201         /*BitWidth=*/nullptr, /*Mutable=*/false,
5202         /*InitStyle=*/ICIS_NoInit);
5203     Anon->setAccess(AS);
5204     ProcessDeclAttributes(S, Anon, Dc);
5205 
5206     if (getLangOpts().CPlusPlus)
5207       FieldCollector->Add(cast<FieldDecl>(Anon));
5208   } else {
5209     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5210     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5211     if (SCSpec == DeclSpec::SCS_mutable) {
5212       // mutable can only appear on non-static class members, so it's always
5213       // an error here
5214       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5215       Invalid = true;
5216       SC = SC_None;
5217     }
5218 
5219     assert(DS.getAttributes().empty() && "No attribute expected");
5220     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5221                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5222                            Context.getTypeDeclType(Record), TInfo, SC);
5223 
5224     // Default-initialize the implicit variable. This initialization will be
5225     // trivial in almost all cases, except if a union member has an in-class
5226     // initializer:
5227     //   union { int n = 0; };
5228     ActOnUninitializedDecl(Anon);
5229   }
5230   Anon->setImplicit();
5231 
5232   // Mark this as an anonymous struct/union type.
5233   Record->setAnonymousStructOrUnion(true);
5234 
5235   // Add the anonymous struct/union object to the current
5236   // context. We'll be referencing this object when we refer to one of
5237   // its members.
5238   Owner->addDecl(Anon);
5239 
5240   // Inject the members of the anonymous struct/union into the owning
5241   // context and into the identifier resolver chain for name lookup
5242   // purposes.
5243   SmallVector<NamedDecl*, 2> Chain;
5244   Chain.push_back(Anon);
5245 
5246   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5247     Invalid = true;
5248 
5249   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5250     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5251       MangleNumberingContext *MCtx;
5252       Decl *ManglingContextDecl;
5253       std::tie(MCtx, ManglingContextDecl) =
5254           getCurrentMangleNumberContext(NewVD->getDeclContext());
5255       if (MCtx) {
5256         Context.setManglingNumber(
5257             NewVD, MCtx->getManglingNumber(
5258                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5259         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5260       }
5261     }
5262   }
5263 
5264   if (Invalid)
5265     Anon->setInvalidDecl();
5266 
5267   return Anon;
5268 }
5269 
5270 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5271 /// Microsoft C anonymous structure.
5272 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5273 /// Example:
5274 ///
5275 /// struct A { int a; };
5276 /// struct B { struct A; int b; };
5277 ///
5278 /// void foo() {
5279 ///   B var;
5280 ///   var.a = 3;
5281 /// }
5282 ///
5283 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5284                                            RecordDecl *Record) {
5285   assert(Record && "expected a record!");
5286 
5287   // Mock up a declarator.
5288   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5289   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5290   assert(TInfo && "couldn't build declarator info for anonymous struct");
5291 
5292   auto *ParentDecl = cast<RecordDecl>(CurContext);
5293   QualType RecTy = Context.getTypeDeclType(Record);
5294 
5295   // Create a declaration for this anonymous struct.
5296   NamedDecl *Anon =
5297       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5298                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5299                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5300                         /*InitStyle=*/ICIS_NoInit);
5301   Anon->setImplicit();
5302 
5303   // Add the anonymous struct object to the current context.
5304   CurContext->addDecl(Anon);
5305 
5306   // Inject the members of the anonymous struct into the current
5307   // context and into the identifier resolver chain for name lookup
5308   // purposes.
5309   SmallVector<NamedDecl*, 2> Chain;
5310   Chain.push_back(Anon);
5311 
5312   RecordDecl *RecordDef = Record->getDefinition();
5313   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5314                                diag::err_field_incomplete_or_sizeless) ||
5315       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5316                                           AS_none, Chain)) {
5317     Anon->setInvalidDecl();
5318     ParentDecl->setInvalidDecl();
5319   }
5320 
5321   return Anon;
5322 }
5323 
5324 /// GetNameForDeclarator - Determine the full declaration name for the
5325 /// given Declarator.
5326 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5327   return GetNameFromUnqualifiedId(D.getName());
5328 }
5329 
5330 /// Retrieves the declaration name from a parsed unqualified-id.
5331 DeclarationNameInfo
5332 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5333   DeclarationNameInfo NameInfo;
5334   NameInfo.setLoc(Name.StartLocation);
5335 
5336   switch (Name.getKind()) {
5337 
5338   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5339   case UnqualifiedIdKind::IK_Identifier:
5340     NameInfo.setName(Name.Identifier);
5341     return NameInfo;
5342 
5343   case UnqualifiedIdKind::IK_DeductionGuideName: {
5344     // C++ [temp.deduct.guide]p3:
5345     //   The simple-template-id shall name a class template specialization.
5346     //   The template-name shall be the same identifier as the template-name
5347     //   of the simple-template-id.
5348     // These together intend to imply that the template-name shall name a
5349     // class template.
5350     // FIXME: template<typename T> struct X {};
5351     //        template<typename T> using Y = X<T>;
5352     //        Y(int) -> Y<int>;
5353     //   satisfies these rules but does not name a class template.
5354     TemplateName TN = Name.TemplateName.get().get();
5355     auto *Template = TN.getAsTemplateDecl();
5356     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5357       Diag(Name.StartLocation,
5358            diag::err_deduction_guide_name_not_class_template)
5359         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5360       if (Template)
5361         Diag(Template->getLocation(), diag::note_template_decl_here);
5362       return DeclarationNameInfo();
5363     }
5364 
5365     NameInfo.setName(
5366         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5367     return NameInfo;
5368   }
5369 
5370   case UnqualifiedIdKind::IK_OperatorFunctionId:
5371     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5372                                            Name.OperatorFunctionId.Operator));
5373     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5374       = Name.OperatorFunctionId.SymbolLocations[0];
5375     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5376       = Name.EndLocation.getRawEncoding();
5377     return NameInfo;
5378 
5379   case UnqualifiedIdKind::IK_LiteralOperatorId:
5380     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5381                                                            Name.Identifier));
5382     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5383     return NameInfo;
5384 
5385   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5386     TypeSourceInfo *TInfo;
5387     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5388     if (Ty.isNull())
5389       return DeclarationNameInfo();
5390     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5391                                                Context.getCanonicalType(Ty)));
5392     NameInfo.setNamedTypeInfo(TInfo);
5393     return NameInfo;
5394   }
5395 
5396   case UnqualifiedIdKind::IK_ConstructorName: {
5397     TypeSourceInfo *TInfo;
5398     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5399     if (Ty.isNull())
5400       return DeclarationNameInfo();
5401     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5402                                               Context.getCanonicalType(Ty)));
5403     NameInfo.setNamedTypeInfo(TInfo);
5404     return NameInfo;
5405   }
5406 
5407   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5408     // In well-formed code, we can only have a constructor
5409     // template-id that refers to the current context, so go there
5410     // to find the actual type being constructed.
5411     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5412     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5413       return DeclarationNameInfo();
5414 
5415     // Determine the type of the class being constructed.
5416     QualType CurClassType = Context.getTypeDeclType(CurClass);
5417 
5418     // FIXME: Check two things: that the template-id names the same type as
5419     // CurClassType, and that the template-id does not occur when the name
5420     // was qualified.
5421 
5422     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5423                                     Context.getCanonicalType(CurClassType)));
5424     // FIXME: should we retrieve TypeSourceInfo?
5425     NameInfo.setNamedTypeInfo(nullptr);
5426     return NameInfo;
5427   }
5428 
5429   case UnqualifiedIdKind::IK_DestructorName: {
5430     TypeSourceInfo *TInfo;
5431     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5432     if (Ty.isNull())
5433       return DeclarationNameInfo();
5434     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5435                                               Context.getCanonicalType(Ty)));
5436     NameInfo.setNamedTypeInfo(TInfo);
5437     return NameInfo;
5438   }
5439 
5440   case UnqualifiedIdKind::IK_TemplateId: {
5441     TemplateName TName = Name.TemplateId->Template.get();
5442     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5443     return Context.getNameForTemplate(TName, TNameLoc);
5444   }
5445 
5446   } // switch (Name.getKind())
5447 
5448   llvm_unreachable("Unknown name kind");
5449 }
5450 
5451 static QualType getCoreType(QualType Ty) {
5452   do {
5453     if (Ty->isPointerType() || Ty->isReferenceType())
5454       Ty = Ty->getPointeeType();
5455     else if (Ty->isArrayType())
5456       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5457     else
5458       return Ty.withoutLocalFastQualifiers();
5459   } while (true);
5460 }
5461 
5462 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5463 /// and Definition have "nearly" matching parameters. This heuristic is
5464 /// used to improve diagnostics in the case where an out-of-line function
5465 /// definition doesn't match any declaration within the class or namespace.
5466 /// Also sets Params to the list of indices to the parameters that differ
5467 /// between the declaration and the definition. If hasSimilarParameters
5468 /// returns true and Params is empty, then all of the parameters match.
5469 static bool hasSimilarParameters(ASTContext &Context,
5470                                      FunctionDecl *Declaration,
5471                                      FunctionDecl *Definition,
5472                                      SmallVectorImpl<unsigned> &Params) {
5473   Params.clear();
5474   if (Declaration->param_size() != Definition->param_size())
5475     return false;
5476   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5477     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5478     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5479 
5480     // The parameter types are identical
5481     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5482       continue;
5483 
5484     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5485     QualType DefParamBaseTy = getCoreType(DefParamTy);
5486     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5487     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5488 
5489     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5490         (DeclTyName && DeclTyName == DefTyName))
5491       Params.push_back(Idx);
5492     else  // The two parameters aren't even close
5493       return false;
5494   }
5495 
5496   return true;
5497 }
5498 
5499 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5500 /// declarator needs to be rebuilt in the current instantiation.
5501 /// Any bits of declarator which appear before the name are valid for
5502 /// consideration here.  That's specifically the type in the decl spec
5503 /// and the base type in any member-pointer chunks.
5504 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5505                                                     DeclarationName Name) {
5506   // The types we specifically need to rebuild are:
5507   //   - typenames, typeofs, and decltypes
5508   //   - types which will become injected class names
5509   // Of course, we also need to rebuild any type referencing such a
5510   // type.  It's safest to just say "dependent", but we call out a
5511   // few cases here.
5512 
5513   DeclSpec &DS = D.getMutableDeclSpec();
5514   switch (DS.getTypeSpecType()) {
5515   case DeclSpec::TST_typename:
5516   case DeclSpec::TST_typeofType:
5517   case DeclSpec::TST_underlyingType:
5518   case DeclSpec::TST_atomic: {
5519     // Grab the type from the parser.
5520     TypeSourceInfo *TSI = nullptr;
5521     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5522     if (T.isNull() || !T->isDependentType()) break;
5523 
5524     // Make sure there's a type source info.  This isn't really much
5525     // of a waste; most dependent types should have type source info
5526     // attached already.
5527     if (!TSI)
5528       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5529 
5530     // Rebuild the type in the current instantiation.
5531     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5532     if (!TSI) return true;
5533 
5534     // Store the new type back in the decl spec.
5535     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5536     DS.UpdateTypeRep(LocType);
5537     break;
5538   }
5539 
5540   case DeclSpec::TST_decltype:
5541   case DeclSpec::TST_typeofExpr: {
5542     Expr *E = DS.getRepAsExpr();
5543     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5544     if (Result.isInvalid()) return true;
5545     DS.UpdateExprRep(Result.get());
5546     break;
5547   }
5548 
5549   default:
5550     // Nothing to do for these decl specs.
5551     break;
5552   }
5553 
5554   // It doesn't matter what order we do this in.
5555   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5556     DeclaratorChunk &Chunk = D.getTypeObject(I);
5557 
5558     // The only type information in the declarator which can come
5559     // before the declaration name is the base type of a member
5560     // pointer.
5561     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5562       continue;
5563 
5564     // Rebuild the scope specifier in-place.
5565     CXXScopeSpec &SS = Chunk.Mem.Scope();
5566     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5567       return true;
5568   }
5569 
5570   return false;
5571 }
5572 
5573 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5574   D.setFunctionDefinitionKind(FDK_Declaration);
5575   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5576 
5577   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5578       Dcl && Dcl->getDeclContext()->isFileContext())
5579     Dcl->setTopLevelDeclInObjCContainer();
5580 
5581   if (getLangOpts().OpenCL)
5582     setCurrentOpenCLExtensionForDecl(Dcl);
5583 
5584   return Dcl;
5585 }
5586 
5587 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5588 ///   If T is the name of a class, then each of the following shall have a
5589 ///   name different from T:
5590 ///     - every static data member of class T;
5591 ///     - every member function of class T
5592 ///     - every member of class T that is itself a type;
5593 /// \returns true if the declaration name violates these rules.
5594 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5595                                    DeclarationNameInfo NameInfo) {
5596   DeclarationName Name = NameInfo.getName();
5597 
5598   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5599   while (Record && Record->isAnonymousStructOrUnion())
5600     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5601   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5602     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5603     return true;
5604   }
5605 
5606   return false;
5607 }
5608 
5609 /// Diagnose a declaration whose declarator-id has the given
5610 /// nested-name-specifier.
5611 ///
5612 /// \param SS The nested-name-specifier of the declarator-id.
5613 ///
5614 /// \param DC The declaration context to which the nested-name-specifier
5615 /// resolves.
5616 ///
5617 /// \param Name The name of the entity being declared.
5618 ///
5619 /// \param Loc The location of the name of the entity being declared.
5620 ///
5621 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5622 /// we're declaring an explicit / partial specialization / instantiation.
5623 ///
5624 /// \returns true if we cannot safely recover from this error, false otherwise.
5625 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5626                                         DeclarationName Name,
5627                                         SourceLocation Loc, bool IsTemplateId) {
5628   DeclContext *Cur = CurContext;
5629   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5630     Cur = Cur->getParent();
5631 
5632   // If the user provided a superfluous scope specifier that refers back to the
5633   // class in which the entity is already declared, diagnose and ignore it.
5634   //
5635   // class X {
5636   //   void X::f();
5637   // };
5638   //
5639   // Note, it was once ill-formed to give redundant qualification in all
5640   // contexts, but that rule was removed by DR482.
5641   if (Cur->Equals(DC)) {
5642     if (Cur->isRecord()) {
5643       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5644                                       : diag::err_member_extra_qualification)
5645         << Name << FixItHint::CreateRemoval(SS.getRange());
5646       SS.clear();
5647     } else {
5648       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5649     }
5650     return false;
5651   }
5652 
5653   // Check whether the qualifying scope encloses the scope of the original
5654   // declaration. For a template-id, we perform the checks in
5655   // CheckTemplateSpecializationScope.
5656   if (!Cur->Encloses(DC) && !IsTemplateId) {
5657     if (Cur->isRecord())
5658       Diag(Loc, diag::err_member_qualification)
5659         << Name << SS.getRange();
5660     else if (isa<TranslationUnitDecl>(DC))
5661       Diag(Loc, diag::err_invalid_declarator_global_scope)
5662         << Name << SS.getRange();
5663     else if (isa<FunctionDecl>(Cur))
5664       Diag(Loc, diag::err_invalid_declarator_in_function)
5665         << Name << SS.getRange();
5666     else if (isa<BlockDecl>(Cur))
5667       Diag(Loc, diag::err_invalid_declarator_in_block)
5668         << Name << SS.getRange();
5669     else
5670       Diag(Loc, diag::err_invalid_declarator_scope)
5671       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5672 
5673     return true;
5674   }
5675 
5676   if (Cur->isRecord()) {
5677     // Cannot qualify members within a class.
5678     Diag(Loc, diag::err_member_qualification)
5679       << Name << SS.getRange();
5680     SS.clear();
5681 
5682     // C++ constructors and destructors with incorrect scopes can break
5683     // our AST invariants by having the wrong underlying types. If
5684     // that's the case, then drop this declaration entirely.
5685     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5686          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5687         !Context.hasSameType(Name.getCXXNameType(),
5688                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5689       return true;
5690 
5691     return false;
5692   }
5693 
5694   // C++11 [dcl.meaning]p1:
5695   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5696   //   not begin with a decltype-specifer"
5697   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5698   while (SpecLoc.getPrefix())
5699     SpecLoc = SpecLoc.getPrefix();
5700   if (dyn_cast_or_null<DecltypeType>(
5701         SpecLoc.getNestedNameSpecifier()->getAsType()))
5702     Diag(Loc, diag::err_decltype_in_declarator)
5703       << SpecLoc.getTypeLoc().getSourceRange();
5704 
5705   return false;
5706 }
5707 
5708 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5709                                   MultiTemplateParamsArg TemplateParamLists) {
5710   // TODO: consider using NameInfo for diagnostic.
5711   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5712   DeclarationName Name = NameInfo.getName();
5713 
5714   // All of these full declarators require an identifier.  If it doesn't have
5715   // one, the ParsedFreeStandingDeclSpec action should be used.
5716   if (D.isDecompositionDeclarator()) {
5717     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5718   } else if (!Name) {
5719     if (!D.isInvalidType())  // Reject this if we think it is valid.
5720       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5721           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5722     return nullptr;
5723   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5724     return nullptr;
5725 
5726   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5727   // we find one that is.
5728   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5729          (S->getFlags() & Scope::TemplateParamScope) != 0)
5730     S = S->getParent();
5731 
5732   DeclContext *DC = CurContext;
5733   if (D.getCXXScopeSpec().isInvalid())
5734     D.setInvalidType();
5735   else if (D.getCXXScopeSpec().isSet()) {
5736     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5737                                         UPPC_DeclarationQualifier))
5738       return nullptr;
5739 
5740     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5741     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5742     if (!DC || isa<EnumDecl>(DC)) {
5743       // If we could not compute the declaration context, it's because the
5744       // declaration context is dependent but does not refer to a class,
5745       // class template, or class template partial specialization. Complain
5746       // and return early, to avoid the coming semantic disaster.
5747       Diag(D.getIdentifierLoc(),
5748            diag::err_template_qualified_declarator_no_match)
5749         << D.getCXXScopeSpec().getScopeRep()
5750         << D.getCXXScopeSpec().getRange();
5751       return nullptr;
5752     }
5753     bool IsDependentContext = DC->isDependentContext();
5754 
5755     if (!IsDependentContext &&
5756         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5757       return nullptr;
5758 
5759     // If a class is incomplete, do not parse entities inside it.
5760     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5761       Diag(D.getIdentifierLoc(),
5762            diag::err_member_def_undefined_record)
5763         << Name << DC << D.getCXXScopeSpec().getRange();
5764       return nullptr;
5765     }
5766     if (!D.getDeclSpec().isFriendSpecified()) {
5767       if (diagnoseQualifiedDeclaration(
5768               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5769               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5770         if (DC->isRecord())
5771           return nullptr;
5772 
5773         D.setInvalidType();
5774       }
5775     }
5776 
5777     // Check whether we need to rebuild the type of the given
5778     // declaration in the current instantiation.
5779     if (EnteringContext && IsDependentContext &&
5780         TemplateParamLists.size() != 0) {
5781       ContextRAII SavedContext(*this, DC);
5782       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5783         D.setInvalidType();
5784     }
5785   }
5786 
5787   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5788   QualType R = TInfo->getType();
5789 
5790   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5791                                       UPPC_DeclarationType))
5792     D.setInvalidType();
5793 
5794   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5795                         forRedeclarationInCurContext());
5796 
5797   // See if this is a redefinition of a variable in the same scope.
5798   if (!D.getCXXScopeSpec().isSet()) {
5799     bool IsLinkageLookup = false;
5800     bool CreateBuiltins = false;
5801 
5802     // If the declaration we're planning to build will be a function
5803     // or object with linkage, then look for another declaration with
5804     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5805     //
5806     // If the declaration we're planning to build will be declared with
5807     // external linkage in the translation unit, create any builtin with
5808     // the same name.
5809     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5810       /* Do nothing*/;
5811     else if (CurContext->isFunctionOrMethod() &&
5812              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5813               R->isFunctionType())) {
5814       IsLinkageLookup = true;
5815       CreateBuiltins =
5816           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5817     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5818                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5819       CreateBuiltins = true;
5820 
5821     if (IsLinkageLookup) {
5822       Previous.clear(LookupRedeclarationWithLinkage);
5823       Previous.setRedeclarationKind(ForExternalRedeclaration);
5824     }
5825 
5826     LookupName(Previous, S, CreateBuiltins);
5827   } else { // Something like "int foo::x;"
5828     LookupQualifiedName(Previous, DC);
5829 
5830     // C++ [dcl.meaning]p1:
5831     //   When the declarator-id is qualified, the declaration shall refer to a
5832     //  previously declared member of the class or namespace to which the
5833     //  qualifier refers (or, in the case of a namespace, of an element of the
5834     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5835     //  thereof; [...]
5836     //
5837     // Note that we already checked the context above, and that we do not have
5838     // enough information to make sure that Previous contains the declaration
5839     // we want to match. For example, given:
5840     //
5841     //   class X {
5842     //     void f();
5843     //     void f(float);
5844     //   };
5845     //
5846     //   void X::f(int) { } // ill-formed
5847     //
5848     // In this case, Previous will point to the overload set
5849     // containing the two f's declared in X, but neither of them
5850     // matches.
5851 
5852     // C++ [dcl.meaning]p1:
5853     //   [...] the member shall not merely have been introduced by a
5854     //   using-declaration in the scope of the class or namespace nominated by
5855     //   the nested-name-specifier of the declarator-id.
5856     RemoveUsingDecls(Previous);
5857   }
5858 
5859   if (Previous.isSingleResult() &&
5860       Previous.getFoundDecl()->isTemplateParameter()) {
5861     // Maybe we will complain about the shadowed template parameter.
5862     if (!D.isInvalidType())
5863       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5864                                       Previous.getFoundDecl());
5865 
5866     // Just pretend that we didn't see the previous declaration.
5867     Previous.clear();
5868   }
5869 
5870   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5871     // Forget that the previous declaration is the injected-class-name.
5872     Previous.clear();
5873 
5874   // In C++, the previous declaration we find might be a tag type
5875   // (class or enum). In this case, the new declaration will hide the
5876   // tag type. Note that this applies to functions, function templates, and
5877   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5878   if (Previous.isSingleTagDecl() &&
5879       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5880       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5881     Previous.clear();
5882 
5883   // Check that there are no default arguments other than in the parameters
5884   // of a function declaration (C++ only).
5885   if (getLangOpts().CPlusPlus)
5886     CheckExtraCXXDefaultArguments(D);
5887 
5888   NamedDecl *New;
5889 
5890   bool AddToScope = true;
5891   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5892     if (TemplateParamLists.size()) {
5893       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5894       return nullptr;
5895     }
5896 
5897     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5898   } else if (R->isFunctionType()) {
5899     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5900                                   TemplateParamLists,
5901                                   AddToScope);
5902   } else {
5903     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5904                                   AddToScope);
5905   }
5906 
5907   if (!New)
5908     return nullptr;
5909 
5910   // If this has an identifier and is not a function template specialization,
5911   // add it to the scope stack.
5912   if (New->getDeclName() && AddToScope)
5913     PushOnScopeChains(New, S);
5914 
5915   if (isInOpenMPDeclareTargetContext())
5916     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5917 
5918   return New;
5919 }
5920 
5921 /// Helper method to turn variable array types into constant array
5922 /// types in certain situations which would otherwise be errors (for
5923 /// GCC compatibility).
5924 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5925                                                     ASTContext &Context,
5926                                                     bool &SizeIsNegative,
5927                                                     llvm::APSInt &Oversized) {
5928   // This method tries to turn a variable array into a constant
5929   // array even when the size isn't an ICE.  This is necessary
5930   // for compatibility with code that depends on gcc's buggy
5931   // constant expression folding, like struct {char x[(int)(char*)2];}
5932   SizeIsNegative = false;
5933   Oversized = 0;
5934 
5935   if (T->isDependentType())
5936     return QualType();
5937 
5938   QualifierCollector Qs;
5939   const Type *Ty = Qs.strip(T);
5940 
5941   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5942     QualType Pointee = PTy->getPointeeType();
5943     QualType FixedType =
5944         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5945                                             Oversized);
5946     if (FixedType.isNull()) return FixedType;
5947     FixedType = Context.getPointerType(FixedType);
5948     return Qs.apply(Context, FixedType);
5949   }
5950   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5951     QualType Inner = PTy->getInnerType();
5952     QualType FixedType =
5953         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5954                                             Oversized);
5955     if (FixedType.isNull()) return FixedType;
5956     FixedType = Context.getParenType(FixedType);
5957     return Qs.apply(Context, FixedType);
5958   }
5959 
5960   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5961   if (!VLATy)
5962     return QualType();
5963   // FIXME: We should probably handle this case
5964   if (VLATy->getElementType()->isVariablyModifiedType())
5965     return QualType();
5966 
5967   Expr::EvalResult Result;
5968   if (!VLATy->getSizeExpr() ||
5969       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5970     return QualType();
5971 
5972   llvm::APSInt Res = Result.Val.getInt();
5973 
5974   // Check whether the array size is negative.
5975   if (Res.isSigned() && Res.isNegative()) {
5976     SizeIsNegative = true;
5977     return QualType();
5978   }
5979 
5980   // Check whether the array is too large to be addressed.
5981   unsigned ActiveSizeBits
5982     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5983                                               Res);
5984   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5985     Oversized = Res;
5986     return QualType();
5987   }
5988 
5989   return Context.getConstantArrayType(
5990       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5991 }
5992 
5993 static void
5994 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5995   SrcTL = SrcTL.getUnqualifiedLoc();
5996   DstTL = DstTL.getUnqualifiedLoc();
5997   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5998     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5999     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6000                                       DstPTL.getPointeeLoc());
6001     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6002     return;
6003   }
6004   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6005     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6006     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6007                                       DstPTL.getInnerLoc());
6008     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6009     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6010     return;
6011   }
6012   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6013   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6014   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6015   TypeLoc DstElemTL = DstATL.getElementLoc();
6016   DstElemTL.initializeFullCopy(SrcElemTL);
6017   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6018   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6019   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6020 }
6021 
6022 /// Helper method to turn variable array types into constant array
6023 /// types in certain situations which would otherwise be errors (for
6024 /// GCC compatibility).
6025 static TypeSourceInfo*
6026 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6027                                               ASTContext &Context,
6028                                               bool &SizeIsNegative,
6029                                               llvm::APSInt &Oversized) {
6030   QualType FixedTy
6031     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6032                                           SizeIsNegative, Oversized);
6033   if (FixedTy.isNull())
6034     return nullptr;
6035   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6036   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6037                                     FixedTInfo->getTypeLoc());
6038   return FixedTInfo;
6039 }
6040 
6041 /// Register the given locally-scoped extern "C" declaration so
6042 /// that it can be found later for redeclarations. We include any extern "C"
6043 /// declaration that is not visible in the translation unit here, not just
6044 /// function-scope declarations.
6045 void
6046 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6047   if (!getLangOpts().CPlusPlus &&
6048       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6049     // Don't need to track declarations in the TU in C.
6050     return;
6051 
6052   // Note that we have a locally-scoped external with this name.
6053   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6054 }
6055 
6056 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6057   // FIXME: We can have multiple results via __attribute__((overloadable)).
6058   auto Result = Context.getExternCContextDecl()->lookup(Name);
6059   return Result.empty() ? nullptr : *Result.begin();
6060 }
6061 
6062 /// Diagnose function specifiers on a declaration of an identifier that
6063 /// does not identify a function.
6064 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6065   // FIXME: We should probably indicate the identifier in question to avoid
6066   // confusion for constructs like "virtual int a(), b;"
6067   if (DS.isVirtualSpecified())
6068     Diag(DS.getVirtualSpecLoc(),
6069          diag::err_virtual_non_function);
6070 
6071   if (DS.hasExplicitSpecifier())
6072     Diag(DS.getExplicitSpecLoc(),
6073          diag::err_explicit_non_function);
6074 
6075   if (DS.isNoreturnSpecified())
6076     Diag(DS.getNoreturnSpecLoc(),
6077          diag::err_noreturn_non_function);
6078 }
6079 
6080 NamedDecl*
6081 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6082                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6083   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6084   if (D.getCXXScopeSpec().isSet()) {
6085     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6086       << D.getCXXScopeSpec().getRange();
6087     D.setInvalidType();
6088     // Pretend we didn't see the scope specifier.
6089     DC = CurContext;
6090     Previous.clear();
6091   }
6092 
6093   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6094 
6095   if (D.getDeclSpec().isInlineSpecified())
6096     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6097         << getLangOpts().CPlusPlus17;
6098   if (D.getDeclSpec().hasConstexprSpecifier())
6099     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6100         << 1 << D.getDeclSpec().getConstexprSpecifier();
6101 
6102   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6103     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6104       Diag(D.getName().StartLocation,
6105            diag::err_deduction_guide_invalid_specifier)
6106           << "typedef";
6107     else
6108       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6109           << D.getName().getSourceRange();
6110     return nullptr;
6111   }
6112 
6113   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6114   if (!NewTD) return nullptr;
6115 
6116   // Handle attributes prior to checking for duplicates in MergeVarDecl
6117   ProcessDeclAttributes(S, NewTD, D);
6118 
6119   CheckTypedefForVariablyModifiedType(S, NewTD);
6120 
6121   bool Redeclaration = D.isRedeclaration();
6122   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6123   D.setRedeclaration(Redeclaration);
6124   return ND;
6125 }
6126 
6127 void
6128 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6129   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6130   // then it shall have block scope.
6131   // Note that variably modified types must be fixed before merging the decl so
6132   // that redeclarations will match.
6133   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6134   QualType T = TInfo->getType();
6135   if (T->isVariablyModifiedType()) {
6136     setFunctionHasBranchProtectedScope();
6137 
6138     if (S->getFnParent() == nullptr) {
6139       bool SizeIsNegative;
6140       llvm::APSInt Oversized;
6141       TypeSourceInfo *FixedTInfo =
6142         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6143                                                       SizeIsNegative,
6144                                                       Oversized);
6145       if (FixedTInfo) {
6146         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6147         NewTD->setTypeSourceInfo(FixedTInfo);
6148       } else {
6149         if (SizeIsNegative)
6150           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6151         else if (T->isVariableArrayType())
6152           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6153         else if (Oversized.getBoolValue())
6154           Diag(NewTD->getLocation(), diag::err_array_too_large)
6155             << Oversized.toString(10);
6156         else
6157           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6158         NewTD->setInvalidDecl();
6159       }
6160     }
6161   }
6162 }
6163 
6164 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6165 /// declares a typedef-name, either using the 'typedef' type specifier or via
6166 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6167 NamedDecl*
6168 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6169                            LookupResult &Previous, bool &Redeclaration) {
6170 
6171   // Find the shadowed declaration before filtering for scope.
6172   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6173 
6174   // Merge the decl with the existing one if appropriate. If the decl is
6175   // in an outer scope, it isn't the same thing.
6176   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6177                        /*AllowInlineNamespace*/false);
6178   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6179   if (!Previous.empty()) {
6180     Redeclaration = true;
6181     MergeTypedefNameDecl(S, NewTD, Previous);
6182   } else {
6183     inferGslPointerAttribute(NewTD);
6184   }
6185 
6186   if (ShadowedDecl && !Redeclaration)
6187     CheckShadow(NewTD, ShadowedDecl, Previous);
6188 
6189   // If this is the C FILE type, notify the AST context.
6190   if (IdentifierInfo *II = NewTD->getIdentifier())
6191     if (!NewTD->isInvalidDecl() &&
6192         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6193       if (II->isStr("FILE"))
6194         Context.setFILEDecl(NewTD);
6195       else if (II->isStr("jmp_buf"))
6196         Context.setjmp_bufDecl(NewTD);
6197       else if (II->isStr("sigjmp_buf"))
6198         Context.setsigjmp_bufDecl(NewTD);
6199       else if (II->isStr("ucontext_t"))
6200         Context.setucontext_tDecl(NewTD);
6201     }
6202 
6203   return NewTD;
6204 }
6205 
6206 /// Determines whether the given declaration is an out-of-scope
6207 /// previous declaration.
6208 ///
6209 /// This routine should be invoked when name lookup has found a
6210 /// previous declaration (PrevDecl) that is not in the scope where a
6211 /// new declaration by the same name is being introduced. If the new
6212 /// declaration occurs in a local scope, previous declarations with
6213 /// linkage may still be considered previous declarations (C99
6214 /// 6.2.2p4-5, C++ [basic.link]p6).
6215 ///
6216 /// \param PrevDecl the previous declaration found by name
6217 /// lookup
6218 ///
6219 /// \param DC the context in which the new declaration is being
6220 /// declared.
6221 ///
6222 /// \returns true if PrevDecl is an out-of-scope previous declaration
6223 /// for a new delcaration with the same name.
6224 static bool
6225 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6226                                 ASTContext &Context) {
6227   if (!PrevDecl)
6228     return false;
6229 
6230   if (!PrevDecl->hasLinkage())
6231     return false;
6232 
6233   if (Context.getLangOpts().CPlusPlus) {
6234     // C++ [basic.link]p6:
6235     //   If there is a visible declaration of an entity with linkage
6236     //   having the same name and type, ignoring entities declared
6237     //   outside the innermost enclosing namespace scope, the block
6238     //   scope declaration declares that same entity and receives the
6239     //   linkage of the previous declaration.
6240     DeclContext *OuterContext = DC->getRedeclContext();
6241     if (!OuterContext->isFunctionOrMethod())
6242       // This rule only applies to block-scope declarations.
6243       return false;
6244 
6245     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6246     if (PrevOuterContext->isRecord())
6247       // We found a member function: ignore it.
6248       return false;
6249 
6250     // Find the innermost enclosing namespace for the new and
6251     // previous declarations.
6252     OuterContext = OuterContext->getEnclosingNamespaceContext();
6253     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6254 
6255     // The previous declaration is in a different namespace, so it
6256     // isn't the same function.
6257     if (!OuterContext->Equals(PrevOuterContext))
6258       return false;
6259   }
6260 
6261   return true;
6262 }
6263 
6264 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6265   CXXScopeSpec &SS = D.getCXXScopeSpec();
6266   if (!SS.isSet()) return;
6267   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6268 }
6269 
6270 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6271   QualType type = decl->getType();
6272   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6273   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6274     // Various kinds of declaration aren't allowed to be __autoreleasing.
6275     unsigned kind = -1U;
6276     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6277       if (var->hasAttr<BlocksAttr>())
6278         kind = 0; // __block
6279       else if (!var->hasLocalStorage())
6280         kind = 1; // global
6281     } else if (isa<ObjCIvarDecl>(decl)) {
6282       kind = 3; // ivar
6283     } else if (isa<FieldDecl>(decl)) {
6284       kind = 2; // field
6285     }
6286 
6287     if (kind != -1U) {
6288       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6289         << kind;
6290     }
6291   } else if (lifetime == Qualifiers::OCL_None) {
6292     // Try to infer lifetime.
6293     if (!type->isObjCLifetimeType())
6294       return false;
6295 
6296     lifetime = type->getObjCARCImplicitLifetime();
6297     type = Context.getLifetimeQualifiedType(type, lifetime);
6298     decl->setType(type);
6299   }
6300 
6301   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6302     // Thread-local variables cannot have lifetime.
6303     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6304         var->getTLSKind()) {
6305       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6306         << var->getType();
6307       return true;
6308     }
6309   }
6310 
6311   return false;
6312 }
6313 
6314 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6315   if (Decl->getType().hasAddressSpace())
6316     return;
6317   if (Decl->getType()->isDependentType())
6318     return;
6319   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6320     QualType Type = Var->getType();
6321     if (Type->isSamplerT() || Type->isVoidType())
6322       return;
6323     LangAS ImplAS = LangAS::opencl_private;
6324     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6325         Var->hasGlobalStorage())
6326       ImplAS = LangAS::opencl_global;
6327     // If the original type from a decayed type is an array type and that array
6328     // type has no address space yet, deduce it now.
6329     if (auto DT = dyn_cast<DecayedType>(Type)) {
6330       auto OrigTy = DT->getOriginalType();
6331       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6332         // Add the address space to the original array type and then propagate
6333         // that to the element type through `getAsArrayType`.
6334         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6335         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6336         // Re-generate the decayed type.
6337         Type = Context.getDecayedType(OrigTy);
6338       }
6339     }
6340     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6341     // Apply any qualifiers (including address space) from the array type to
6342     // the element type. This implements C99 6.7.3p8: "If the specification of
6343     // an array type includes any type qualifiers, the element type is so
6344     // qualified, not the array type."
6345     if (Type->isArrayType())
6346       Type = QualType(Context.getAsArrayType(Type), 0);
6347     Decl->setType(Type);
6348   }
6349 }
6350 
6351 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6352   // Ensure that an auto decl is deduced otherwise the checks below might cache
6353   // the wrong linkage.
6354   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6355 
6356   // 'weak' only applies to declarations with external linkage.
6357   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6358     if (!ND.isExternallyVisible()) {
6359       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6360       ND.dropAttr<WeakAttr>();
6361     }
6362   }
6363   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6364     if (ND.isExternallyVisible()) {
6365       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6366       ND.dropAttr<WeakRefAttr>();
6367       ND.dropAttr<AliasAttr>();
6368     }
6369   }
6370 
6371   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6372     if (VD->hasInit()) {
6373       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6374         assert(VD->isThisDeclarationADefinition() &&
6375                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6376         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6377         VD->dropAttr<AliasAttr>();
6378       }
6379     }
6380   }
6381 
6382   // 'selectany' only applies to externally visible variable declarations.
6383   // It does not apply to functions.
6384   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6385     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6386       S.Diag(Attr->getLocation(),
6387              diag::err_attribute_selectany_non_extern_data);
6388       ND.dropAttr<SelectAnyAttr>();
6389     }
6390   }
6391 
6392   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6393     auto *VD = dyn_cast<VarDecl>(&ND);
6394     bool IsAnonymousNS = false;
6395     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6396     if (VD) {
6397       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6398       while (NS && !IsAnonymousNS) {
6399         IsAnonymousNS = NS->isAnonymousNamespace();
6400         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6401       }
6402     }
6403     // dll attributes require external linkage. Static locals may have external
6404     // linkage but still cannot be explicitly imported or exported.
6405     // In Microsoft mode, a variable defined in anonymous namespace must have
6406     // external linkage in order to be exported.
6407     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6408     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6409         (!AnonNSInMicrosoftMode &&
6410          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6411       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6412         << &ND << Attr;
6413       ND.setInvalidDecl();
6414     }
6415   }
6416 
6417   // Virtual functions cannot be marked as 'notail'.
6418   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6419     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6420       if (MD->isVirtual()) {
6421         S.Diag(ND.getLocation(),
6422                diag::err_invalid_attribute_on_virtual_function)
6423             << Attr;
6424         ND.dropAttr<NotTailCalledAttr>();
6425       }
6426 
6427   // Check the attributes on the function type, if any.
6428   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6429     // Don't declare this variable in the second operand of the for-statement;
6430     // GCC miscompiles that by ending its lifetime before evaluating the
6431     // third operand. See gcc.gnu.org/PR86769.
6432     AttributedTypeLoc ATL;
6433     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6434          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6435          TL = ATL.getModifiedLoc()) {
6436       // The [[lifetimebound]] attribute can be applied to the implicit object
6437       // parameter of a non-static member function (other than a ctor or dtor)
6438       // by applying it to the function type.
6439       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6440         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6441         if (!MD || MD->isStatic()) {
6442           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6443               << !MD << A->getRange();
6444         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6445           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6446               << isa<CXXDestructorDecl>(MD) << A->getRange();
6447         }
6448       }
6449     }
6450   }
6451 }
6452 
6453 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6454                                            NamedDecl *NewDecl,
6455                                            bool IsSpecialization,
6456                                            bool IsDefinition) {
6457   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6458     return;
6459 
6460   bool IsTemplate = false;
6461   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6462     OldDecl = OldTD->getTemplatedDecl();
6463     IsTemplate = true;
6464     if (!IsSpecialization)
6465       IsDefinition = false;
6466   }
6467   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6468     NewDecl = NewTD->getTemplatedDecl();
6469     IsTemplate = true;
6470   }
6471 
6472   if (!OldDecl || !NewDecl)
6473     return;
6474 
6475   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6476   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6477   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6478   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6479 
6480   // dllimport and dllexport are inheritable attributes so we have to exclude
6481   // inherited attribute instances.
6482   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6483                     (NewExportAttr && !NewExportAttr->isInherited());
6484 
6485   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6486   // the only exception being explicit specializations.
6487   // Implicitly generated declarations are also excluded for now because there
6488   // is no other way to switch these to use dllimport or dllexport.
6489   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6490 
6491   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6492     // Allow with a warning for free functions and global variables.
6493     bool JustWarn = false;
6494     if (!OldDecl->isCXXClassMember()) {
6495       auto *VD = dyn_cast<VarDecl>(OldDecl);
6496       if (VD && !VD->getDescribedVarTemplate())
6497         JustWarn = true;
6498       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6499       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6500         JustWarn = true;
6501     }
6502 
6503     // We cannot change a declaration that's been used because IR has already
6504     // been emitted. Dllimported functions will still work though (modulo
6505     // address equality) as they can use the thunk.
6506     if (OldDecl->isUsed())
6507       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6508         JustWarn = false;
6509 
6510     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6511                                : diag::err_attribute_dll_redeclaration;
6512     S.Diag(NewDecl->getLocation(), DiagID)
6513         << NewDecl
6514         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6515     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6516     if (!JustWarn) {
6517       NewDecl->setInvalidDecl();
6518       return;
6519     }
6520   }
6521 
6522   // A redeclaration is not allowed to drop a dllimport attribute, the only
6523   // exceptions being inline function definitions (except for function
6524   // templates), local extern declarations, qualified friend declarations or
6525   // special MSVC extension: in the last case, the declaration is treated as if
6526   // it were marked dllexport.
6527   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6528   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6529   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6530     // Ignore static data because out-of-line definitions are diagnosed
6531     // separately.
6532     IsStaticDataMember = VD->isStaticDataMember();
6533     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6534                    VarDecl::DeclarationOnly;
6535   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6536     IsInline = FD->isInlined();
6537     IsQualifiedFriend = FD->getQualifier() &&
6538                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6539   }
6540 
6541   if (OldImportAttr && !HasNewAttr &&
6542       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6543       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6544     if (IsMicrosoft && IsDefinition) {
6545       S.Diag(NewDecl->getLocation(),
6546              diag::warn_redeclaration_without_import_attribute)
6547           << NewDecl;
6548       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6549       NewDecl->dropAttr<DLLImportAttr>();
6550       NewDecl->addAttr(
6551           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6552     } else {
6553       S.Diag(NewDecl->getLocation(),
6554              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6555           << NewDecl << OldImportAttr;
6556       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6557       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6558       OldDecl->dropAttr<DLLImportAttr>();
6559       NewDecl->dropAttr<DLLImportAttr>();
6560     }
6561   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6562     // In MinGW, seeing a function declared inline drops the dllimport
6563     // attribute.
6564     OldDecl->dropAttr<DLLImportAttr>();
6565     NewDecl->dropAttr<DLLImportAttr>();
6566     S.Diag(NewDecl->getLocation(),
6567            diag::warn_dllimport_dropped_from_inline_function)
6568         << NewDecl << OldImportAttr;
6569   }
6570 
6571   // A specialization of a class template member function is processed here
6572   // since it's a redeclaration. If the parent class is dllexport, the
6573   // specialization inherits that attribute. This doesn't happen automatically
6574   // since the parent class isn't instantiated until later.
6575   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6576     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6577         !NewImportAttr && !NewExportAttr) {
6578       if (const DLLExportAttr *ParentExportAttr =
6579               MD->getParent()->getAttr<DLLExportAttr>()) {
6580         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6581         NewAttr->setInherited(true);
6582         NewDecl->addAttr(NewAttr);
6583       }
6584     }
6585   }
6586 }
6587 
6588 /// Given that we are within the definition of the given function,
6589 /// will that definition behave like C99's 'inline', where the
6590 /// definition is discarded except for optimization purposes?
6591 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6592   // Try to avoid calling GetGVALinkageForFunction.
6593 
6594   // All cases of this require the 'inline' keyword.
6595   if (!FD->isInlined()) return false;
6596 
6597   // This is only possible in C++ with the gnu_inline attribute.
6598   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6599     return false;
6600 
6601   // Okay, go ahead and call the relatively-more-expensive function.
6602   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6603 }
6604 
6605 /// Determine whether a variable is extern "C" prior to attaching
6606 /// an initializer. We can't just call isExternC() here, because that
6607 /// will also compute and cache whether the declaration is externally
6608 /// visible, which might change when we attach the initializer.
6609 ///
6610 /// This can only be used if the declaration is known to not be a
6611 /// redeclaration of an internal linkage declaration.
6612 ///
6613 /// For instance:
6614 ///
6615 ///   auto x = []{};
6616 ///
6617 /// Attaching the initializer here makes this declaration not externally
6618 /// visible, because its type has internal linkage.
6619 ///
6620 /// FIXME: This is a hack.
6621 template<typename T>
6622 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6623   if (S.getLangOpts().CPlusPlus) {
6624     // In C++, the overloadable attribute negates the effects of extern "C".
6625     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6626       return false;
6627 
6628     // So do CUDA's host/device attributes.
6629     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6630                                  D->template hasAttr<CUDAHostAttr>()))
6631       return false;
6632   }
6633   return D->isExternC();
6634 }
6635 
6636 static bool shouldConsiderLinkage(const VarDecl *VD) {
6637   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6638   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6639       isa<OMPDeclareMapperDecl>(DC))
6640     return VD->hasExternalStorage();
6641   if (DC->isFileContext())
6642     return true;
6643   if (DC->isRecord())
6644     return false;
6645   if (isa<RequiresExprBodyDecl>(DC))
6646     return false;
6647   llvm_unreachable("Unexpected context");
6648 }
6649 
6650 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6651   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6652   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6653       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6654     return true;
6655   if (DC->isRecord())
6656     return false;
6657   llvm_unreachable("Unexpected context");
6658 }
6659 
6660 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6661                           ParsedAttr::Kind Kind) {
6662   // Check decl attributes on the DeclSpec.
6663   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6664     return true;
6665 
6666   // Walk the declarator structure, checking decl attributes that were in a type
6667   // position to the decl itself.
6668   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6669     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6670       return true;
6671   }
6672 
6673   // Finally, check attributes on the decl itself.
6674   return PD.getAttributes().hasAttribute(Kind);
6675 }
6676 
6677 /// Adjust the \c DeclContext for a function or variable that might be a
6678 /// function-local external declaration.
6679 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6680   if (!DC->isFunctionOrMethod())
6681     return false;
6682 
6683   // If this is a local extern function or variable declared within a function
6684   // template, don't add it into the enclosing namespace scope until it is
6685   // instantiated; it might have a dependent type right now.
6686   if (DC->isDependentContext())
6687     return true;
6688 
6689   // C++11 [basic.link]p7:
6690   //   When a block scope declaration of an entity with linkage is not found to
6691   //   refer to some other declaration, then that entity is a member of the
6692   //   innermost enclosing namespace.
6693   //
6694   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6695   // semantically-enclosing namespace, not a lexically-enclosing one.
6696   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6697     DC = DC->getParent();
6698   return true;
6699 }
6700 
6701 /// Returns true if given declaration has external C language linkage.
6702 static bool isDeclExternC(const Decl *D) {
6703   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6704     return FD->isExternC();
6705   if (const auto *VD = dyn_cast<VarDecl>(D))
6706     return VD->isExternC();
6707 
6708   llvm_unreachable("Unknown type of decl!");
6709 }
6710 /// Returns true if there hasn't been any invalid type diagnosed.
6711 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6712                                 DeclContext *DC, QualType R) {
6713   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6714   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6715   // argument.
6716   if (R->isImageType() || R->isPipeType()) {
6717     Se.Diag(D.getIdentifierLoc(),
6718             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6719         << R;
6720     D.setInvalidType();
6721     return false;
6722   }
6723 
6724   // OpenCL v1.2 s6.9.r:
6725   // The event type cannot be used to declare a program scope variable.
6726   // OpenCL v2.0 s6.9.q:
6727   // The clk_event_t and reserve_id_t types cannot be declared in program
6728   // scope.
6729   if (NULL == S->getParent()) {
6730     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6731       Se.Diag(D.getIdentifierLoc(),
6732               diag::err_invalid_type_for_program_scope_var)
6733           << R;
6734       D.setInvalidType();
6735       return false;
6736     }
6737   }
6738 
6739   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6740   QualType NR = R;
6741   while (NR->isPointerType()) {
6742     if (NR->isFunctionPointerType()) {
6743       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6744       D.setInvalidType();
6745       return false;
6746     }
6747     NR = NR->getPointeeType();
6748   }
6749 
6750   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6751     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6752     // half array type (unless the cl_khr_fp16 extension is enabled).
6753     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6754       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6755       D.setInvalidType();
6756       return false;
6757     }
6758   }
6759 
6760   // OpenCL v1.2 s6.9.r:
6761   // The event type cannot be used with the __local, __constant and __global
6762   // address space qualifiers.
6763   if (R->isEventT()) {
6764     if (R.getAddressSpace() != LangAS::opencl_private) {
6765       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6766       D.setInvalidType();
6767       return false;
6768     }
6769   }
6770 
6771   // C++ for OpenCL does not allow the thread_local storage qualifier.
6772   // OpenCL C does not support thread_local either, and
6773   // also reject all other thread storage class specifiers.
6774   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6775   if (TSC != TSCS_unspecified) {
6776     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6777     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6778             diag::err_opencl_unknown_type_specifier)
6779         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6780         << DeclSpec::getSpecifierName(TSC) << 1;
6781     D.setInvalidType();
6782     return false;
6783   }
6784 
6785   if (R->isSamplerT()) {
6786     // OpenCL v1.2 s6.9.b p4:
6787     // The sampler type cannot be used with the __local and __global address
6788     // space qualifiers.
6789     if (R.getAddressSpace() == LangAS::opencl_local ||
6790         R.getAddressSpace() == LangAS::opencl_global) {
6791       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6792       D.setInvalidType();
6793     }
6794 
6795     // OpenCL v1.2 s6.12.14.1:
6796     // A global sampler must be declared with either the constant address
6797     // space qualifier or with the const qualifier.
6798     if (DC->isTranslationUnit() &&
6799         !(R.getAddressSpace() == LangAS::opencl_constant ||
6800           R.isConstQualified())) {
6801       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6802       D.setInvalidType();
6803     }
6804     if (D.isInvalidType())
6805       return false;
6806   }
6807   return true;
6808 }
6809 
6810 NamedDecl *Sema::ActOnVariableDeclarator(
6811     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6812     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6813     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6814   QualType R = TInfo->getType();
6815   DeclarationName Name = GetNameForDeclarator(D).getName();
6816 
6817   IdentifierInfo *II = Name.getAsIdentifierInfo();
6818 
6819   if (D.isDecompositionDeclarator()) {
6820     // Take the name of the first declarator as our name for diagnostic
6821     // purposes.
6822     auto &Decomp = D.getDecompositionDeclarator();
6823     if (!Decomp.bindings().empty()) {
6824       II = Decomp.bindings()[0].Name;
6825       Name = II;
6826     }
6827   } else if (!II) {
6828     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6829     return nullptr;
6830   }
6831 
6832 
6833   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6834   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6835 
6836   // dllimport globals without explicit storage class are treated as extern. We
6837   // have to change the storage class this early to get the right DeclContext.
6838   if (SC == SC_None && !DC->isRecord() &&
6839       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6840       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6841     SC = SC_Extern;
6842 
6843   DeclContext *OriginalDC = DC;
6844   bool IsLocalExternDecl = SC == SC_Extern &&
6845                            adjustContextForLocalExternDecl(DC);
6846 
6847   if (SCSpec == DeclSpec::SCS_mutable) {
6848     // mutable can only appear on non-static class members, so it's always
6849     // an error here
6850     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6851     D.setInvalidType();
6852     SC = SC_None;
6853   }
6854 
6855   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6856       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6857                               D.getDeclSpec().getStorageClassSpecLoc())) {
6858     // In C++11, the 'register' storage class specifier is deprecated.
6859     // Suppress the warning in system macros, it's used in macros in some
6860     // popular C system headers, such as in glibc's htonl() macro.
6861     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6862          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6863                                    : diag::warn_deprecated_register)
6864       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6865   }
6866 
6867   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6868 
6869   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6870     // C99 6.9p2: The storage-class specifiers auto and register shall not
6871     // appear in the declaration specifiers in an external declaration.
6872     // Global Register+Asm is a GNU extension we support.
6873     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6874       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6875       D.setInvalidType();
6876     }
6877   }
6878 
6879   bool IsMemberSpecialization = false;
6880   bool IsVariableTemplateSpecialization = false;
6881   bool IsPartialSpecialization = false;
6882   bool IsVariableTemplate = false;
6883   VarDecl *NewVD = nullptr;
6884   VarTemplateDecl *NewTemplate = nullptr;
6885   TemplateParameterList *TemplateParams = nullptr;
6886   if (!getLangOpts().CPlusPlus) {
6887     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6888                             II, R, TInfo, SC);
6889 
6890     if (R->getContainedDeducedType())
6891       ParsingInitForAutoVars.insert(NewVD);
6892 
6893     if (D.isInvalidType())
6894       NewVD->setInvalidDecl();
6895 
6896     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6897         NewVD->hasLocalStorage())
6898       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6899                             NTCUC_AutoVar, NTCUK_Destruct);
6900   } else {
6901     bool Invalid = false;
6902 
6903     if (DC->isRecord() && !CurContext->isRecord()) {
6904       // This is an out-of-line definition of a static data member.
6905       switch (SC) {
6906       case SC_None:
6907         break;
6908       case SC_Static:
6909         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6910              diag::err_static_out_of_line)
6911           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6912         break;
6913       case SC_Auto:
6914       case SC_Register:
6915       case SC_Extern:
6916         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6917         // to names of variables declared in a block or to function parameters.
6918         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6919         // of class members
6920 
6921         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6922              diag::err_storage_class_for_static_member)
6923           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6924         break;
6925       case SC_PrivateExtern:
6926         llvm_unreachable("C storage class in c++!");
6927       }
6928     }
6929 
6930     if (SC == SC_Static && CurContext->isRecord()) {
6931       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6932         // Walk up the enclosing DeclContexts to check for any that are
6933         // incompatible with static data members.
6934         const DeclContext *FunctionOrMethod = nullptr;
6935         const CXXRecordDecl *AnonStruct = nullptr;
6936         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6937           if (Ctxt->isFunctionOrMethod()) {
6938             FunctionOrMethod = Ctxt;
6939             break;
6940           }
6941           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6942           if (ParentDecl && !ParentDecl->getDeclName()) {
6943             AnonStruct = ParentDecl;
6944             break;
6945           }
6946         }
6947         if (FunctionOrMethod) {
6948           // C++ [class.static.data]p5: A local class shall not have static data
6949           // members.
6950           Diag(D.getIdentifierLoc(),
6951                diag::err_static_data_member_not_allowed_in_local_class)
6952             << Name << RD->getDeclName() << RD->getTagKind();
6953         } else if (AnonStruct) {
6954           // C++ [class.static.data]p4: Unnamed classes and classes contained
6955           // directly or indirectly within unnamed classes shall not contain
6956           // static data members.
6957           Diag(D.getIdentifierLoc(),
6958                diag::err_static_data_member_not_allowed_in_anon_struct)
6959             << Name << AnonStruct->getTagKind();
6960           Invalid = true;
6961         } else if (RD->isUnion()) {
6962           // C++98 [class.union]p1: If a union contains a static data member,
6963           // the program is ill-formed. C++11 drops this restriction.
6964           Diag(D.getIdentifierLoc(),
6965                getLangOpts().CPlusPlus11
6966                  ? diag::warn_cxx98_compat_static_data_member_in_union
6967                  : diag::ext_static_data_member_in_union) << Name;
6968         }
6969       }
6970     }
6971 
6972     // Match up the template parameter lists with the scope specifier, then
6973     // determine whether we have a template or a template specialization.
6974     bool InvalidScope = false;
6975     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6976         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6977         D.getCXXScopeSpec(),
6978         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6979             ? D.getName().TemplateId
6980             : nullptr,
6981         TemplateParamLists,
6982         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6983     Invalid |= InvalidScope;
6984 
6985     if (TemplateParams) {
6986       if (!TemplateParams->size() &&
6987           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6988         // There is an extraneous 'template<>' for this variable. Complain
6989         // about it, but allow the declaration of the variable.
6990         Diag(TemplateParams->getTemplateLoc(),
6991              diag::err_template_variable_noparams)
6992           << II
6993           << SourceRange(TemplateParams->getTemplateLoc(),
6994                          TemplateParams->getRAngleLoc());
6995         TemplateParams = nullptr;
6996       } else {
6997         // Check that we can declare a template here.
6998         if (CheckTemplateDeclScope(S, TemplateParams))
6999           return nullptr;
7000 
7001         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7002           // This is an explicit specialization or a partial specialization.
7003           IsVariableTemplateSpecialization = true;
7004           IsPartialSpecialization = TemplateParams->size() > 0;
7005         } else { // if (TemplateParams->size() > 0)
7006           // This is a template declaration.
7007           IsVariableTemplate = true;
7008 
7009           // Only C++1y supports variable templates (N3651).
7010           Diag(D.getIdentifierLoc(),
7011                getLangOpts().CPlusPlus14
7012                    ? diag::warn_cxx11_compat_variable_template
7013                    : diag::ext_variable_template);
7014         }
7015       }
7016     } else {
7017       // Check that we can declare a member specialization here.
7018       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7019           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7020         return nullptr;
7021       assert((Invalid ||
7022               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7023              "should have a 'template<>' for this decl");
7024     }
7025 
7026     if (IsVariableTemplateSpecialization) {
7027       SourceLocation TemplateKWLoc =
7028           TemplateParamLists.size() > 0
7029               ? TemplateParamLists[0]->getTemplateLoc()
7030               : SourceLocation();
7031       DeclResult Res = ActOnVarTemplateSpecialization(
7032           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7033           IsPartialSpecialization);
7034       if (Res.isInvalid())
7035         return nullptr;
7036       NewVD = cast<VarDecl>(Res.get());
7037       AddToScope = false;
7038     } else if (D.isDecompositionDeclarator()) {
7039       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7040                                         D.getIdentifierLoc(), R, TInfo, SC,
7041                                         Bindings);
7042     } else
7043       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7044                               D.getIdentifierLoc(), II, R, TInfo, SC);
7045 
7046     // If this is supposed to be a variable template, create it as such.
7047     if (IsVariableTemplate) {
7048       NewTemplate =
7049           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7050                                   TemplateParams, NewVD);
7051       NewVD->setDescribedVarTemplate(NewTemplate);
7052     }
7053 
7054     // If this decl has an auto type in need of deduction, make a note of the
7055     // Decl so we can diagnose uses of it in its own initializer.
7056     if (R->getContainedDeducedType())
7057       ParsingInitForAutoVars.insert(NewVD);
7058 
7059     if (D.isInvalidType() || Invalid) {
7060       NewVD->setInvalidDecl();
7061       if (NewTemplate)
7062         NewTemplate->setInvalidDecl();
7063     }
7064 
7065     SetNestedNameSpecifier(*this, NewVD, D);
7066 
7067     // If we have any template parameter lists that don't directly belong to
7068     // the variable (matching the scope specifier), store them.
7069     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7070     if (TemplateParamLists.size() > VDTemplateParamLists)
7071       NewVD->setTemplateParameterListsInfo(
7072           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7073   }
7074 
7075   if (D.getDeclSpec().isInlineSpecified()) {
7076     if (!getLangOpts().CPlusPlus) {
7077       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7078           << 0;
7079     } else if (CurContext->isFunctionOrMethod()) {
7080       // 'inline' is not allowed on block scope variable declaration.
7081       Diag(D.getDeclSpec().getInlineSpecLoc(),
7082            diag::err_inline_declaration_block_scope) << Name
7083         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7084     } else {
7085       Diag(D.getDeclSpec().getInlineSpecLoc(),
7086            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7087                                      : diag::ext_inline_variable);
7088       NewVD->setInlineSpecified();
7089     }
7090   }
7091 
7092   // Set the lexical context. If the declarator has a C++ scope specifier, the
7093   // lexical context will be different from the semantic context.
7094   NewVD->setLexicalDeclContext(CurContext);
7095   if (NewTemplate)
7096     NewTemplate->setLexicalDeclContext(CurContext);
7097 
7098   if (IsLocalExternDecl) {
7099     if (D.isDecompositionDeclarator())
7100       for (auto *B : Bindings)
7101         B->setLocalExternDecl();
7102     else
7103       NewVD->setLocalExternDecl();
7104   }
7105 
7106   bool EmitTLSUnsupportedError = false;
7107   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7108     // C++11 [dcl.stc]p4:
7109     //   When thread_local is applied to a variable of block scope the
7110     //   storage-class-specifier static is implied if it does not appear
7111     //   explicitly.
7112     // Core issue: 'static' is not implied if the variable is declared
7113     //   'extern'.
7114     if (NewVD->hasLocalStorage() &&
7115         (SCSpec != DeclSpec::SCS_unspecified ||
7116          TSCS != DeclSpec::TSCS_thread_local ||
7117          !DC->isFunctionOrMethod()))
7118       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7119            diag::err_thread_non_global)
7120         << DeclSpec::getSpecifierName(TSCS);
7121     else if (!Context.getTargetInfo().isTLSSupported()) {
7122       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7123           getLangOpts().SYCLIsDevice) {
7124         // Postpone error emission until we've collected attributes required to
7125         // figure out whether it's a host or device variable and whether the
7126         // error should be ignored.
7127         EmitTLSUnsupportedError = true;
7128         // We still need to mark the variable as TLS so it shows up in AST with
7129         // proper storage class for other tools to use even if we're not going
7130         // to emit any code for it.
7131         NewVD->setTSCSpec(TSCS);
7132       } else
7133         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7134              diag::err_thread_unsupported);
7135     } else
7136       NewVD->setTSCSpec(TSCS);
7137   }
7138 
7139   switch (D.getDeclSpec().getConstexprSpecifier()) {
7140   case CSK_unspecified:
7141     break;
7142 
7143   case CSK_consteval:
7144     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7145         diag::err_constexpr_wrong_decl_kind)
7146       << D.getDeclSpec().getConstexprSpecifier();
7147     LLVM_FALLTHROUGH;
7148 
7149   case CSK_constexpr:
7150     NewVD->setConstexpr(true);
7151     MaybeAddCUDAConstantAttr(NewVD);
7152     // C++1z [dcl.spec.constexpr]p1:
7153     //   A static data member declared with the constexpr specifier is
7154     //   implicitly an inline variable.
7155     if (NewVD->isStaticDataMember() &&
7156         (getLangOpts().CPlusPlus17 ||
7157          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7158       NewVD->setImplicitlyInline();
7159     break;
7160 
7161   case CSK_constinit:
7162     if (!NewVD->hasGlobalStorage())
7163       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7164            diag::err_constinit_local_variable);
7165     else
7166       NewVD->addAttr(ConstInitAttr::Create(
7167           Context, D.getDeclSpec().getConstexprSpecLoc(),
7168           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7169     break;
7170   }
7171 
7172   // C99 6.7.4p3
7173   //   An inline definition of a function with external linkage shall
7174   //   not contain a definition of a modifiable object with static or
7175   //   thread storage duration...
7176   // We only apply this when the function is required to be defined
7177   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7178   // that a local variable with thread storage duration still has to
7179   // be marked 'static'.  Also note that it's possible to get these
7180   // semantics in C++ using __attribute__((gnu_inline)).
7181   if (SC == SC_Static && S->getFnParent() != nullptr &&
7182       !NewVD->getType().isConstQualified()) {
7183     FunctionDecl *CurFD = getCurFunctionDecl();
7184     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7185       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7186            diag::warn_static_local_in_extern_inline);
7187       MaybeSuggestAddingStaticToDecl(CurFD);
7188     }
7189   }
7190 
7191   if (D.getDeclSpec().isModulePrivateSpecified()) {
7192     if (IsVariableTemplateSpecialization)
7193       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7194           << (IsPartialSpecialization ? 1 : 0)
7195           << FixItHint::CreateRemoval(
7196                  D.getDeclSpec().getModulePrivateSpecLoc());
7197     else if (IsMemberSpecialization)
7198       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7199         << 2
7200         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7201     else if (NewVD->hasLocalStorage())
7202       Diag(NewVD->getLocation(), diag::err_module_private_local)
7203           << 0 << NewVD
7204           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7205           << FixItHint::CreateRemoval(
7206                  D.getDeclSpec().getModulePrivateSpecLoc());
7207     else {
7208       NewVD->setModulePrivate();
7209       if (NewTemplate)
7210         NewTemplate->setModulePrivate();
7211       for (auto *B : Bindings)
7212         B->setModulePrivate();
7213     }
7214   }
7215 
7216   if (getLangOpts().OpenCL) {
7217 
7218     deduceOpenCLAddressSpace(NewVD);
7219 
7220     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7221   }
7222 
7223   // Handle attributes prior to checking for duplicates in MergeVarDecl
7224   ProcessDeclAttributes(S, NewVD, D);
7225 
7226   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7227       getLangOpts().SYCLIsDevice) {
7228     if (EmitTLSUnsupportedError &&
7229         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7230          (getLangOpts().OpenMPIsDevice &&
7231           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7232       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7233            diag::err_thread_unsupported);
7234 
7235     if (EmitTLSUnsupportedError &&
7236         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7237       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7238     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7239     // storage [duration]."
7240     if (SC == SC_None && S->getFnParent() != nullptr &&
7241         (NewVD->hasAttr<CUDASharedAttr>() ||
7242          NewVD->hasAttr<CUDAConstantAttr>())) {
7243       NewVD->setStorageClass(SC_Static);
7244     }
7245   }
7246 
7247   // Ensure that dllimport globals without explicit storage class are treated as
7248   // extern. The storage class is set above using parsed attributes. Now we can
7249   // check the VarDecl itself.
7250   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7251          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7252          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7253 
7254   // In auto-retain/release, infer strong retension for variables of
7255   // retainable type.
7256   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7257     NewVD->setInvalidDecl();
7258 
7259   // Handle GNU asm-label extension (encoded as an attribute).
7260   if (Expr *E = (Expr*)D.getAsmLabel()) {
7261     // The parser guarantees this is a string.
7262     StringLiteral *SE = cast<StringLiteral>(E);
7263     StringRef Label = SE->getString();
7264     if (S->getFnParent() != nullptr) {
7265       switch (SC) {
7266       case SC_None:
7267       case SC_Auto:
7268         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7269         break;
7270       case SC_Register:
7271         // Local Named register
7272         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7273             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7274           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7275         break;
7276       case SC_Static:
7277       case SC_Extern:
7278       case SC_PrivateExtern:
7279         break;
7280       }
7281     } else if (SC == SC_Register) {
7282       // Global Named register
7283       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7284         const auto &TI = Context.getTargetInfo();
7285         bool HasSizeMismatch;
7286 
7287         if (!TI.isValidGCCRegisterName(Label))
7288           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7289         else if (!TI.validateGlobalRegisterVariable(Label,
7290                                                     Context.getTypeSize(R),
7291                                                     HasSizeMismatch))
7292           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7293         else if (HasSizeMismatch)
7294           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7295       }
7296 
7297       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7298         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7299         NewVD->setInvalidDecl(true);
7300       }
7301     }
7302 
7303     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7304                                         /*IsLiteralLabel=*/true,
7305                                         SE->getStrTokenLoc(0)));
7306   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7307     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7308       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7309     if (I != ExtnameUndeclaredIdentifiers.end()) {
7310       if (isDeclExternC(NewVD)) {
7311         NewVD->addAttr(I->second);
7312         ExtnameUndeclaredIdentifiers.erase(I);
7313       } else
7314         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7315             << /*Variable*/1 << NewVD;
7316     }
7317   }
7318 
7319   // Find the shadowed declaration before filtering for scope.
7320   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7321                                 ? getShadowedDeclaration(NewVD, Previous)
7322                                 : nullptr;
7323 
7324   // Don't consider existing declarations that are in a different
7325   // scope and are out-of-semantic-context declarations (if the new
7326   // declaration has linkage).
7327   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7328                        D.getCXXScopeSpec().isNotEmpty() ||
7329                        IsMemberSpecialization ||
7330                        IsVariableTemplateSpecialization);
7331 
7332   // Check whether the previous declaration is in the same block scope. This
7333   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7334   if (getLangOpts().CPlusPlus &&
7335       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7336     NewVD->setPreviousDeclInSameBlockScope(
7337         Previous.isSingleResult() && !Previous.isShadowed() &&
7338         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7339 
7340   if (!getLangOpts().CPlusPlus) {
7341     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7342   } else {
7343     // If this is an explicit specialization of a static data member, check it.
7344     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7345         CheckMemberSpecialization(NewVD, Previous))
7346       NewVD->setInvalidDecl();
7347 
7348     // Merge the decl with the existing one if appropriate.
7349     if (!Previous.empty()) {
7350       if (Previous.isSingleResult() &&
7351           isa<FieldDecl>(Previous.getFoundDecl()) &&
7352           D.getCXXScopeSpec().isSet()) {
7353         // The user tried to define a non-static data member
7354         // out-of-line (C++ [dcl.meaning]p1).
7355         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7356           << D.getCXXScopeSpec().getRange();
7357         Previous.clear();
7358         NewVD->setInvalidDecl();
7359       }
7360     } else if (D.getCXXScopeSpec().isSet()) {
7361       // No previous declaration in the qualifying scope.
7362       Diag(D.getIdentifierLoc(), diag::err_no_member)
7363         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7364         << D.getCXXScopeSpec().getRange();
7365       NewVD->setInvalidDecl();
7366     }
7367 
7368     if (!IsVariableTemplateSpecialization)
7369       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7370 
7371     if (NewTemplate) {
7372       VarTemplateDecl *PrevVarTemplate =
7373           NewVD->getPreviousDecl()
7374               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7375               : nullptr;
7376 
7377       // Check the template parameter list of this declaration, possibly
7378       // merging in the template parameter list from the previous variable
7379       // template declaration.
7380       if (CheckTemplateParameterList(
7381               TemplateParams,
7382               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7383                               : nullptr,
7384               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7385                DC->isDependentContext())
7386                   ? TPC_ClassTemplateMember
7387                   : TPC_VarTemplate))
7388         NewVD->setInvalidDecl();
7389 
7390       // If we are providing an explicit specialization of a static variable
7391       // template, make a note of that.
7392       if (PrevVarTemplate &&
7393           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7394         PrevVarTemplate->setMemberSpecialization();
7395     }
7396   }
7397 
7398   // Diagnose shadowed variables iff this isn't a redeclaration.
7399   if (ShadowedDecl && !D.isRedeclaration())
7400     CheckShadow(NewVD, ShadowedDecl, Previous);
7401 
7402   ProcessPragmaWeak(S, NewVD);
7403 
7404   // If this is the first declaration of an extern C variable, update
7405   // the map of such variables.
7406   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7407       isIncompleteDeclExternC(*this, NewVD))
7408     RegisterLocallyScopedExternCDecl(NewVD, S);
7409 
7410   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7411     MangleNumberingContext *MCtx;
7412     Decl *ManglingContextDecl;
7413     std::tie(MCtx, ManglingContextDecl) =
7414         getCurrentMangleNumberContext(NewVD->getDeclContext());
7415     if (MCtx) {
7416       Context.setManglingNumber(
7417           NewVD, MCtx->getManglingNumber(
7418                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7419       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7420     }
7421   }
7422 
7423   // Special handling of variable named 'main'.
7424   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7425       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7426       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7427 
7428     // C++ [basic.start.main]p3
7429     // A program that declares a variable main at global scope is ill-formed.
7430     if (getLangOpts().CPlusPlus)
7431       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7432 
7433     // In C, and external-linkage variable named main results in undefined
7434     // behavior.
7435     else if (NewVD->hasExternalFormalLinkage())
7436       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7437   }
7438 
7439   if (D.isRedeclaration() && !Previous.empty()) {
7440     NamedDecl *Prev = Previous.getRepresentativeDecl();
7441     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7442                                    D.isFunctionDefinition());
7443   }
7444 
7445   if (NewTemplate) {
7446     if (NewVD->isInvalidDecl())
7447       NewTemplate->setInvalidDecl();
7448     ActOnDocumentableDecl(NewTemplate);
7449     return NewTemplate;
7450   }
7451 
7452   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7453     CompleteMemberSpecialization(NewVD, Previous);
7454 
7455   return NewVD;
7456 }
7457 
7458 /// Enum describing the %select options in diag::warn_decl_shadow.
7459 enum ShadowedDeclKind {
7460   SDK_Local,
7461   SDK_Global,
7462   SDK_StaticMember,
7463   SDK_Field,
7464   SDK_Typedef,
7465   SDK_Using
7466 };
7467 
7468 /// Determine what kind of declaration we're shadowing.
7469 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7470                                                 const DeclContext *OldDC) {
7471   if (isa<TypeAliasDecl>(ShadowedDecl))
7472     return SDK_Using;
7473   else if (isa<TypedefDecl>(ShadowedDecl))
7474     return SDK_Typedef;
7475   else if (isa<RecordDecl>(OldDC))
7476     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7477 
7478   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7479 }
7480 
7481 /// Return the location of the capture if the given lambda captures the given
7482 /// variable \p VD, or an invalid source location otherwise.
7483 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7484                                          const VarDecl *VD) {
7485   for (const Capture &Capture : LSI->Captures) {
7486     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7487       return Capture.getLocation();
7488   }
7489   return SourceLocation();
7490 }
7491 
7492 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7493                                      const LookupResult &R) {
7494   // Only diagnose if we're shadowing an unambiguous field or variable.
7495   if (R.getResultKind() != LookupResult::Found)
7496     return false;
7497 
7498   // Return false if warning is ignored.
7499   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7500 }
7501 
7502 /// Return the declaration shadowed by the given variable \p D, or null
7503 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7504 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7505                                         const LookupResult &R) {
7506   if (!shouldWarnIfShadowedDecl(Diags, R))
7507     return nullptr;
7508 
7509   // Don't diagnose declarations at file scope.
7510   if (D->hasGlobalStorage())
7511     return nullptr;
7512 
7513   NamedDecl *ShadowedDecl = R.getFoundDecl();
7514   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7515              ? ShadowedDecl
7516              : nullptr;
7517 }
7518 
7519 /// Return the declaration shadowed by the given typedef \p D, or null
7520 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7521 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7522                                         const LookupResult &R) {
7523   // Don't warn if typedef declaration is part of a class
7524   if (D->getDeclContext()->isRecord())
7525     return nullptr;
7526 
7527   if (!shouldWarnIfShadowedDecl(Diags, R))
7528     return nullptr;
7529 
7530   NamedDecl *ShadowedDecl = R.getFoundDecl();
7531   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7532 }
7533 
7534 /// Diagnose variable or built-in function shadowing.  Implements
7535 /// -Wshadow.
7536 ///
7537 /// This method is called whenever a VarDecl is added to a "useful"
7538 /// scope.
7539 ///
7540 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7541 /// \param R the lookup of the name
7542 ///
7543 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7544                        const LookupResult &R) {
7545   DeclContext *NewDC = D->getDeclContext();
7546 
7547   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7548     // Fields are not shadowed by variables in C++ static methods.
7549     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7550       if (MD->isStatic())
7551         return;
7552 
7553     // Fields shadowed by constructor parameters are a special case. Usually
7554     // the constructor initializes the field with the parameter.
7555     if (isa<CXXConstructorDecl>(NewDC))
7556       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7557         // Remember that this was shadowed so we can either warn about its
7558         // modification or its existence depending on warning settings.
7559         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7560         return;
7561       }
7562   }
7563 
7564   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7565     if (shadowedVar->isExternC()) {
7566       // For shadowing external vars, make sure that we point to the global
7567       // declaration, not a locally scoped extern declaration.
7568       for (auto I : shadowedVar->redecls())
7569         if (I->isFileVarDecl()) {
7570           ShadowedDecl = I;
7571           break;
7572         }
7573     }
7574 
7575   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7576 
7577   unsigned WarningDiag = diag::warn_decl_shadow;
7578   SourceLocation CaptureLoc;
7579   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7580       isa<CXXMethodDecl>(NewDC)) {
7581     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7582       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7583         if (RD->getLambdaCaptureDefault() == LCD_None) {
7584           // Try to avoid warnings for lambdas with an explicit capture list.
7585           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7586           // Warn only when the lambda captures the shadowed decl explicitly.
7587           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7588           if (CaptureLoc.isInvalid())
7589             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7590         } else {
7591           // Remember that this was shadowed so we can avoid the warning if the
7592           // shadowed decl isn't captured and the warning settings allow it.
7593           cast<LambdaScopeInfo>(getCurFunction())
7594               ->ShadowingDecls.push_back(
7595                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7596           return;
7597         }
7598       }
7599 
7600       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7601         // A variable can't shadow a local variable in an enclosing scope, if
7602         // they are separated by a non-capturing declaration context.
7603         for (DeclContext *ParentDC = NewDC;
7604              ParentDC && !ParentDC->Equals(OldDC);
7605              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7606           // Only block literals, captured statements, and lambda expressions
7607           // can capture; other scopes don't.
7608           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7609               !isLambdaCallOperator(ParentDC)) {
7610             return;
7611           }
7612         }
7613       }
7614     }
7615   }
7616 
7617   // Only warn about certain kinds of shadowing for class members.
7618   if (NewDC && NewDC->isRecord()) {
7619     // In particular, don't warn about shadowing non-class members.
7620     if (!OldDC->isRecord())
7621       return;
7622 
7623     // TODO: should we warn about static data members shadowing
7624     // static data members from base classes?
7625 
7626     // TODO: don't diagnose for inaccessible shadowed members.
7627     // This is hard to do perfectly because we might friend the
7628     // shadowing context, but that's just a false negative.
7629   }
7630 
7631 
7632   DeclarationName Name = R.getLookupName();
7633 
7634   // Emit warning and note.
7635   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7636     return;
7637   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7638   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7639   if (!CaptureLoc.isInvalid())
7640     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7641         << Name << /*explicitly*/ 1;
7642   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7643 }
7644 
7645 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7646 /// when these variables are captured by the lambda.
7647 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7648   for (const auto &Shadow : LSI->ShadowingDecls) {
7649     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7650     // Try to avoid the warning when the shadowed decl isn't captured.
7651     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7652     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7653     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7654                                        ? diag::warn_decl_shadow_uncaptured_local
7655                                        : diag::warn_decl_shadow)
7656         << Shadow.VD->getDeclName()
7657         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7658     if (!CaptureLoc.isInvalid())
7659       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7660           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7661     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7662   }
7663 }
7664 
7665 /// Check -Wshadow without the advantage of a previous lookup.
7666 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7667   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7668     return;
7669 
7670   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7671                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7672   LookupName(R, S);
7673   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7674     CheckShadow(D, ShadowedDecl, R);
7675 }
7676 
7677 /// Check if 'E', which is an expression that is about to be modified, refers
7678 /// to a constructor parameter that shadows a field.
7679 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7680   // Quickly ignore expressions that can't be shadowing ctor parameters.
7681   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7682     return;
7683   E = E->IgnoreParenImpCasts();
7684   auto *DRE = dyn_cast<DeclRefExpr>(E);
7685   if (!DRE)
7686     return;
7687   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7688   auto I = ShadowingDecls.find(D);
7689   if (I == ShadowingDecls.end())
7690     return;
7691   const NamedDecl *ShadowedDecl = I->second;
7692   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7693   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7694   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7695   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7696 
7697   // Avoid issuing multiple warnings about the same decl.
7698   ShadowingDecls.erase(I);
7699 }
7700 
7701 /// Check for conflict between this global or extern "C" declaration and
7702 /// previous global or extern "C" declarations. This is only used in C++.
7703 template<typename T>
7704 static bool checkGlobalOrExternCConflict(
7705     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7706   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7707   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7708 
7709   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7710     // The common case: this global doesn't conflict with any extern "C"
7711     // declaration.
7712     return false;
7713   }
7714 
7715   if (Prev) {
7716     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7717       // Both the old and new declarations have C language linkage. This is a
7718       // redeclaration.
7719       Previous.clear();
7720       Previous.addDecl(Prev);
7721       return true;
7722     }
7723 
7724     // This is a global, non-extern "C" declaration, and there is a previous
7725     // non-global extern "C" declaration. Diagnose if this is a variable
7726     // declaration.
7727     if (!isa<VarDecl>(ND))
7728       return false;
7729   } else {
7730     // The declaration is extern "C". Check for any declaration in the
7731     // translation unit which might conflict.
7732     if (IsGlobal) {
7733       // We have already performed the lookup into the translation unit.
7734       IsGlobal = false;
7735       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7736            I != E; ++I) {
7737         if (isa<VarDecl>(*I)) {
7738           Prev = *I;
7739           break;
7740         }
7741       }
7742     } else {
7743       DeclContext::lookup_result R =
7744           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7745       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7746            I != E; ++I) {
7747         if (isa<VarDecl>(*I)) {
7748           Prev = *I;
7749           break;
7750         }
7751         // FIXME: If we have any other entity with this name in global scope,
7752         // the declaration is ill-formed, but that is a defect: it breaks the
7753         // 'stat' hack, for instance. Only variables can have mangled name
7754         // clashes with extern "C" declarations, so only they deserve a
7755         // diagnostic.
7756       }
7757     }
7758 
7759     if (!Prev)
7760       return false;
7761   }
7762 
7763   // Use the first declaration's location to ensure we point at something which
7764   // is lexically inside an extern "C" linkage-spec.
7765   assert(Prev && "should have found a previous declaration to diagnose");
7766   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7767     Prev = FD->getFirstDecl();
7768   else
7769     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7770 
7771   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7772     << IsGlobal << ND;
7773   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7774     << IsGlobal;
7775   return false;
7776 }
7777 
7778 /// Apply special rules for handling extern "C" declarations. Returns \c true
7779 /// if we have found that this is a redeclaration of some prior entity.
7780 ///
7781 /// Per C++ [dcl.link]p6:
7782 ///   Two declarations [for a function or variable] with C language linkage
7783 ///   with the same name that appear in different scopes refer to the same
7784 ///   [entity]. An entity with C language linkage shall not be declared with
7785 ///   the same name as an entity in global scope.
7786 template<typename T>
7787 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7788                                                   LookupResult &Previous) {
7789   if (!S.getLangOpts().CPlusPlus) {
7790     // In C, when declaring a global variable, look for a corresponding 'extern'
7791     // variable declared in function scope. We don't need this in C++, because
7792     // we find local extern decls in the surrounding file-scope DeclContext.
7793     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7794       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7795         Previous.clear();
7796         Previous.addDecl(Prev);
7797         return true;
7798       }
7799     }
7800     return false;
7801   }
7802 
7803   // A declaration in the translation unit can conflict with an extern "C"
7804   // declaration.
7805   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7806     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7807 
7808   // An extern "C" declaration can conflict with a declaration in the
7809   // translation unit or can be a redeclaration of an extern "C" declaration
7810   // in another scope.
7811   if (isIncompleteDeclExternC(S,ND))
7812     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7813 
7814   // Neither global nor extern "C": nothing to do.
7815   return false;
7816 }
7817 
7818 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7819   // If the decl is already known invalid, don't check it.
7820   if (NewVD->isInvalidDecl())
7821     return;
7822 
7823   QualType T = NewVD->getType();
7824 
7825   // Defer checking an 'auto' type until its initializer is attached.
7826   if (T->isUndeducedType())
7827     return;
7828 
7829   if (NewVD->hasAttrs())
7830     CheckAlignasUnderalignment(NewVD);
7831 
7832   if (T->isObjCObjectType()) {
7833     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7834       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7835     T = Context.getObjCObjectPointerType(T);
7836     NewVD->setType(T);
7837   }
7838 
7839   // Emit an error if an address space was applied to decl with local storage.
7840   // This includes arrays of objects with address space qualifiers, but not
7841   // automatic variables that point to other address spaces.
7842   // ISO/IEC TR 18037 S5.1.2
7843   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7844       T.getAddressSpace() != LangAS::Default) {
7845     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7846     NewVD->setInvalidDecl();
7847     return;
7848   }
7849 
7850   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7851   // scope.
7852   if (getLangOpts().OpenCLVersion == 120 &&
7853       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7854       NewVD->isStaticLocal()) {
7855     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7856     NewVD->setInvalidDecl();
7857     return;
7858   }
7859 
7860   if (getLangOpts().OpenCL) {
7861     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7862     if (NewVD->hasAttr<BlocksAttr>()) {
7863       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7864       return;
7865     }
7866 
7867     if (T->isBlockPointerType()) {
7868       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7869       // can't use 'extern' storage class.
7870       if (!T.isConstQualified()) {
7871         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7872             << 0 /*const*/;
7873         NewVD->setInvalidDecl();
7874         return;
7875       }
7876       if (NewVD->hasExternalStorage()) {
7877         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7878         NewVD->setInvalidDecl();
7879         return;
7880       }
7881     }
7882     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7883     // __constant address space.
7884     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7885     // variables inside a function can also be declared in the global
7886     // address space.
7887     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7888     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7889     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7890         NewVD->hasExternalStorage()) {
7891       if (!T->isSamplerT() &&
7892           !T->isDependentType() &&
7893           !(T.getAddressSpace() == LangAS::opencl_constant ||
7894             (T.getAddressSpace() == LangAS::opencl_global &&
7895              (getLangOpts().OpenCLVersion == 200 ||
7896               getLangOpts().OpenCLCPlusPlus)))) {
7897         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7898         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7899           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7900               << Scope << "global or constant";
7901         else
7902           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7903               << Scope << "constant";
7904         NewVD->setInvalidDecl();
7905         return;
7906       }
7907     } else {
7908       if (T.getAddressSpace() == LangAS::opencl_global) {
7909         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7910             << 1 /*is any function*/ << "global";
7911         NewVD->setInvalidDecl();
7912         return;
7913       }
7914       if (T.getAddressSpace() == LangAS::opencl_constant ||
7915           T.getAddressSpace() == LangAS::opencl_local) {
7916         FunctionDecl *FD = getCurFunctionDecl();
7917         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7918         // in functions.
7919         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7920           if (T.getAddressSpace() == LangAS::opencl_constant)
7921             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7922                 << 0 /*non-kernel only*/ << "constant";
7923           else
7924             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7925                 << 0 /*non-kernel only*/ << "local";
7926           NewVD->setInvalidDecl();
7927           return;
7928         }
7929         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7930         // in the outermost scope of a kernel function.
7931         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7932           if (!getCurScope()->isFunctionScope()) {
7933             if (T.getAddressSpace() == LangAS::opencl_constant)
7934               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7935                   << "constant";
7936             else
7937               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7938                   << "local";
7939             NewVD->setInvalidDecl();
7940             return;
7941           }
7942         }
7943       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7944                  // If we are parsing a template we didn't deduce an addr
7945                  // space yet.
7946                  T.getAddressSpace() != LangAS::Default) {
7947         // Do not allow other address spaces on automatic variable.
7948         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7949         NewVD->setInvalidDecl();
7950         return;
7951       }
7952     }
7953   }
7954 
7955   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7956       && !NewVD->hasAttr<BlocksAttr>()) {
7957     if (getLangOpts().getGC() != LangOptions::NonGC)
7958       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7959     else {
7960       assert(!getLangOpts().ObjCAutoRefCount);
7961       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7962     }
7963   }
7964 
7965   bool isVM = T->isVariablyModifiedType();
7966   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7967       NewVD->hasAttr<BlocksAttr>())
7968     setFunctionHasBranchProtectedScope();
7969 
7970   if ((isVM && NewVD->hasLinkage()) ||
7971       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7972     bool SizeIsNegative;
7973     llvm::APSInt Oversized;
7974     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7975         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7976     QualType FixedT;
7977     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7978       FixedT = FixedTInfo->getType();
7979     else if (FixedTInfo) {
7980       // Type and type-as-written are canonically different. We need to fix up
7981       // both types separately.
7982       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7983                                                    Oversized);
7984     }
7985     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7986       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7987       // FIXME: This won't give the correct result for
7988       // int a[10][n];
7989       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7990 
7991       if (NewVD->isFileVarDecl())
7992         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7993         << SizeRange;
7994       else if (NewVD->isStaticLocal())
7995         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7996         << SizeRange;
7997       else
7998         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7999         << SizeRange;
8000       NewVD->setInvalidDecl();
8001       return;
8002     }
8003 
8004     if (!FixedTInfo) {
8005       if (NewVD->isFileVarDecl())
8006         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8007       else
8008         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8009       NewVD->setInvalidDecl();
8010       return;
8011     }
8012 
8013     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
8014     NewVD->setType(FixedT);
8015     NewVD->setTypeSourceInfo(FixedTInfo);
8016   }
8017 
8018   if (T->isVoidType()) {
8019     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8020     //                    of objects and functions.
8021     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8022       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8023         << T;
8024       NewVD->setInvalidDecl();
8025       return;
8026     }
8027   }
8028 
8029   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8030     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8031     NewVD->setInvalidDecl();
8032     return;
8033   }
8034 
8035   if (!NewVD->hasLocalStorage() && T->isSizelessType() && !T->isVLST()) {
8036     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8037     NewVD->setInvalidDecl();
8038     return;
8039   }
8040 
8041   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8042     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8043     NewVD->setInvalidDecl();
8044     return;
8045   }
8046 
8047   if (NewVD->isConstexpr() && !T->isDependentType() &&
8048       RequireLiteralType(NewVD->getLocation(), T,
8049                          diag::err_constexpr_var_non_literal)) {
8050     NewVD->setInvalidDecl();
8051     return;
8052   }
8053 }
8054 
8055 /// Perform semantic checking on a newly-created variable
8056 /// declaration.
8057 ///
8058 /// This routine performs all of the type-checking required for a
8059 /// variable declaration once it has been built. It is used both to
8060 /// check variables after they have been parsed and their declarators
8061 /// have been translated into a declaration, and to check variables
8062 /// that have been instantiated from a template.
8063 ///
8064 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8065 ///
8066 /// Returns true if the variable declaration is a redeclaration.
8067 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8068   CheckVariableDeclarationType(NewVD);
8069 
8070   // If the decl is already known invalid, don't check it.
8071   if (NewVD->isInvalidDecl())
8072     return false;
8073 
8074   // If we did not find anything by this name, look for a non-visible
8075   // extern "C" declaration with the same name.
8076   if (Previous.empty() &&
8077       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8078     Previous.setShadowed();
8079 
8080   if (!Previous.empty()) {
8081     MergeVarDecl(NewVD, Previous);
8082     return true;
8083   }
8084   return false;
8085 }
8086 
8087 namespace {
8088 struct FindOverriddenMethod {
8089   Sema *S;
8090   CXXMethodDecl *Method;
8091 
8092   /// Member lookup function that determines whether a given C++
8093   /// method overrides a method in a base class, to be used with
8094   /// CXXRecordDecl::lookupInBases().
8095   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8096     RecordDecl *BaseRecord =
8097         Specifier->getType()->castAs<RecordType>()->getDecl();
8098 
8099     DeclarationName Name = Method->getDeclName();
8100 
8101     // FIXME: Do we care about other names here too?
8102     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8103       // We really want to find the base class destructor here.
8104       QualType T = S->Context.getTypeDeclType(BaseRecord);
8105       CanQualType CT = S->Context.getCanonicalType(T);
8106 
8107       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8108     }
8109 
8110     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8111          Path.Decls = Path.Decls.slice(1)) {
8112       NamedDecl *D = Path.Decls.front();
8113       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8114         if (MD->isVirtual() &&
8115             !S->IsOverload(
8116                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8117                 /*ConsiderCudaAttrs=*/true,
8118                 // C++2a [class.virtual]p2 does not consider requires clauses
8119                 // when overriding.
8120                 /*ConsiderRequiresClauses=*/false))
8121           return true;
8122       }
8123     }
8124 
8125     return false;
8126   }
8127 };
8128 } // end anonymous namespace
8129 
8130 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8131 /// and if so, check that it's a valid override and remember it.
8132 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8133   // Look for methods in base classes that this method might override.
8134   CXXBasePaths Paths;
8135   FindOverriddenMethod FOM;
8136   FOM.Method = MD;
8137   FOM.S = this;
8138   bool AddedAny = false;
8139   if (DC->lookupInBases(FOM, Paths)) {
8140     for (auto *I : Paths.found_decls()) {
8141       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8142         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8143         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8144             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8145             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8146             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8147           AddedAny = true;
8148         }
8149       }
8150     }
8151   }
8152 
8153   return AddedAny;
8154 }
8155 
8156 namespace {
8157   // Struct for holding all of the extra arguments needed by
8158   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8159   struct ActOnFDArgs {
8160     Scope *S;
8161     Declarator &D;
8162     MultiTemplateParamsArg TemplateParamLists;
8163     bool AddToScope;
8164   };
8165 } // end anonymous namespace
8166 
8167 namespace {
8168 
8169 // Callback to only accept typo corrections that have a non-zero edit distance.
8170 // Also only accept corrections that have the same parent decl.
8171 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8172  public:
8173   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8174                             CXXRecordDecl *Parent)
8175       : Context(Context), OriginalFD(TypoFD),
8176         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8177 
8178   bool ValidateCandidate(const TypoCorrection &candidate) override {
8179     if (candidate.getEditDistance() == 0)
8180       return false;
8181 
8182     SmallVector<unsigned, 1> MismatchedParams;
8183     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8184                                           CDeclEnd = candidate.end();
8185          CDecl != CDeclEnd; ++CDecl) {
8186       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8187 
8188       if (FD && !FD->hasBody() &&
8189           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8190         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8191           CXXRecordDecl *Parent = MD->getParent();
8192           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8193             return true;
8194         } else if (!ExpectedParent) {
8195           return true;
8196         }
8197       }
8198     }
8199 
8200     return false;
8201   }
8202 
8203   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8204     return std::make_unique<DifferentNameValidatorCCC>(*this);
8205   }
8206 
8207  private:
8208   ASTContext &Context;
8209   FunctionDecl *OriginalFD;
8210   CXXRecordDecl *ExpectedParent;
8211 };
8212 
8213 } // end anonymous namespace
8214 
8215 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8216   TypoCorrectedFunctionDefinitions.insert(F);
8217 }
8218 
8219 /// Generate diagnostics for an invalid function redeclaration.
8220 ///
8221 /// This routine handles generating the diagnostic messages for an invalid
8222 /// function redeclaration, including finding possible similar declarations
8223 /// or performing typo correction if there are no previous declarations with
8224 /// the same name.
8225 ///
8226 /// Returns a NamedDecl iff typo correction was performed and substituting in
8227 /// the new declaration name does not cause new errors.
8228 static NamedDecl *DiagnoseInvalidRedeclaration(
8229     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8230     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8231   DeclarationName Name = NewFD->getDeclName();
8232   DeclContext *NewDC = NewFD->getDeclContext();
8233   SmallVector<unsigned, 1> MismatchedParams;
8234   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8235   TypoCorrection Correction;
8236   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8237   unsigned DiagMsg =
8238     IsLocalFriend ? diag::err_no_matching_local_friend :
8239     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8240     diag::err_member_decl_does_not_match;
8241   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8242                     IsLocalFriend ? Sema::LookupLocalFriendName
8243                                   : Sema::LookupOrdinaryName,
8244                     Sema::ForVisibleRedeclaration);
8245 
8246   NewFD->setInvalidDecl();
8247   if (IsLocalFriend)
8248     SemaRef.LookupName(Prev, S);
8249   else
8250     SemaRef.LookupQualifiedName(Prev, NewDC);
8251   assert(!Prev.isAmbiguous() &&
8252          "Cannot have an ambiguity in previous-declaration lookup");
8253   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8254   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8255                                 MD ? MD->getParent() : nullptr);
8256   if (!Prev.empty()) {
8257     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8258          Func != FuncEnd; ++Func) {
8259       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8260       if (FD &&
8261           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8262         // Add 1 to the index so that 0 can mean the mismatch didn't
8263         // involve a parameter
8264         unsigned ParamNum =
8265             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8266         NearMatches.push_back(std::make_pair(FD, ParamNum));
8267       }
8268     }
8269   // If the qualified name lookup yielded nothing, try typo correction
8270   } else if ((Correction = SemaRef.CorrectTypo(
8271                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8272                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8273                   IsLocalFriend ? nullptr : NewDC))) {
8274     // Set up everything for the call to ActOnFunctionDeclarator
8275     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8276                               ExtraArgs.D.getIdentifierLoc());
8277     Previous.clear();
8278     Previous.setLookupName(Correction.getCorrection());
8279     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8280                                     CDeclEnd = Correction.end();
8281          CDecl != CDeclEnd; ++CDecl) {
8282       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8283       if (FD && !FD->hasBody() &&
8284           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8285         Previous.addDecl(FD);
8286       }
8287     }
8288     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8289 
8290     NamedDecl *Result;
8291     // Retry building the function declaration with the new previous
8292     // declarations, and with errors suppressed.
8293     {
8294       // Trap errors.
8295       Sema::SFINAETrap Trap(SemaRef);
8296 
8297       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8298       // pieces need to verify the typo-corrected C++ declaration and hopefully
8299       // eliminate the need for the parameter pack ExtraArgs.
8300       Result = SemaRef.ActOnFunctionDeclarator(
8301           ExtraArgs.S, ExtraArgs.D,
8302           Correction.getCorrectionDecl()->getDeclContext(),
8303           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8304           ExtraArgs.AddToScope);
8305 
8306       if (Trap.hasErrorOccurred())
8307         Result = nullptr;
8308     }
8309 
8310     if (Result) {
8311       // Determine which correction we picked.
8312       Decl *Canonical = Result->getCanonicalDecl();
8313       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8314            I != E; ++I)
8315         if ((*I)->getCanonicalDecl() == Canonical)
8316           Correction.setCorrectionDecl(*I);
8317 
8318       // Let Sema know about the correction.
8319       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8320       SemaRef.diagnoseTypo(
8321           Correction,
8322           SemaRef.PDiag(IsLocalFriend
8323                           ? diag::err_no_matching_local_friend_suggest
8324                           : diag::err_member_decl_does_not_match_suggest)
8325             << Name << NewDC << IsDefinition);
8326       return Result;
8327     }
8328 
8329     // Pretend the typo correction never occurred
8330     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8331                               ExtraArgs.D.getIdentifierLoc());
8332     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8333     Previous.clear();
8334     Previous.setLookupName(Name);
8335   }
8336 
8337   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8338       << Name << NewDC << IsDefinition << NewFD->getLocation();
8339 
8340   bool NewFDisConst = false;
8341   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8342     NewFDisConst = NewMD->isConst();
8343 
8344   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8345        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8346        NearMatch != NearMatchEnd; ++NearMatch) {
8347     FunctionDecl *FD = NearMatch->first;
8348     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8349     bool FDisConst = MD && MD->isConst();
8350     bool IsMember = MD || !IsLocalFriend;
8351 
8352     // FIXME: These notes are poorly worded for the local friend case.
8353     if (unsigned Idx = NearMatch->second) {
8354       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8355       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8356       if (Loc.isInvalid()) Loc = FD->getLocation();
8357       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8358                                  : diag::note_local_decl_close_param_match)
8359         << Idx << FDParam->getType()
8360         << NewFD->getParamDecl(Idx - 1)->getType();
8361     } else if (FDisConst != NewFDisConst) {
8362       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8363           << NewFDisConst << FD->getSourceRange().getEnd();
8364     } else
8365       SemaRef.Diag(FD->getLocation(),
8366                    IsMember ? diag::note_member_def_close_match
8367                             : diag::note_local_decl_close_match);
8368   }
8369   return nullptr;
8370 }
8371 
8372 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8373   switch (D.getDeclSpec().getStorageClassSpec()) {
8374   default: llvm_unreachable("Unknown storage class!");
8375   case DeclSpec::SCS_auto:
8376   case DeclSpec::SCS_register:
8377   case DeclSpec::SCS_mutable:
8378     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8379                  diag::err_typecheck_sclass_func);
8380     D.getMutableDeclSpec().ClearStorageClassSpecs();
8381     D.setInvalidType();
8382     break;
8383   case DeclSpec::SCS_unspecified: break;
8384   case DeclSpec::SCS_extern:
8385     if (D.getDeclSpec().isExternInLinkageSpec())
8386       return SC_None;
8387     return SC_Extern;
8388   case DeclSpec::SCS_static: {
8389     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8390       // C99 6.7.1p5:
8391       //   The declaration of an identifier for a function that has
8392       //   block scope shall have no explicit storage-class specifier
8393       //   other than extern
8394       // See also (C++ [dcl.stc]p4).
8395       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8396                    diag::err_static_block_func);
8397       break;
8398     } else
8399       return SC_Static;
8400   }
8401   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8402   }
8403 
8404   // No explicit storage class has already been returned
8405   return SC_None;
8406 }
8407 
8408 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8409                                            DeclContext *DC, QualType &R,
8410                                            TypeSourceInfo *TInfo,
8411                                            StorageClass SC,
8412                                            bool &IsVirtualOkay) {
8413   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8414   DeclarationName Name = NameInfo.getName();
8415 
8416   FunctionDecl *NewFD = nullptr;
8417   bool isInline = D.getDeclSpec().isInlineSpecified();
8418 
8419   if (!SemaRef.getLangOpts().CPlusPlus) {
8420     // Determine whether the function was written with a
8421     // prototype. This true when:
8422     //   - there is a prototype in the declarator, or
8423     //   - the type R of the function is some kind of typedef or other non-
8424     //     attributed reference to a type name (which eventually refers to a
8425     //     function type).
8426     bool HasPrototype =
8427       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8428       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8429 
8430     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8431                                  R, TInfo, SC, isInline, HasPrototype,
8432                                  CSK_unspecified,
8433                                  /*TrailingRequiresClause=*/nullptr);
8434     if (D.isInvalidType())
8435       NewFD->setInvalidDecl();
8436 
8437     return NewFD;
8438   }
8439 
8440   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8441 
8442   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8443   if (ConstexprKind == CSK_constinit) {
8444     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8445                  diag::err_constexpr_wrong_decl_kind)
8446         << ConstexprKind;
8447     ConstexprKind = CSK_unspecified;
8448     D.getMutableDeclSpec().ClearConstexprSpec();
8449   }
8450   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8451 
8452   // Check that the return type is not an abstract class type.
8453   // For record types, this is done by the AbstractClassUsageDiagnoser once
8454   // the class has been completely parsed.
8455   if (!DC->isRecord() &&
8456       SemaRef.RequireNonAbstractType(
8457           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8458           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8459     D.setInvalidType();
8460 
8461   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8462     // This is a C++ constructor declaration.
8463     assert(DC->isRecord() &&
8464            "Constructors can only be declared in a member context");
8465 
8466     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8467     return CXXConstructorDecl::Create(
8468         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8469         TInfo, ExplicitSpecifier, isInline,
8470         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8471         TrailingRequiresClause);
8472 
8473   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8474     // This is a C++ destructor declaration.
8475     if (DC->isRecord()) {
8476       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8477       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8478       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8479           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8480           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8481           TrailingRequiresClause);
8482 
8483       // If the destructor needs an implicit exception specification, set it
8484       // now. FIXME: It'd be nice to be able to create the right type to start
8485       // with, but the type needs to reference the destructor declaration.
8486       if (SemaRef.getLangOpts().CPlusPlus11)
8487         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8488 
8489       IsVirtualOkay = true;
8490       return NewDD;
8491 
8492     } else {
8493       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8494       D.setInvalidType();
8495 
8496       // Create a FunctionDecl to satisfy the function definition parsing
8497       // code path.
8498       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8499                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8500                                   isInline,
8501                                   /*hasPrototype=*/true, ConstexprKind,
8502                                   TrailingRequiresClause);
8503     }
8504 
8505   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8506     if (!DC->isRecord()) {
8507       SemaRef.Diag(D.getIdentifierLoc(),
8508            diag::err_conv_function_not_member);
8509       return nullptr;
8510     }
8511 
8512     SemaRef.CheckConversionDeclarator(D, R, SC);
8513     if (D.isInvalidType())
8514       return nullptr;
8515 
8516     IsVirtualOkay = true;
8517     return CXXConversionDecl::Create(
8518         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8519         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8520         TrailingRequiresClause);
8521 
8522   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8523     if (TrailingRequiresClause)
8524       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8525                    diag::err_trailing_requires_clause_on_deduction_guide)
8526           << TrailingRequiresClause->getSourceRange();
8527     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8528 
8529     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8530                                          ExplicitSpecifier, NameInfo, R, TInfo,
8531                                          D.getEndLoc());
8532   } else if (DC->isRecord()) {
8533     // If the name of the function is the same as the name of the record,
8534     // then this must be an invalid constructor that has a return type.
8535     // (The parser checks for a return type and makes the declarator a
8536     // constructor if it has no return type).
8537     if (Name.getAsIdentifierInfo() &&
8538         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8539       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8540         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8541         << SourceRange(D.getIdentifierLoc());
8542       return nullptr;
8543     }
8544 
8545     // This is a C++ method declaration.
8546     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8547         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8548         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8549         TrailingRequiresClause);
8550     IsVirtualOkay = !Ret->isStatic();
8551     return Ret;
8552   } else {
8553     bool isFriend =
8554         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8555     if (!isFriend && SemaRef.CurContext->isRecord())
8556       return nullptr;
8557 
8558     // Determine whether the function was written with a
8559     // prototype. This true when:
8560     //   - we're in C++ (where every function has a prototype),
8561     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8562                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8563                                 ConstexprKind, TrailingRequiresClause);
8564   }
8565 }
8566 
8567 enum OpenCLParamType {
8568   ValidKernelParam,
8569   PtrPtrKernelParam,
8570   PtrKernelParam,
8571   InvalidAddrSpacePtrKernelParam,
8572   InvalidKernelParam,
8573   RecordKernelParam
8574 };
8575 
8576 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8577   // Size dependent types are just typedefs to normal integer types
8578   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8579   // integers other than by their names.
8580   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8581 
8582   // Remove typedefs one by one until we reach a typedef
8583   // for a size dependent type.
8584   QualType DesugaredTy = Ty;
8585   do {
8586     ArrayRef<StringRef> Names(SizeTypeNames);
8587     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8588     if (Names.end() != Match)
8589       return true;
8590 
8591     Ty = DesugaredTy;
8592     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8593   } while (DesugaredTy != Ty);
8594 
8595   return false;
8596 }
8597 
8598 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8599   if (PT->isPointerType()) {
8600     QualType PointeeType = PT->getPointeeType();
8601     if (PointeeType->isPointerType())
8602       return PtrPtrKernelParam;
8603     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8604         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8605         PointeeType.getAddressSpace() == LangAS::Default)
8606       return InvalidAddrSpacePtrKernelParam;
8607     return PtrKernelParam;
8608   }
8609 
8610   // OpenCL v1.2 s6.9.k:
8611   // Arguments to kernel functions in a program cannot be declared with the
8612   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8613   // uintptr_t or a struct and/or union that contain fields declared to be one
8614   // of these built-in scalar types.
8615   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8616     return InvalidKernelParam;
8617 
8618   if (PT->isImageType())
8619     return PtrKernelParam;
8620 
8621   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8622     return InvalidKernelParam;
8623 
8624   // OpenCL extension spec v1.2 s9.5:
8625   // This extension adds support for half scalar and vector types as built-in
8626   // types that can be used for arithmetic operations, conversions etc.
8627   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8628     return InvalidKernelParam;
8629 
8630   if (PT->isRecordType())
8631     return RecordKernelParam;
8632 
8633   // Look into an array argument to check if it has a forbidden type.
8634   if (PT->isArrayType()) {
8635     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8636     // Call ourself to check an underlying type of an array. Since the
8637     // getPointeeOrArrayElementType returns an innermost type which is not an
8638     // array, this recursive call only happens once.
8639     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8640   }
8641 
8642   return ValidKernelParam;
8643 }
8644 
8645 static void checkIsValidOpenCLKernelParameter(
8646   Sema &S,
8647   Declarator &D,
8648   ParmVarDecl *Param,
8649   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8650   QualType PT = Param->getType();
8651 
8652   // Cache the valid types we encounter to avoid rechecking structs that are
8653   // used again
8654   if (ValidTypes.count(PT.getTypePtr()))
8655     return;
8656 
8657   switch (getOpenCLKernelParameterType(S, PT)) {
8658   case PtrPtrKernelParam:
8659     // OpenCL v1.2 s6.9.a:
8660     // A kernel function argument cannot be declared as a
8661     // pointer to a pointer type.
8662     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8663     D.setInvalidType();
8664     return;
8665 
8666   case InvalidAddrSpacePtrKernelParam:
8667     // OpenCL v1.0 s6.5:
8668     // __kernel function arguments declared to be a pointer of a type can point
8669     // to one of the following address spaces only : __global, __local or
8670     // __constant.
8671     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8672     D.setInvalidType();
8673     return;
8674 
8675     // OpenCL v1.2 s6.9.k:
8676     // Arguments to kernel functions in a program cannot be declared with the
8677     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8678     // uintptr_t or a struct and/or union that contain fields declared to be
8679     // one of these built-in scalar types.
8680 
8681   case InvalidKernelParam:
8682     // OpenCL v1.2 s6.8 n:
8683     // A kernel function argument cannot be declared
8684     // of event_t type.
8685     // Do not diagnose half type since it is diagnosed as invalid argument
8686     // type for any function elsewhere.
8687     if (!PT->isHalfType()) {
8688       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8689 
8690       // Explain what typedefs are involved.
8691       const TypedefType *Typedef = nullptr;
8692       while ((Typedef = PT->getAs<TypedefType>())) {
8693         SourceLocation Loc = Typedef->getDecl()->getLocation();
8694         // SourceLocation may be invalid for a built-in type.
8695         if (Loc.isValid())
8696           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8697         PT = Typedef->desugar();
8698       }
8699     }
8700 
8701     D.setInvalidType();
8702     return;
8703 
8704   case PtrKernelParam:
8705   case ValidKernelParam:
8706     ValidTypes.insert(PT.getTypePtr());
8707     return;
8708 
8709   case RecordKernelParam:
8710     break;
8711   }
8712 
8713   // Track nested structs we will inspect
8714   SmallVector<const Decl *, 4> VisitStack;
8715 
8716   // Track where we are in the nested structs. Items will migrate from
8717   // VisitStack to HistoryStack as we do the DFS for bad field.
8718   SmallVector<const FieldDecl *, 4> HistoryStack;
8719   HistoryStack.push_back(nullptr);
8720 
8721   // At this point we already handled everything except of a RecordType or
8722   // an ArrayType of a RecordType.
8723   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8724   const RecordType *RecTy =
8725       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8726   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8727 
8728   VisitStack.push_back(RecTy->getDecl());
8729   assert(VisitStack.back() && "First decl null?");
8730 
8731   do {
8732     const Decl *Next = VisitStack.pop_back_val();
8733     if (!Next) {
8734       assert(!HistoryStack.empty());
8735       // Found a marker, we have gone up a level
8736       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8737         ValidTypes.insert(Hist->getType().getTypePtr());
8738 
8739       continue;
8740     }
8741 
8742     // Adds everything except the original parameter declaration (which is not a
8743     // field itself) to the history stack.
8744     const RecordDecl *RD;
8745     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8746       HistoryStack.push_back(Field);
8747 
8748       QualType FieldTy = Field->getType();
8749       // Other field types (known to be valid or invalid) are handled while we
8750       // walk around RecordDecl::fields().
8751       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8752              "Unexpected type.");
8753       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8754 
8755       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8756     } else {
8757       RD = cast<RecordDecl>(Next);
8758     }
8759 
8760     // Add a null marker so we know when we've gone back up a level
8761     VisitStack.push_back(nullptr);
8762 
8763     for (const auto *FD : RD->fields()) {
8764       QualType QT = FD->getType();
8765 
8766       if (ValidTypes.count(QT.getTypePtr()))
8767         continue;
8768 
8769       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8770       if (ParamType == ValidKernelParam)
8771         continue;
8772 
8773       if (ParamType == RecordKernelParam) {
8774         VisitStack.push_back(FD);
8775         continue;
8776       }
8777 
8778       // OpenCL v1.2 s6.9.p:
8779       // Arguments to kernel functions that are declared to be a struct or union
8780       // do not allow OpenCL objects to be passed as elements of the struct or
8781       // union.
8782       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8783           ParamType == InvalidAddrSpacePtrKernelParam) {
8784         S.Diag(Param->getLocation(),
8785                diag::err_record_with_pointers_kernel_param)
8786           << PT->isUnionType()
8787           << PT;
8788       } else {
8789         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8790       }
8791 
8792       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8793           << OrigRecDecl->getDeclName();
8794 
8795       // We have an error, now let's go back up through history and show where
8796       // the offending field came from
8797       for (ArrayRef<const FieldDecl *>::const_iterator
8798                I = HistoryStack.begin() + 1,
8799                E = HistoryStack.end();
8800            I != E; ++I) {
8801         const FieldDecl *OuterField = *I;
8802         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8803           << OuterField->getType();
8804       }
8805 
8806       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8807         << QT->isPointerType()
8808         << QT;
8809       D.setInvalidType();
8810       return;
8811     }
8812   } while (!VisitStack.empty());
8813 }
8814 
8815 /// Find the DeclContext in which a tag is implicitly declared if we see an
8816 /// elaborated type specifier in the specified context, and lookup finds
8817 /// nothing.
8818 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8819   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8820     DC = DC->getParent();
8821   return DC;
8822 }
8823 
8824 /// Find the Scope in which a tag is implicitly declared if we see an
8825 /// elaborated type specifier in the specified context, and lookup finds
8826 /// nothing.
8827 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8828   while (S->isClassScope() ||
8829          (LangOpts.CPlusPlus &&
8830           S->isFunctionPrototypeScope()) ||
8831          ((S->getFlags() & Scope::DeclScope) == 0) ||
8832          (S->getEntity() && S->getEntity()->isTransparentContext()))
8833     S = S->getParent();
8834   return S;
8835 }
8836 
8837 NamedDecl*
8838 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8839                               TypeSourceInfo *TInfo, LookupResult &Previous,
8840                               MultiTemplateParamsArg TemplateParamListsRef,
8841                               bool &AddToScope) {
8842   QualType R = TInfo->getType();
8843 
8844   assert(R->isFunctionType());
8845   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8846     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8847 
8848   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8849   for (TemplateParameterList *TPL : TemplateParamListsRef)
8850     TemplateParamLists.push_back(TPL);
8851   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8852     if (!TemplateParamLists.empty() &&
8853         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8854       TemplateParamLists.back() = Invented;
8855     else
8856       TemplateParamLists.push_back(Invented);
8857   }
8858 
8859   // TODO: consider using NameInfo for diagnostic.
8860   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8861   DeclarationName Name = NameInfo.getName();
8862   StorageClass SC = getFunctionStorageClass(*this, D);
8863 
8864   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8865     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8866          diag::err_invalid_thread)
8867       << DeclSpec::getSpecifierName(TSCS);
8868 
8869   if (D.isFirstDeclarationOfMember())
8870     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8871                            D.getIdentifierLoc());
8872 
8873   bool isFriend = false;
8874   FunctionTemplateDecl *FunctionTemplate = nullptr;
8875   bool isMemberSpecialization = false;
8876   bool isFunctionTemplateSpecialization = false;
8877 
8878   bool isDependentClassScopeExplicitSpecialization = false;
8879   bool HasExplicitTemplateArgs = false;
8880   TemplateArgumentListInfo TemplateArgs;
8881 
8882   bool isVirtualOkay = false;
8883 
8884   DeclContext *OriginalDC = DC;
8885   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8886 
8887   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8888                                               isVirtualOkay);
8889   if (!NewFD) return nullptr;
8890 
8891   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8892     NewFD->setTopLevelDeclInObjCContainer();
8893 
8894   // Set the lexical context. If this is a function-scope declaration, or has a
8895   // C++ scope specifier, or is the object of a friend declaration, the lexical
8896   // context will be different from the semantic context.
8897   NewFD->setLexicalDeclContext(CurContext);
8898 
8899   if (IsLocalExternDecl)
8900     NewFD->setLocalExternDecl();
8901 
8902   if (getLangOpts().CPlusPlus) {
8903     bool isInline = D.getDeclSpec().isInlineSpecified();
8904     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8905     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8906     isFriend = D.getDeclSpec().isFriendSpecified();
8907     if (isFriend && !isInline && D.isFunctionDefinition()) {
8908       // C++ [class.friend]p5
8909       //   A function can be defined in a friend declaration of a
8910       //   class . . . . Such a function is implicitly inline.
8911       NewFD->setImplicitlyInline();
8912     }
8913 
8914     // If this is a method defined in an __interface, and is not a constructor
8915     // or an overloaded operator, then set the pure flag (isVirtual will already
8916     // return true).
8917     if (const CXXRecordDecl *Parent =
8918           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8919       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8920         NewFD->setPure(true);
8921 
8922       // C++ [class.union]p2
8923       //   A union can have member functions, but not virtual functions.
8924       if (isVirtual && Parent->isUnion())
8925         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8926     }
8927 
8928     SetNestedNameSpecifier(*this, NewFD, D);
8929     isMemberSpecialization = false;
8930     isFunctionTemplateSpecialization = false;
8931     if (D.isInvalidType())
8932       NewFD->setInvalidDecl();
8933 
8934     // Match up the template parameter lists with the scope specifier, then
8935     // determine whether we have a template or a template specialization.
8936     bool Invalid = false;
8937     TemplateParameterList *TemplateParams =
8938         MatchTemplateParametersToScopeSpecifier(
8939             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8940             D.getCXXScopeSpec(),
8941             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8942                 ? D.getName().TemplateId
8943                 : nullptr,
8944             TemplateParamLists, isFriend, isMemberSpecialization,
8945             Invalid);
8946     if (TemplateParams) {
8947       // Check that we can declare a template here.
8948       if (CheckTemplateDeclScope(S, TemplateParams))
8949         NewFD->setInvalidDecl();
8950 
8951       if (TemplateParams->size() > 0) {
8952         // This is a function template
8953 
8954         // A destructor cannot be a template.
8955         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8956           Diag(NewFD->getLocation(), diag::err_destructor_template);
8957           NewFD->setInvalidDecl();
8958         }
8959 
8960         // If we're adding a template to a dependent context, we may need to
8961         // rebuilding some of the types used within the template parameter list,
8962         // now that we know what the current instantiation is.
8963         if (DC->isDependentContext()) {
8964           ContextRAII SavedContext(*this, DC);
8965           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8966             Invalid = true;
8967         }
8968 
8969         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8970                                                         NewFD->getLocation(),
8971                                                         Name, TemplateParams,
8972                                                         NewFD);
8973         FunctionTemplate->setLexicalDeclContext(CurContext);
8974         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8975 
8976         // For source fidelity, store the other template param lists.
8977         if (TemplateParamLists.size() > 1) {
8978           NewFD->setTemplateParameterListsInfo(Context,
8979               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8980                   .drop_back(1));
8981         }
8982       } else {
8983         // This is a function template specialization.
8984         isFunctionTemplateSpecialization = true;
8985         // For source fidelity, store all the template param lists.
8986         if (TemplateParamLists.size() > 0)
8987           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8988 
8989         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8990         if (isFriend) {
8991           // We want to remove the "template<>", found here.
8992           SourceRange RemoveRange = TemplateParams->getSourceRange();
8993 
8994           // If we remove the template<> and the name is not a
8995           // template-id, we're actually silently creating a problem:
8996           // the friend declaration will refer to an untemplated decl,
8997           // and clearly the user wants a template specialization.  So
8998           // we need to insert '<>' after the name.
8999           SourceLocation InsertLoc;
9000           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9001             InsertLoc = D.getName().getSourceRange().getEnd();
9002             InsertLoc = getLocForEndOfToken(InsertLoc);
9003           }
9004 
9005           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9006             << Name << RemoveRange
9007             << FixItHint::CreateRemoval(RemoveRange)
9008             << FixItHint::CreateInsertion(InsertLoc, "<>");
9009         }
9010       }
9011     } else {
9012       // Check that we can declare a template here.
9013       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9014           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9015         NewFD->setInvalidDecl();
9016 
9017       // All template param lists were matched against the scope specifier:
9018       // this is NOT (an explicit specialization of) a template.
9019       if (TemplateParamLists.size() > 0)
9020         // For source fidelity, store all the template param lists.
9021         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9022     }
9023 
9024     if (Invalid) {
9025       NewFD->setInvalidDecl();
9026       if (FunctionTemplate)
9027         FunctionTemplate->setInvalidDecl();
9028     }
9029 
9030     // C++ [dcl.fct.spec]p5:
9031     //   The virtual specifier shall only be used in declarations of
9032     //   nonstatic class member functions that appear within a
9033     //   member-specification of a class declaration; see 10.3.
9034     //
9035     if (isVirtual && !NewFD->isInvalidDecl()) {
9036       if (!isVirtualOkay) {
9037         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9038              diag::err_virtual_non_function);
9039       } else if (!CurContext->isRecord()) {
9040         // 'virtual' was specified outside of the class.
9041         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9042              diag::err_virtual_out_of_class)
9043           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9044       } else if (NewFD->getDescribedFunctionTemplate()) {
9045         // C++ [temp.mem]p3:
9046         //  A member function template shall not be virtual.
9047         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9048              diag::err_virtual_member_function_template)
9049           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9050       } else {
9051         // Okay: Add virtual to the method.
9052         NewFD->setVirtualAsWritten(true);
9053       }
9054 
9055       if (getLangOpts().CPlusPlus14 &&
9056           NewFD->getReturnType()->isUndeducedType())
9057         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9058     }
9059 
9060     if (getLangOpts().CPlusPlus14 &&
9061         (NewFD->isDependentContext() ||
9062          (isFriend && CurContext->isDependentContext())) &&
9063         NewFD->getReturnType()->isUndeducedType()) {
9064       // If the function template is referenced directly (for instance, as a
9065       // member of the current instantiation), pretend it has a dependent type.
9066       // This is not really justified by the standard, but is the only sane
9067       // thing to do.
9068       // FIXME: For a friend function, we have not marked the function as being
9069       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9070       const FunctionProtoType *FPT =
9071           NewFD->getType()->castAs<FunctionProtoType>();
9072       QualType Result =
9073           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9074       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9075                                              FPT->getExtProtoInfo()));
9076     }
9077 
9078     // C++ [dcl.fct.spec]p3:
9079     //  The inline specifier shall not appear on a block scope function
9080     //  declaration.
9081     if (isInline && !NewFD->isInvalidDecl()) {
9082       if (CurContext->isFunctionOrMethod()) {
9083         // 'inline' is not allowed on block scope function declaration.
9084         Diag(D.getDeclSpec().getInlineSpecLoc(),
9085              diag::err_inline_declaration_block_scope) << Name
9086           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9087       }
9088     }
9089 
9090     // C++ [dcl.fct.spec]p6:
9091     //  The explicit specifier shall be used only in the declaration of a
9092     //  constructor or conversion function within its class definition;
9093     //  see 12.3.1 and 12.3.2.
9094     if (hasExplicit && !NewFD->isInvalidDecl() &&
9095         !isa<CXXDeductionGuideDecl>(NewFD)) {
9096       if (!CurContext->isRecord()) {
9097         // 'explicit' was specified outside of the class.
9098         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9099              diag::err_explicit_out_of_class)
9100             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9101       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9102                  !isa<CXXConversionDecl>(NewFD)) {
9103         // 'explicit' was specified on a function that wasn't a constructor
9104         // or conversion function.
9105         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9106              diag::err_explicit_non_ctor_or_conv_function)
9107             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9108       }
9109     }
9110 
9111     if (ConstexprSpecKind ConstexprKind =
9112             D.getDeclSpec().getConstexprSpecifier()) {
9113       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9114       // are implicitly inline.
9115       NewFD->setImplicitlyInline();
9116 
9117       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9118       // be either constructors or to return a literal type. Therefore,
9119       // destructors cannot be declared constexpr.
9120       if (isa<CXXDestructorDecl>(NewFD) &&
9121           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9122         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9123             << ConstexprKind;
9124         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9125       }
9126       // C++20 [dcl.constexpr]p2: An allocation function, or a
9127       // deallocation function shall not be declared with the consteval
9128       // specifier.
9129       if (ConstexprKind == CSK_consteval &&
9130           (NewFD->getOverloadedOperator() == OO_New ||
9131            NewFD->getOverloadedOperator() == OO_Array_New ||
9132            NewFD->getOverloadedOperator() == OO_Delete ||
9133            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9134         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9135              diag::err_invalid_consteval_decl_kind)
9136             << NewFD;
9137         NewFD->setConstexprKind(CSK_constexpr);
9138       }
9139     }
9140 
9141     // If __module_private__ was specified, mark the function accordingly.
9142     if (D.getDeclSpec().isModulePrivateSpecified()) {
9143       if (isFunctionTemplateSpecialization) {
9144         SourceLocation ModulePrivateLoc
9145           = D.getDeclSpec().getModulePrivateSpecLoc();
9146         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9147           << 0
9148           << FixItHint::CreateRemoval(ModulePrivateLoc);
9149       } else {
9150         NewFD->setModulePrivate();
9151         if (FunctionTemplate)
9152           FunctionTemplate->setModulePrivate();
9153       }
9154     }
9155 
9156     if (isFriend) {
9157       if (FunctionTemplate) {
9158         FunctionTemplate->setObjectOfFriendDecl();
9159         FunctionTemplate->setAccess(AS_public);
9160       }
9161       NewFD->setObjectOfFriendDecl();
9162       NewFD->setAccess(AS_public);
9163     }
9164 
9165     // If a function is defined as defaulted or deleted, mark it as such now.
9166     // We'll do the relevant checks on defaulted / deleted functions later.
9167     switch (D.getFunctionDefinitionKind()) {
9168       case FDK_Declaration:
9169       case FDK_Definition:
9170         break;
9171 
9172       case FDK_Defaulted:
9173         NewFD->setDefaulted();
9174         break;
9175 
9176       case FDK_Deleted:
9177         NewFD->setDeletedAsWritten();
9178         break;
9179     }
9180 
9181     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9182         D.isFunctionDefinition()) {
9183       // C++ [class.mfct]p2:
9184       //   A member function may be defined (8.4) in its class definition, in
9185       //   which case it is an inline member function (7.1.2)
9186       NewFD->setImplicitlyInline();
9187     }
9188 
9189     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9190         !CurContext->isRecord()) {
9191       // C++ [class.static]p1:
9192       //   A data or function member of a class may be declared static
9193       //   in a class definition, in which case it is a static member of
9194       //   the class.
9195 
9196       // Complain about the 'static' specifier if it's on an out-of-line
9197       // member function definition.
9198 
9199       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9200       // member function template declaration and class member template
9201       // declaration (MSVC versions before 2015), warn about this.
9202       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9203            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9204              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9205            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9206            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9207         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9208     }
9209 
9210     // C++11 [except.spec]p15:
9211     //   A deallocation function with no exception-specification is treated
9212     //   as if it were specified with noexcept(true).
9213     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9214     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9215          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9216         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9217       NewFD->setType(Context.getFunctionType(
9218           FPT->getReturnType(), FPT->getParamTypes(),
9219           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9220   }
9221 
9222   // Filter out previous declarations that don't match the scope.
9223   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9224                        D.getCXXScopeSpec().isNotEmpty() ||
9225                        isMemberSpecialization ||
9226                        isFunctionTemplateSpecialization);
9227 
9228   // Handle GNU asm-label extension (encoded as an attribute).
9229   if (Expr *E = (Expr*) D.getAsmLabel()) {
9230     // The parser guarantees this is a string.
9231     StringLiteral *SE = cast<StringLiteral>(E);
9232     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9233                                         /*IsLiteralLabel=*/true,
9234                                         SE->getStrTokenLoc(0)));
9235   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9236     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9237       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9238     if (I != ExtnameUndeclaredIdentifiers.end()) {
9239       if (isDeclExternC(NewFD)) {
9240         NewFD->addAttr(I->second);
9241         ExtnameUndeclaredIdentifiers.erase(I);
9242       } else
9243         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9244             << /*Variable*/0 << NewFD;
9245     }
9246   }
9247 
9248   // Copy the parameter declarations from the declarator D to the function
9249   // declaration NewFD, if they are available.  First scavenge them into Params.
9250   SmallVector<ParmVarDecl*, 16> Params;
9251   unsigned FTIIdx;
9252   if (D.isFunctionDeclarator(FTIIdx)) {
9253     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9254 
9255     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9256     // function that takes no arguments, not a function that takes a
9257     // single void argument.
9258     // We let through "const void" here because Sema::GetTypeForDeclarator
9259     // already checks for that case.
9260     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9261       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9262         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9263         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9264         Param->setDeclContext(NewFD);
9265         Params.push_back(Param);
9266 
9267         if (Param->isInvalidDecl())
9268           NewFD->setInvalidDecl();
9269       }
9270     }
9271 
9272     if (!getLangOpts().CPlusPlus) {
9273       // In C, find all the tag declarations from the prototype and move them
9274       // into the function DeclContext. Remove them from the surrounding tag
9275       // injection context of the function, which is typically but not always
9276       // the TU.
9277       DeclContext *PrototypeTagContext =
9278           getTagInjectionContext(NewFD->getLexicalDeclContext());
9279       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9280         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9281 
9282         // We don't want to reparent enumerators. Look at their parent enum
9283         // instead.
9284         if (!TD) {
9285           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9286             TD = cast<EnumDecl>(ECD->getDeclContext());
9287         }
9288         if (!TD)
9289           continue;
9290         DeclContext *TagDC = TD->getLexicalDeclContext();
9291         if (!TagDC->containsDecl(TD))
9292           continue;
9293         TagDC->removeDecl(TD);
9294         TD->setDeclContext(NewFD);
9295         NewFD->addDecl(TD);
9296 
9297         // Preserve the lexical DeclContext if it is not the surrounding tag
9298         // injection context of the FD. In this example, the semantic context of
9299         // E will be f and the lexical context will be S, while both the
9300         // semantic and lexical contexts of S will be f:
9301         //   void f(struct S { enum E { a } f; } s);
9302         if (TagDC != PrototypeTagContext)
9303           TD->setLexicalDeclContext(TagDC);
9304       }
9305     }
9306   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9307     // When we're declaring a function with a typedef, typeof, etc as in the
9308     // following example, we'll need to synthesize (unnamed)
9309     // parameters for use in the declaration.
9310     //
9311     // @code
9312     // typedef void fn(int);
9313     // fn f;
9314     // @endcode
9315 
9316     // Synthesize a parameter for each argument type.
9317     for (const auto &AI : FT->param_types()) {
9318       ParmVarDecl *Param =
9319           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9320       Param->setScopeInfo(0, Params.size());
9321       Params.push_back(Param);
9322     }
9323   } else {
9324     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9325            "Should not need args for typedef of non-prototype fn");
9326   }
9327 
9328   // Finally, we know we have the right number of parameters, install them.
9329   NewFD->setParams(Params);
9330 
9331   if (D.getDeclSpec().isNoreturnSpecified())
9332     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9333                                            D.getDeclSpec().getNoreturnSpecLoc(),
9334                                            AttributeCommonInfo::AS_Keyword));
9335 
9336   // Functions returning a variably modified type violate C99 6.7.5.2p2
9337   // because all functions have linkage.
9338   if (!NewFD->isInvalidDecl() &&
9339       NewFD->getReturnType()->isVariablyModifiedType()) {
9340     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9341     NewFD->setInvalidDecl();
9342   }
9343 
9344   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9345   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9346       !NewFD->hasAttr<SectionAttr>())
9347     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9348         Context, PragmaClangTextSection.SectionName,
9349         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9350 
9351   // Apply an implicit SectionAttr if #pragma code_seg is active.
9352   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9353       !NewFD->hasAttr<SectionAttr>()) {
9354     NewFD->addAttr(SectionAttr::CreateImplicit(
9355         Context, CodeSegStack.CurrentValue->getString(),
9356         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9357         SectionAttr::Declspec_allocate));
9358     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9359                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9360                          ASTContext::PSF_Read,
9361                      NewFD))
9362       NewFD->dropAttr<SectionAttr>();
9363   }
9364 
9365   // Apply an implicit CodeSegAttr from class declspec or
9366   // apply an implicit SectionAttr from #pragma code_seg if active.
9367   if (!NewFD->hasAttr<CodeSegAttr>()) {
9368     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9369                                                                  D.isFunctionDefinition())) {
9370       NewFD->addAttr(SAttr);
9371     }
9372   }
9373 
9374   // Handle attributes.
9375   ProcessDeclAttributes(S, NewFD, D);
9376 
9377   if (getLangOpts().OpenCL) {
9378     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9379     // type declaration will generate a compilation error.
9380     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9381     if (AddressSpace != LangAS::Default) {
9382       Diag(NewFD->getLocation(),
9383            diag::err_opencl_return_value_with_address_space);
9384       NewFD->setInvalidDecl();
9385     }
9386   }
9387 
9388   if (!getLangOpts().CPlusPlus) {
9389     // Perform semantic checking on the function declaration.
9390     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9391       CheckMain(NewFD, D.getDeclSpec());
9392 
9393     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9394       CheckMSVCRTEntryPoint(NewFD);
9395 
9396     if (!NewFD->isInvalidDecl())
9397       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9398                                                   isMemberSpecialization));
9399     else if (!Previous.empty())
9400       // Recover gracefully from an invalid redeclaration.
9401       D.setRedeclaration(true);
9402     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9403             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9404            "previous declaration set still overloaded");
9405 
9406     // Diagnose no-prototype function declarations with calling conventions that
9407     // don't support variadic calls. Only do this in C and do it after merging
9408     // possibly prototyped redeclarations.
9409     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9410     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9411       CallingConv CC = FT->getExtInfo().getCC();
9412       if (!supportsVariadicCall(CC)) {
9413         // Windows system headers sometimes accidentally use stdcall without
9414         // (void) parameters, so we relax this to a warning.
9415         int DiagID =
9416             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9417         Diag(NewFD->getLocation(), DiagID)
9418             << FunctionType::getNameForCallConv(CC);
9419       }
9420     }
9421 
9422    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9423        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9424      checkNonTrivialCUnion(NewFD->getReturnType(),
9425                            NewFD->getReturnTypeSourceRange().getBegin(),
9426                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9427   } else {
9428     // C++11 [replacement.functions]p3:
9429     //  The program's definitions shall not be specified as inline.
9430     //
9431     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9432     //
9433     // Suppress the diagnostic if the function is __attribute__((used)), since
9434     // that forces an external definition to be emitted.
9435     if (D.getDeclSpec().isInlineSpecified() &&
9436         NewFD->isReplaceableGlobalAllocationFunction() &&
9437         !NewFD->hasAttr<UsedAttr>())
9438       Diag(D.getDeclSpec().getInlineSpecLoc(),
9439            diag::ext_operator_new_delete_declared_inline)
9440         << NewFD->getDeclName();
9441 
9442     // If the declarator is a template-id, translate the parser's template
9443     // argument list into our AST format.
9444     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9445       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9446       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9447       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9448       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9449                                          TemplateId->NumArgs);
9450       translateTemplateArguments(TemplateArgsPtr,
9451                                  TemplateArgs);
9452 
9453       HasExplicitTemplateArgs = true;
9454 
9455       if (NewFD->isInvalidDecl()) {
9456         HasExplicitTemplateArgs = false;
9457       } else if (FunctionTemplate) {
9458         // Function template with explicit template arguments.
9459         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9460           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9461 
9462         HasExplicitTemplateArgs = false;
9463       } else {
9464         assert((isFunctionTemplateSpecialization ||
9465                 D.getDeclSpec().isFriendSpecified()) &&
9466                "should have a 'template<>' for this decl");
9467         // "friend void foo<>(int);" is an implicit specialization decl.
9468         isFunctionTemplateSpecialization = true;
9469       }
9470     } else if (isFriend && isFunctionTemplateSpecialization) {
9471       // This combination is only possible in a recovery case;  the user
9472       // wrote something like:
9473       //   template <> friend void foo(int);
9474       // which we're recovering from as if the user had written:
9475       //   friend void foo<>(int);
9476       // Go ahead and fake up a template id.
9477       HasExplicitTemplateArgs = true;
9478       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9479       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9480     }
9481 
9482     // We do not add HD attributes to specializations here because
9483     // they may have different constexpr-ness compared to their
9484     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9485     // may end up with different effective targets. Instead, a
9486     // specialization inherits its target attributes from its template
9487     // in the CheckFunctionTemplateSpecialization() call below.
9488     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9489       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9490 
9491     // If it's a friend (and only if it's a friend), it's possible
9492     // that either the specialized function type or the specialized
9493     // template is dependent, and therefore matching will fail.  In
9494     // this case, don't check the specialization yet.
9495     bool InstantiationDependent = false;
9496     if (isFunctionTemplateSpecialization && isFriend &&
9497         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9498          TemplateSpecializationType::anyDependentTemplateArguments(
9499             TemplateArgs,
9500             InstantiationDependent))) {
9501       assert(HasExplicitTemplateArgs &&
9502              "friend function specialization without template args");
9503       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9504                                                        Previous))
9505         NewFD->setInvalidDecl();
9506     } else if (isFunctionTemplateSpecialization) {
9507       if (CurContext->isDependentContext() && CurContext->isRecord()
9508           && !isFriend) {
9509         isDependentClassScopeExplicitSpecialization = true;
9510       } else if (!NewFD->isInvalidDecl() &&
9511                  CheckFunctionTemplateSpecialization(
9512                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9513                      Previous))
9514         NewFD->setInvalidDecl();
9515 
9516       // C++ [dcl.stc]p1:
9517       //   A storage-class-specifier shall not be specified in an explicit
9518       //   specialization (14.7.3)
9519       FunctionTemplateSpecializationInfo *Info =
9520           NewFD->getTemplateSpecializationInfo();
9521       if (Info && SC != SC_None) {
9522         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9523           Diag(NewFD->getLocation(),
9524                diag::err_explicit_specialization_inconsistent_storage_class)
9525             << SC
9526             << FixItHint::CreateRemoval(
9527                                       D.getDeclSpec().getStorageClassSpecLoc());
9528 
9529         else
9530           Diag(NewFD->getLocation(),
9531                diag::ext_explicit_specialization_storage_class)
9532             << FixItHint::CreateRemoval(
9533                                       D.getDeclSpec().getStorageClassSpecLoc());
9534       }
9535     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9536       if (CheckMemberSpecialization(NewFD, Previous))
9537           NewFD->setInvalidDecl();
9538     }
9539 
9540     // Perform semantic checking on the function declaration.
9541     if (!isDependentClassScopeExplicitSpecialization) {
9542       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9543         CheckMain(NewFD, D.getDeclSpec());
9544 
9545       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9546         CheckMSVCRTEntryPoint(NewFD);
9547 
9548       if (!NewFD->isInvalidDecl())
9549         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9550                                                     isMemberSpecialization));
9551       else if (!Previous.empty())
9552         // Recover gracefully from an invalid redeclaration.
9553         D.setRedeclaration(true);
9554     }
9555 
9556     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9557             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9558            "previous declaration set still overloaded");
9559 
9560     NamedDecl *PrincipalDecl = (FunctionTemplate
9561                                 ? cast<NamedDecl>(FunctionTemplate)
9562                                 : NewFD);
9563 
9564     if (isFriend && NewFD->getPreviousDecl()) {
9565       AccessSpecifier Access = AS_public;
9566       if (!NewFD->isInvalidDecl())
9567         Access = NewFD->getPreviousDecl()->getAccess();
9568 
9569       NewFD->setAccess(Access);
9570       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9571     }
9572 
9573     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9574         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9575       PrincipalDecl->setNonMemberOperator();
9576 
9577     // If we have a function template, check the template parameter
9578     // list. This will check and merge default template arguments.
9579     if (FunctionTemplate) {
9580       FunctionTemplateDecl *PrevTemplate =
9581                                      FunctionTemplate->getPreviousDecl();
9582       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9583                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9584                                     : nullptr,
9585                             D.getDeclSpec().isFriendSpecified()
9586                               ? (D.isFunctionDefinition()
9587                                    ? TPC_FriendFunctionTemplateDefinition
9588                                    : TPC_FriendFunctionTemplate)
9589                               : (D.getCXXScopeSpec().isSet() &&
9590                                  DC && DC->isRecord() &&
9591                                  DC->isDependentContext())
9592                                   ? TPC_ClassTemplateMember
9593                                   : TPC_FunctionTemplate);
9594     }
9595 
9596     if (NewFD->isInvalidDecl()) {
9597       // Ignore all the rest of this.
9598     } else if (!D.isRedeclaration()) {
9599       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9600                                        AddToScope };
9601       // Fake up an access specifier if it's supposed to be a class member.
9602       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9603         NewFD->setAccess(AS_public);
9604 
9605       // Qualified decls generally require a previous declaration.
9606       if (D.getCXXScopeSpec().isSet()) {
9607         // ...with the major exception of templated-scope or
9608         // dependent-scope friend declarations.
9609 
9610         // TODO: we currently also suppress this check in dependent
9611         // contexts because (1) the parameter depth will be off when
9612         // matching friend templates and (2) we might actually be
9613         // selecting a friend based on a dependent factor.  But there
9614         // are situations where these conditions don't apply and we
9615         // can actually do this check immediately.
9616         //
9617         // Unless the scope is dependent, it's always an error if qualified
9618         // redeclaration lookup found nothing at all. Diagnose that now;
9619         // nothing will diagnose that error later.
9620         if (isFriend &&
9621             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9622              (!Previous.empty() && CurContext->isDependentContext()))) {
9623           // ignore these
9624         } else {
9625           // The user tried to provide an out-of-line definition for a
9626           // function that is a member of a class or namespace, but there
9627           // was no such member function declared (C++ [class.mfct]p2,
9628           // C++ [namespace.memdef]p2). For example:
9629           //
9630           // class X {
9631           //   void f() const;
9632           // };
9633           //
9634           // void X::f() { } // ill-formed
9635           //
9636           // Complain about this problem, and attempt to suggest close
9637           // matches (e.g., those that differ only in cv-qualifiers and
9638           // whether the parameter types are references).
9639 
9640           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9641                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9642             AddToScope = ExtraArgs.AddToScope;
9643             return Result;
9644           }
9645         }
9646 
9647         // Unqualified local friend declarations are required to resolve
9648         // to something.
9649       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9650         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9651                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9652           AddToScope = ExtraArgs.AddToScope;
9653           return Result;
9654         }
9655       }
9656     } else if (!D.isFunctionDefinition() &&
9657                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9658                !isFriend && !isFunctionTemplateSpecialization &&
9659                !isMemberSpecialization) {
9660       // An out-of-line member function declaration must also be a
9661       // definition (C++ [class.mfct]p2).
9662       // Note that this is not the case for explicit specializations of
9663       // function templates or member functions of class templates, per
9664       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9665       // extension for compatibility with old SWIG code which likes to
9666       // generate them.
9667       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9668         << D.getCXXScopeSpec().getRange();
9669     }
9670   }
9671 
9672   ProcessPragmaWeak(S, NewFD);
9673   checkAttributesAfterMerging(*this, *NewFD);
9674 
9675   AddKnownFunctionAttributes(NewFD);
9676 
9677   if (NewFD->hasAttr<OverloadableAttr>() &&
9678       !NewFD->getType()->getAs<FunctionProtoType>()) {
9679     Diag(NewFD->getLocation(),
9680          diag::err_attribute_overloadable_no_prototype)
9681       << NewFD;
9682 
9683     // Turn this into a variadic function with no parameters.
9684     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9685     FunctionProtoType::ExtProtoInfo EPI(
9686         Context.getDefaultCallingConvention(true, false));
9687     EPI.Variadic = true;
9688     EPI.ExtInfo = FT->getExtInfo();
9689 
9690     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9691     NewFD->setType(R);
9692   }
9693 
9694   // If there's a #pragma GCC visibility in scope, and this isn't a class
9695   // member, set the visibility of this function.
9696   if (!DC->isRecord() && NewFD->isExternallyVisible())
9697     AddPushedVisibilityAttribute(NewFD);
9698 
9699   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9700   // marking the function.
9701   AddCFAuditedAttribute(NewFD);
9702 
9703   // If this is a function definition, check if we have to apply optnone due to
9704   // a pragma.
9705   if(D.isFunctionDefinition())
9706     AddRangeBasedOptnone(NewFD);
9707 
9708   // If this is the first declaration of an extern C variable, update
9709   // the map of such variables.
9710   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9711       isIncompleteDeclExternC(*this, NewFD))
9712     RegisterLocallyScopedExternCDecl(NewFD, S);
9713 
9714   // Set this FunctionDecl's range up to the right paren.
9715   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9716 
9717   if (D.isRedeclaration() && !Previous.empty()) {
9718     NamedDecl *Prev = Previous.getRepresentativeDecl();
9719     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9720                                    isMemberSpecialization ||
9721                                        isFunctionTemplateSpecialization,
9722                                    D.isFunctionDefinition());
9723   }
9724 
9725   if (getLangOpts().CUDA) {
9726     IdentifierInfo *II = NewFD->getIdentifier();
9727     if (II && II->isStr(getCudaConfigureFuncName()) &&
9728         !NewFD->isInvalidDecl() &&
9729         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9730       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9731         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9732             << getCudaConfigureFuncName();
9733       Context.setcudaConfigureCallDecl(NewFD);
9734     }
9735 
9736     // Variadic functions, other than a *declaration* of printf, are not allowed
9737     // in device-side CUDA code, unless someone passed
9738     // -fcuda-allow-variadic-functions.
9739     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9740         (NewFD->hasAttr<CUDADeviceAttr>() ||
9741          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9742         !(II && II->isStr("printf") && NewFD->isExternC() &&
9743           !D.isFunctionDefinition())) {
9744       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9745     }
9746   }
9747 
9748   MarkUnusedFileScopedDecl(NewFD);
9749 
9750 
9751 
9752   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9753     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9754     if ((getLangOpts().OpenCLVersion >= 120)
9755         && (SC == SC_Static)) {
9756       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9757       D.setInvalidType();
9758     }
9759 
9760     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9761     if (!NewFD->getReturnType()->isVoidType()) {
9762       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9763       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9764           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9765                                 : FixItHint());
9766       D.setInvalidType();
9767     }
9768 
9769     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9770     for (auto Param : NewFD->parameters())
9771       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9772 
9773     if (getLangOpts().OpenCLCPlusPlus) {
9774       if (DC->isRecord()) {
9775         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9776         D.setInvalidType();
9777       }
9778       if (FunctionTemplate) {
9779         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9780         D.setInvalidType();
9781       }
9782     }
9783   }
9784 
9785   if (getLangOpts().CPlusPlus) {
9786     if (FunctionTemplate) {
9787       if (NewFD->isInvalidDecl())
9788         FunctionTemplate->setInvalidDecl();
9789       return FunctionTemplate;
9790     }
9791 
9792     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9793       CompleteMemberSpecialization(NewFD, Previous);
9794   }
9795 
9796   for (const ParmVarDecl *Param : NewFD->parameters()) {
9797     QualType PT = Param->getType();
9798 
9799     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9800     // types.
9801     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9802       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9803         QualType ElemTy = PipeTy->getElementType();
9804           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9805             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9806             D.setInvalidType();
9807           }
9808       }
9809     }
9810   }
9811 
9812   // Here we have an function template explicit specialization at class scope.
9813   // The actual specialization will be postponed to template instatiation
9814   // time via the ClassScopeFunctionSpecializationDecl node.
9815   if (isDependentClassScopeExplicitSpecialization) {
9816     ClassScopeFunctionSpecializationDecl *NewSpec =
9817                          ClassScopeFunctionSpecializationDecl::Create(
9818                                 Context, CurContext, NewFD->getLocation(),
9819                                 cast<CXXMethodDecl>(NewFD),
9820                                 HasExplicitTemplateArgs, TemplateArgs);
9821     CurContext->addDecl(NewSpec);
9822     AddToScope = false;
9823   }
9824 
9825   // Diagnose availability attributes. Availability cannot be used on functions
9826   // that are run during load/unload.
9827   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9828     if (NewFD->hasAttr<ConstructorAttr>()) {
9829       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9830           << 1;
9831       NewFD->dropAttr<AvailabilityAttr>();
9832     }
9833     if (NewFD->hasAttr<DestructorAttr>()) {
9834       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9835           << 2;
9836       NewFD->dropAttr<AvailabilityAttr>();
9837     }
9838   }
9839 
9840   // Diagnose no_builtin attribute on function declaration that are not a
9841   // definition.
9842   // FIXME: We should really be doing this in
9843   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9844   // the FunctionDecl and at this point of the code
9845   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9846   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9847   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9848     switch (D.getFunctionDefinitionKind()) {
9849     case FDK_Defaulted:
9850     case FDK_Deleted:
9851       Diag(NBA->getLocation(),
9852            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9853           << NBA->getSpelling();
9854       break;
9855     case FDK_Declaration:
9856       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9857           << NBA->getSpelling();
9858       break;
9859     case FDK_Definition:
9860       break;
9861     }
9862 
9863   return NewFD;
9864 }
9865 
9866 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9867 /// when __declspec(code_seg) "is applied to a class, all member functions of
9868 /// the class and nested classes -- this includes compiler-generated special
9869 /// member functions -- are put in the specified segment."
9870 /// The actual behavior is a little more complicated. The Microsoft compiler
9871 /// won't check outer classes if there is an active value from #pragma code_seg.
9872 /// The CodeSeg is always applied from the direct parent but only from outer
9873 /// classes when the #pragma code_seg stack is empty. See:
9874 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9875 /// available since MS has removed the page.
9876 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9877   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9878   if (!Method)
9879     return nullptr;
9880   const CXXRecordDecl *Parent = Method->getParent();
9881   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9882     Attr *NewAttr = SAttr->clone(S.getASTContext());
9883     NewAttr->setImplicit(true);
9884     return NewAttr;
9885   }
9886 
9887   // The Microsoft compiler won't check outer classes for the CodeSeg
9888   // when the #pragma code_seg stack is active.
9889   if (S.CodeSegStack.CurrentValue)
9890    return nullptr;
9891 
9892   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9893     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9894       Attr *NewAttr = SAttr->clone(S.getASTContext());
9895       NewAttr->setImplicit(true);
9896       return NewAttr;
9897     }
9898   }
9899   return nullptr;
9900 }
9901 
9902 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9903 /// containing class. Otherwise it will return implicit SectionAttr if the
9904 /// function is a definition and there is an active value on CodeSegStack
9905 /// (from the current #pragma code-seg value).
9906 ///
9907 /// \param FD Function being declared.
9908 /// \param IsDefinition Whether it is a definition or just a declarartion.
9909 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9910 ///          nullptr if no attribute should be added.
9911 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9912                                                        bool IsDefinition) {
9913   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9914     return A;
9915   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9916       CodeSegStack.CurrentValue)
9917     return SectionAttr::CreateImplicit(
9918         getASTContext(), CodeSegStack.CurrentValue->getString(),
9919         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9920         SectionAttr::Declspec_allocate);
9921   return nullptr;
9922 }
9923 
9924 /// Determines if we can perform a correct type check for \p D as a
9925 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9926 /// best-effort check.
9927 ///
9928 /// \param NewD The new declaration.
9929 /// \param OldD The old declaration.
9930 /// \param NewT The portion of the type of the new declaration to check.
9931 /// \param OldT The portion of the type of the old declaration to check.
9932 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9933                                           QualType NewT, QualType OldT) {
9934   if (!NewD->getLexicalDeclContext()->isDependentContext())
9935     return true;
9936 
9937   // For dependently-typed local extern declarations and friends, we can't
9938   // perform a correct type check in general until instantiation:
9939   //
9940   //   int f();
9941   //   template<typename T> void g() { T f(); }
9942   //
9943   // (valid if g() is only instantiated with T = int).
9944   if (NewT->isDependentType() &&
9945       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9946     return false;
9947 
9948   // Similarly, if the previous declaration was a dependent local extern
9949   // declaration, we don't really know its type yet.
9950   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9951     return false;
9952 
9953   return true;
9954 }
9955 
9956 /// Checks if the new declaration declared in dependent context must be
9957 /// put in the same redeclaration chain as the specified declaration.
9958 ///
9959 /// \param D Declaration that is checked.
9960 /// \param PrevDecl Previous declaration found with proper lookup method for the
9961 ///                 same declaration name.
9962 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9963 ///          belongs to.
9964 ///
9965 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9966   if (!D->getLexicalDeclContext()->isDependentContext())
9967     return true;
9968 
9969   // Don't chain dependent friend function definitions until instantiation, to
9970   // permit cases like
9971   //
9972   //   void func();
9973   //   template<typename T> class C1 { friend void func() {} };
9974   //   template<typename T> class C2 { friend void func() {} };
9975   //
9976   // ... which is valid if only one of C1 and C2 is ever instantiated.
9977   //
9978   // FIXME: This need only apply to function definitions. For now, we proxy
9979   // this by checking for a file-scope function. We do not want this to apply
9980   // to friend declarations nominating member functions, because that gets in
9981   // the way of access checks.
9982   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9983     return false;
9984 
9985   auto *VD = dyn_cast<ValueDecl>(D);
9986   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9987   return !VD || !PrevVD ||
9988          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9989                                         PrevVD->getType());
9990 }
9991 
9992 /// Check the target attribute of the function for MultiVersion
9993 /// validity.
9994 ///
9995 /// Returns true if there was an error, false otherwise.
9996 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9997   const auto *TA = FD->getAttr<TargetAttr>();
9998   assert(TA && "MultiVersion Candidate requires a target attribute");
9999   ParsedTargetAttr ParseInfo = TA->parse();
10000   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10001   enum ErrType { Feature = 0, Architecture = 1 };
10002 
10003   if (!ParseInfo.Architecture.empty() &&
10004       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10005     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10006         << Architecture << ParseInfo.Architecture;
10007     return true;
10008   }
10009 
10010   for (const auto &Feat : ParseInfo.Features) {
10011     auto BareFeat = StringRef{Feat}.substr(1);
10012     if (Feat[0] == '-') {
10013       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10014           << Feature << ("no-" + BareFeat).str();
10015       return true;
10016     }
10017 
10018     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10019         !TargetInfo.isValidFeatureName(BareFeat)) {
10020       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10021           << Feature << BareFeat;
10022       return true;
10023     }
10024   }
10025   return false;
10026 }
10027 
10028 // Provide a white-list of attributes that are allowed to be combined with
10029 // multiversion functions.
10030 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10031                                            MultiVersionKind MVType) {
10032   switch (Kind) {
10033   default:
10034     return false;
10035   case attr::Used:
10036     return MVType == MultiVersionKind::Target;
10037   }
10038 }
10039 
10040 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
10041                                          MultiVersionKind MVType) {
10042   for (const Attr *A : FD->attrs()) {
10043     switch (A->getKind()) {
10044     case attr::CPUDispatch:
10045     case attr::CPUSpecific:
10046       if (MVType != MultiVersionKind::CPUDispatch &&
10047           MVType != MultiVersionKind::CPUSpecific)
10048         return true;
10049       break;
10050     case attr::Target:
10051       if (MVType != MultiVersionKind::Target)
10052         return true;
10053       break;
10054     default:
10055       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10056         return true;
10057       break;
10058     }
10059   }
10060   return false;
10061 }
10062 
10063 bool Sema::areMultiversionVariantFunctionsCompatible(
10064     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10065     const PartialDiagnostic &NoProtoDiagID,
10066     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10067     const PartialDiagnosticAt &NoSupportDiagIDAt,
10068     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10069     bool ConstexprSupported, bool CLinkageMayDiffer) {
10070   enum DoesntSupport {
10071     FuncTemplates = 0,
10072     VirtFuncs = 1,
10073     DeducedReturn = 2,
10074     Constructors = 3,
10075     Destructors = 4,
10076     DeletedFuncs = 5,
10077     DefaultedFuncs = 6,
10078     ConstexprFuncs = 7,
10079     ConstevalFuncs = 8,
10080   };
10081   enum Different {
10082     CallingConv = 0,
10083     ReturnType = 1,
10084     ConstexprSpec = 2,
10085     InlineSpec = 3,
10086     StorageClass = 4,
10087     Linkage = 5,
10088   };
10089 
10090   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10091       !OldFD->getType()->getAs<FunctionProtoType>()) {
10092     Diag(OldFD->getLocation(), NoProtoDiagID);
10093     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10094     return true;
10095   }
10096 
10097   if (NoProtoDiagID.getDiagID() != 0 &&
10098       !NewFD->getType()->getAs<FunctionProtoType>())
10099     return Diag(NewFD->getLocation(), NoProtoDiagID);
10100 
10101   if (!TemplatesSupported &&
10102       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10103     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10104            << FuncTemplates;
10105 
10106   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10107     if (NewCXXFD->isVirtual())
10108       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10109              << VirtFuncs;
10110 
10111     if (isa<CXXConstructorDecl>(NewCXXFD))
10112       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10113              << Constructors;
10114 
10115     if (isa<CXXDestructorDecl>(NewCXXFD))
10116       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10117              << Destructors;
10118   }
10119 
10120   if (NewFD->isDeleted())
10121     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10122            << DeletedFuncs;
10123 
10124   if (NewFD->isDefaulted())
10125     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10126            << DefaultedFuncs;
10127 
10128   if (!ConstexprSupported && NewFD->isConstexpr())
10129     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10130            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10131 
10132   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10133   const auto *NewType = cast<FunctionType>(NewQType);
10134   QualType NewReturnType = NewType->getReturnType();
10135 
10136   if (NewReturnType->isUndeducedType())
10137     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10138            << DeducedReturn;
10139 
10140   // Ensure the return type is identical.
10141   if (OldFD) {
10142     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10143     const auto *OldType = cast<FunctionType>(OldQType);
10144     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10145     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10146 
10147     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10148       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10149 
10150     QualType OldReturnType = OldType->getReturnType();
10151 
10152     if (OldReturnType != NewReturnType)
10153       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10154 
10155     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10156       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10157 
10158     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10159       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10160 
10161     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10162       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10163 
10164     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10165       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10166 
10167     if (CheckEquivalentExceptionSpec(
10168             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10169             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10170       return true;
10171   }
10172   return false;
10173 }
10174 
10175 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10176                                              const FunctionDecl *NewFD,
10177                                              bool CausesMV,
10178                                              MultiVersionKind MVType) {
10179   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10180     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10181     if (OldFD)
10182       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10183     return true;
10184   }
10185 
10186   bool IsCPUSpecificCPUDispatchMVType =
10187       MVType == MultiVersionKind::CPUDispatch ||
10188       MVType == MultiVersionKind::CPUSpecific;
10189 
10190   // For now, disallow all other attributes.  These should be opt-in, but
10191   // an analysis of all of them is a future FIXME.
10192   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
10193     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
10194         << IsCPUSpecificCPUDispatchMVType;
10195     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10196     return true;
10197   }
10198 
10199   if (HasNonMultiVersionAttributes(NewFD, MVType))
10200     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10201            << IsCPUSpecificCPUDispatchMVType;
10202 
10203   // Only allow transition to MultiVersion if it hasn't been used.
10204   if (OldFD && CausesMV && OldFD->isUsed(false))
10205     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10206 
10207   return S.areMultiversionVariantFunctionsCompatible(
10208       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10209       PartialDiagnosticAt(NewFD->getLocation(),
10210                           S.PDiag(diag::note_multiversioning_caused_here)),
10211       PartialDiagnosticAt(NewFD->getLocation(),
10212                           S.PDiag(diag::err_multiversion_doesnt_support)
10213                               << IsCPUSpecificCPUDispatchMVType),
10214       PartialDiagnosticAt(NewFD->getLocation(),
10215                           S.PDiag(diag::err_multiversion_diff)),
10216       /*TemplatesSupported=*/false,
10217       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10218       /*CLinkageMayDiffer=*/false);
10219 }
10220 
10221 /// Check the validity of a multiversion function declaration that is the
10222 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10223 ///
10224 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10225 ///
10226 /// Returns true if there was an error, false otherwise.
10227 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10228                                            MultiVersionKind MVType,
10229                                            const TargetAttr *TA) {
10230   assert(MVType != MultiVersionKind::None &&
10231          "Function lacks multiversion attribute");
10232 
10233   // Target only causes MV if it is default, otherwise this is a normal
10234   // function.
10235   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10236     return false;
10237 
10238   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10239     FD->setInvalidDecl();
10240     return true;
10241   }
10242 
10243   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10244     FD->setInvalidDecl();
10245     return true;
10246   }
10247 
10248   FD->setIsMultiVersion();
10249   return false;
10250 }
10251 
10252 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10253   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10254     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10255       return true;
10256   }
10257 
10258   return false;
10259 }
10260 
10261 static bool CheckTargetCausesMultiVersioning(
10262     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10263     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10264     LookupResult &Previous) {
10265   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10266   ParsedTargetAttr NewParsed = NewTA->parse();
10267   // Sort order doesn't matter, it just needs to be consistent.
10268   llvm::sort(NewParsed.Features);
10269 
10270   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10271   // to change, this is a simple redeclaration.
10272   if (!NewTA->isDefaultVersion() &&
10273       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10274     return false;
10275 
10276   // Otherwise, this decl causes MultiVersioning.
10277   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10278     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10279     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10280     NewFD->setInvalidDecl();
10281     return true;
10282   }
10283 
10284   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10285                                        MultiVersionKind::Target)) {
10286     NewFD->setInvalidDecl();
10287     return true;
10288   }
10289 
10290   if (CheckMultiVersionValue(S, NewFD)) {
10291     NewFD->setInvalidDecl();
10292     return true;
10293   }
10294 
10295   // If this is 'default', permit the forward declaration.
10296   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10297     Redeclaration = true;
10298     OldDecl = OldFD;
10299     OldFD->setIsMultiVersion();
10300     NewFD->setIsMultiVersion();
10301     return false;
10302   }
10303 
10304   if (CheckMultiVersionValue(S, OldFD)) {
10305     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10306     NewFD->setInvalidDecl();
10307     return true;
10308   }
10309 
10310   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10311 
10312   if (OldParsed == NewParsed) {
10313     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10314     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10315     NewFD->setInvalidDecl();
10316     return true;
10317   }
10318 
10319   for (const auto *FD : OldFD->redecls()) {
10320     const auto *CurTA = FD->getAttr<TargetAttr>();
10321     // We allow forward declarations before ANY multiversioning attributes, but
10322     // nothing after the fact.
10323     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10324         (!CurTA || CurTA->isInherited())) {
10325       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10326           << 0;
10327       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10328       NewFD->setInvalidDecl();
10329       return true;
10330     }
10331   }
10332 
10333   OldFD->setIsMultiVersion();
10334   NewFD->setIsMultiVersion();
10335   Redeclaration = false;
10336   MergeTypeWithPrevious = false;
10337   OldDecl = nullptr;
10338   Previous.clear();
10339   return false;
10340 }
10341 
10342 /// Check the validity of a new function declaration being added to an existing
10343 /// multiversioned declaration collection.
10344 static bool CheckMultiVersionAdditionalDecl(
10345     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10346     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10347     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10348     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10349     LookupResult &Previous) {
10350 
10351   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10352   // Disallow mixing of multiversioning types.
10353   if ((OldMVType == MultiVersionKind::Target &&
10354        NewMVType != MultiVersionKind::Target) ||
10355       (NewMVType == MultiVersionKind::Target &&
10356        OldMVType != MultiVersionKind::Target)) {
10357     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10358     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10359     NewFD->setInvalidDecl();
10360     return true;
10361   }
10362 
10363   ParsedTargetAttr NewParsed;
10364   if (NewTA) {
10365     NewParsed = NewTA->parse();
10366     llvm::sort(NewParsed.Features);
10367   }
10368 
10369   bool UseMemberUsingDeclRules =
10370       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10371 
10372   // Next, check ALL non-overloads to see if this is a redeclaration of a
10373   // previous member of the MultiVersion set.
10374   for (NamedDecl *ND : Previous) {
10375     FunctionDecl *CurFD = ND->getAsFunction();
10376     if (!CurFD)
10377       continue;
10378     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10379       continue;
10380 
10381     if (NewMVType == MultiVersionKind::Target) {
10382       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10383       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10384         NewFD->setIsMultiVersion();
10385         Redeclaration = true;
10386         OldDecl = ND;
10387         return false;
10388       }
10389 
10390       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10391       if (CurParsed == NewParsed) {
10392         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10393         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10394         NewFD->setInvalidDecl();
10395         return true;
10396       }
10397     } else {
10398       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10399       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10400       // Handle CPUDispatch/CPUSpecific versions.
10401       // Only 1 CPUDispatch function is allowed, this will make it go through
10402       // the redeclaration errors.
10403       if (NewMVType == MultiVersionKind::CPUDispatch &&
10404           CurFD->hasAttr<CPUDispatchAttr>()) {
10405         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10406             std::equal(
10407                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10408                 NewCPUDisp->cpus_begin(),
10409                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10410                   return Cur->getName() == New->getName();
10411                 })) {
10412           NewFD->setIsMultiVersion();
10413           Redeclaration = true;
10414           OldDecl = ND;
10415           return false;
10416         }
10417 
10418         // If the declarations don't match, this is an error condition.
10419         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10420         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10421         NewFD->setInvalidDecl();
10422         return true;
10423       }
10424       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10425 
10426         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10427             std::equal(
10428                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10429                 NewCPUSpec->cpus_begin(),
10430                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10431                   return Cur->getName() == New->getName();
10432                 })) {
10433           NewFD->setIsMultiVersion();
10434           Redeclaration = true;
10435           OldDecl = ND;
10436           return false;
10437         }
10438 
10439         // Only 1 version of CPUSpecific is allowed for each CPU.
10440         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10441           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10442             if (CurII == NewII) {
10443               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10444                   << NewII;
10445               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10446               NewFD->setInvalidDecl();
10447               return true;
10448             }
10449           }
10450         }
10451       }
10452       // If the two decls aren't the same MVType, there is no possible error
10453       // condition.
10454     }
10455   }
10456 
10457   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10458   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10459   // handled in the attribute adding step.
10460   if (NewMVType == MultiVersionKind::Target &&
10461       CheckMultiVersionValue(S, NewFD)) {
10462     NewFD->setInvalidDecl();
10463     return true;
10464   }
10465 
10466   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10467                                        !OldFD->isMultiVersion(), NewMVType)) {
10468     NewFD->setInvalidDecl();
10469     return true;
10470   }
10471 
10472   // Permit forward declarations in the case where these two are compatible.
10473   if (!OldFD->isMultiVersion()) {
10474     OldFD->setIsMultiVersion();
10475     NewFD->setIsMultiVersion();
10476     Redeclaration = true;
10477     OldDecl = OldFD;
10478     return false;
10479   }
10480 
10481   NewFD->setIsMultiVersion();
10482   Redeclaration = false;
10483   MergeTypeWithPrevious = false;
10484   OldDecl = nullptr;
10485   Previous.clear();
10486   return false;
10487 }
10488 
10489 
10490 /// Check the validity of a mulitversion function declaration.
10491 /// Also sets the multiversion'ness' of the function itself.
10492 ///
10493 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10494 ///
10495 /// Returns true if there was an error, false otherwise.
10496 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10497                                       bool &Redeclaration, NamedDecl *&OldDecl,
10498                                       bool &MergeTypeWithPrevious,
10499                                       LookupResult &Previous) {
10500   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10501   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10502   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10503 
10504   // Mixing Multiversioning types is prohibited.
10505   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10506       (NewCPUDisp && NewCPUSpec)) {
10507     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10508     NewFD->setInvalidDecl();
10509     return true;
10510   }
10511 
10512   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10513 
10514   // Main isn't allowed to become a multiversion function, however it IS
10515   // permitted to have 'main' be marked with the 'target' optimization hint.
10516   if (NewFD->isMain()) {
10517     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10518         MVType == MultiVersionKind::CPUDispatch ||
10519         MVType == MultiVersionKind::CPUSpecific) {
10520       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10521       NewFD->setInvalidDecl();
10522       return true;
10523     }
10524     return false;
10525   }
10526 
10527   if (!OldDecl || !OldDecl->getAsFunction() ||
10528       OldDecl->getDeclContext()->getRedeclContext() !=
10529           NewFD->getDeclContext()->getRedeclContext()) {
10530     // If there's no previous declaration, AND this isn't attempting to cause
10531     // multiversioning, this isn't an error condition.
10532     if (MVType == MultiVersionKind::None)
10533       return false;
10534     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10535   }
10536 
10537   FunctionDecl *OldFD = OldDecl->getAsFunction();
10538 
10539   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10540     return false;
10541 
10542   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10543     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10544         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10545     NewFD->setInvalidDecl();
10546     return true;
10547   }
10548 
10549   // Handle the target potentially causes multiversioning case.
10550   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10551     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10552                                             Redeclaration, OldDecl,
10553                                             MergeTypeWithPrevious, Previous);
10554 
10555   // At this point, we have a multiversion function decl (in OldFD) AND an
10556   // appropriate attribute in the current function decl.  Resolve that these are
10557   // still compatible with previous declarations.
10558   return CheckMultiVersionAdditionalDecl(
10559       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10560       OldDecl, MergeTypeWithPrevious, Previous);
10561 }
10562 
10563 /// Perform semantic checking of a new function declaration.
10564 ///
10565 /// Performs semantic analysis of the new function declaration
10566 /// NewFD. This routine performs all semantic checking that does not
10567 /// require the actual declarator involved in the declaration, and is
10568 /// used both for the declaration of functions as they are parsed
10569 /// (called via ActOnDeclarator) and for the declaration of functions
10570 /// that have been instantiated via C++ template instantiation (called
10571 /// via InstantiateDecl).
10572 ///
10573 /// \param IsMemberSpecialization whether this new function declaration is
10574 /// a member specialization (that replaces any definition provided by the
10575 /// previous declaration).
10576 ///
10577 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10578 ///
10579 /// \returns true if the function declaration is a redeclaration.
10580 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10581                                     LookupResult &Previous,
10582                                     bool IsMemberSpecialization) {
10583   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10584          "Variably modified return types are not handled here");
10585 
10586   // Determine whether the type of this function should be merged with
10587   // a previous visible declaration. This never happens for functions in C++,
10588   // and always happens in C if the previous declaration was visible.
10589   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10590                                !Previous.isShadowed();
10591 
10592   bool Redeclaration = false;
10593   NamedDecl *OldDecl = nullptr;
10594   bool MayNeedOverloadableChecks = false;
10595 
10596   // Merge or overload the declaration with an existing declaration of
10597   // the same name, if appropriate.
10598   if (!Previous.empty()) {
10599     // Determine whether NewFD is an overload of PrevDecl or
10600     // a declaration that requires merging. If it's an overload,
10601     // there's no more work to do here; we'll just add the new
10602     // function to the scope.
10603     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10604       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10605       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10606         Redeclaration = true;
10607         OldDecl = Candidate;
10608       }
10609     } else {
10610       MayNeedOverloadableChecks = true;
10611       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10612                             /*NewIsUsingDecl*/ false)) {
10613       case Ovl_Match:
10614         Redeclaration = true;
10615         break;
10616 
10617       case Ovl_NonFunction:
10618         Redeclaration = true;
10619         break;
10620 
10621       case Ovl_Overload:
10622         Redeclaration = false;
10623         break;
10624       }
10625     }
10626   }
10627 
10628   // Check for a previous extern "C" declaration with this name.
10629   if (!Redeclaration &&
10630       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10631     if (!Previous.empty()) {
10632       // This is an extern "C" declaration with the same name as a previous
10633       // declaration, and thus redeclares that entity...
10634       Redeclaration = true;
10635       OldDecl = Previous.getFoundDecl();
10636       MergeTypeWithPrevious = false;
10637 
10638       // ... except in the presence of __attribute__((overloadable)).
10639       if (OldDecl->hasAttr<OverloadableAttr>() ||
10640           NewFD->hasAttr<OverloadableAttr>()) {
10641         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10642           MayNeedOverloadableChecks = true;
10643           Redeclaration = false;
10644           OldDecl = nullptr;
10645         }
10646       }
10647     }
10648   }
10649 
10650   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10651                                 MergeTypeWithPrevious, Previous))
10652     return Redeclaration;
10653 
10654   // C++11 [dcl.constexpr]p8:
10655   //   A constexpr specifier for a non-static member function that is not
10656   //   a constructor declares that member function to be const.
10657   //
10658   // This needs to be delayed until we know whether this is an out-of-line
10659   // definition of a static member function.
10660   //
10661   // This rule is not present in C++1y, so we produce a backwards
10662   // compatibility warning whenever it happens in C++11.
10663   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10664   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10665       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10666       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10667     CXXMethodDecl *OldMD = nullptr;
10668     if (OldDecl)
10669       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10670     if (!OldMD || !OldMD->isStatic()) {
10671       const FunctionProtoType *FPT =
10672         MD->getType()->castAs<FunctionProtoType>();
10673       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10674       EPI.TypeQuals.addConst();
10675       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10676                                           FPT->getParamTypes(), EPI));
10677 
10678       // Warn that we did this, if we're not performing template instantiation.
10679       // In that case, we'll have warned already when the template was defined.
10680       if (!inTemplateInstantiation()) {
10681         SourceLocation AddConstLoc;
10682         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10683                 .IgnoreParens().getAs<FunctionTypeLoc>())
10684           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10685 
10686         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10687           << FixItHint::CreateInsertion(AddConstLoc, " const");
10688       }
10689     }
10690   }
10691 
10692   if (Redeclaration) {
10693     // NewFD and OldDecl represent declarations that need to be
10694     // merged.
10695     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10696       NewFD->setInvalidDecl();
10697       return Redeclaration;
10698     }
10699 
10700     Previous.clear();
10701     Previous.addDecl(OldDecl);
10702 
10703     if (FunctionTemplateDecl *OldTemplateDecl =
10704             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10705       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10706       FunctionTemplateDecl *NewTemplateDecl
10707         = NewFD->getDescribedFunctionTemplate();
10708       assert(NewTemplateDecl && "Template/non-template mismatch");
10709 
10710       // The call to MergeFunctionDecl above may have created some state in
10711       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10712       // can add it as a redeclaration.
10713       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10714 
10715       NewFD->setPreviousDeclaration(OldFD);
10716       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10717       if (NewFD->isCXXClassMember()) {
10718         NewFD->setAccess(OldTemplateDecl->getAccess());
10719         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10720       }
10721 
10722       // If this is an explicit specialization of a member that is a function
10723       // template, mark it as a member specialization.
10724       if (IsMemberSpecialization &&
10725           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10726         NewTemplateDecl->setMemberSpecialization();
10727         assert(OldTemplateDecl->isMemberSpecialization());
10728         // Explicit specializations of a member template do not inherit deleted
10729         // status from the parent member template that they are specializing.
10730         if (OldFD->isDeleted()) {
10731           // FIXME: This assert will not hold in the presence of modules.
10732           assert(OldFD->getCanonicalDecl() == OldFD);
10733           // FIXME: We need an update record for this AST mutation.
10734           OldFD->setDeletedAsWritten(false);
10735         }
10736       }
10737 
10738     } else {
10739       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10740         auto *OldFD = cast<FunctionDecl>(OldDecl);
10741         // This needs to happen first so that 'inline' propagates.
10742         NewFD->setPreviousDeclaration(OldFD);
10743         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10744         if (NewFD->isCXXClassMember())
10745           NewFD->setAccess(OldFD->getAccess());
10746       }
10747     }
10748   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10749              !NewFD->getAttr<OverloadableAttr>()) {
10750     assert((Previous.empty() ||
10751             llvm::any_of(Previous,
10752                          [](const NamedDecl *ND) {
10753                            return ND->hasAttr<OverloadableAttr>();
10754                          })) &&
10755            "Non-redecls shouldn't happen without overloadable present");
10756 
10757     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10758       const auto *FD = dyn_cast<FunctionDecl>(ND);
10759       return FD && !FD->hasAttr<OverloadableAttr>();
10760     });
10761 
10762     if (OtherUnmarkedIter != Previous.end()) {
10763       Diag(NewFD->getLocation(),
10764            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10765       Diag((*OtherUnmarkedIter)->getLocation(),
10766            diag::note_attribute_overloadable_prev_overload)
10767           << false;
10768 
10769       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10770     }
10771   }
10772 
10773   // Semantic checking for this function declaration (in isolation).
10774 
10775   if (getLangOpts().CPlusPlus) {
10776     // C++-specific checks.
10777     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10778       CheckConstructor(Constructor);
10779     } else if (CXXDestructorDecl *Destructor =
10780                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10781       CXXRecordDecl *Record = Destructor->getParent();
10782       QualType ClassType = Context.getTypeDeclType(Record);
10783 
10784       // FIXME: Shouldn't we be able to perform this check even when the class
10785       // type is dependent? Both gcc and edg can handle that.
10786       if (!ClassType->isDependentType()) {
10787         DeclarationName Name
10788           = Context.DeclarationNames.getCXXDestructorName(
10789                                         Context.getCanonicalType(ClassType));
10790         if (NewFD->getDeclName() != Name) {
10791           Diag(NewFD->getLocation(), diag::err_destructor_name);
10792           NewFD->setInvalidDecl();
10793           return Redeclaration;
10794         }
10795       }
10796     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10797       if (auto *TD = Guide->getDescribedFunctionTemplate())
10798         CheckDeductionGuideTemplate(TD);
10799 
10800       // A deduction guide is not on the list of entities that can be
10801       // explicitly specialized.
10802       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10803         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10804             << /*explicit specialization*/ 1;
10805     }
10806 
10807     // Find any virtual functions that this function overrides.
10808     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10809       if (!Method->isFunctionTemplateSpecialization() &&
10810           !Method->getDescribedFunctionTemplate() &&
10811           Method->isCanonicalDecl()) {
10812         AddOverriddenMethods(Method->getParent(), Method);
10813       }
10814       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10815         // C++2a [class.virtual]p6
10816         // A virtual method shall not have a requires-clause.
10817         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10818              diag::err_constrained_virtual_method);
10819 
10820       if (Method->isStatic())
10821         checkThisInStaticMemberFunctionType(Method);
10822     }
10823 
10824     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10825       ActOnConversionDeclarator(Conversion);
10826 
10827     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10828     if (NewFD->isOverloadedOperator() &&
10829         CheckOverloadedOperatorDeclaration(NewFD)) {
10830       NewFD->setInvalidDecl();
10831       return Redeclaration;
10832     }
10833 
10834     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10835     if (NewFD->getLiteralIdentifier() &&
10836         CheckLiteralOperatorDeclaration(NewFD)) {
10837       NewFD->setInvalidDecl();
10838       return Redeclaration;
10839     }
10840 
10841     // In C++, check default arguments now that we have merged decls. Unless
10842     // the lexical context is the class, because in this case this is done
10843     // during delayed parsing anyway.
10844     if (!CurContext->isRecord())
10845       CheckCXXDefaultArguments(NewFD);
10846 
10847     // If this function declares a builtin function, check the type of this
10848     // declaration against the expected type for the builtin.
10849     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10850       ASTContext::GetBuiltinTypeError Error;
10851       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10852       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10853       // If the type of the builtin differs only in its exception
10854       // specification, that's OK.
10855       // FIXME: If the types do differ in this way, it would be better to
10856       // retain the 'noexcept' form of the type.
10857       if (!T.isNull() &&
10858           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10859                                                             NewFD->getType()))
10860         // The type of this function differs from the type of the builtin,
10861         // so forget about the builtin entirely.
10862         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10863     }
10864 
10865     // If this function is declared as being extern "C", then check to see if
10866     // the function returns a UDT (class, struct, or union type) that is not C
10867     // compatible, and if it does, warn the user.
10868     // But, issue any diagnostic on the first declaration only.
10869     if (Previous.empty() && NewFD->isExternC()) {
10870       QualType R = NewFD->getReturnType();
10871       if (R->isIncompleteType() && !R->isVoidType())
10872         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10873             << NewFD << R;
10874       else if (!R.isPODType(Context) && !R->isVoidType() &&
10875                !R->isObjCObjectPointerType())
10876         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10877     }
10878 
10879     // C++1z [dcl.fct]p6:
10880     //   [...] whether the function has a non-throwing exception-specification
10881     //   [is] part of the function type
10882     //
10883     // This results in an ABI break between C++14 and C++17 for functions whose
10884     // declared type includes an exception-specification in a parameter or
10885     // return type. (Exception specifications on the function itself are OK in
10886     // most cases, and exception specifications are not permitted in most other
10887     // contexts where they could make it into a mangling.)
10888     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10889       auto HasNoexcept = [&](QualType T) -> bool {
10890         // Strip off declarator chunks that could be between us and a function
10891         // type. We don't need to look far, exception specifications are very
10892         // restricted prior to C++17.
10893         if (auto *RT = T->getAs<ReferenceType>())
10894           T = RT->getPointeeType();
10895         else if (T->isAnyPointerType())
10896           T = T->getPointeeType();
10897         else if (auto *MPT = T->getAs<MemberPointerType>())
10898           T = MPT->getPointeeType();
10899         if (auto *FPT = T->getAs<FunctionProtoType>())
10900           if (FPT->isNothrow())
10901             return true;
10902         return false;
10903       };
10904 
10905       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10906       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10907       for (QualType T : FPT->param_types())
10908         AnyNoexcept |= HasNoexcept(T);
10909       if (AnyNoexcept)
10910         Diag(NewFD->getLocation(),
10911              diag::warn_cxx17_compat_exception_spec_in_signature)
10912             << NewFD;
10913     }
10914 
10915     if (!Redeclaration && LangOpts.CUDA)
10916       checkCUDATargetOverload(NewFD, Previous);
10917   }
10918   return Redeclaration;
10919 }
10920 
10921 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10922   // C++11 [basic.start.main]p3:
10923   //   A program that [...] declares main to be inline, static or
10924   //   constexpr is ill-formed.
10925   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10926   //   appear in a declaration of main.
10927   // static main is not an error under C99, but we should warn about it.
10928   // We accept _Noreturn main as an extension.
10929   if (FD->getStorageClass() == SC_Static)
10930     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10931          ? diag::err_static_main : diag::warn_static_main)
10932       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10933   if (FD->isInlineSpecified())
10934     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10935       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10936   if (DS.isNoreturnSpecified()) {
10937     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10938     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10939     Diag(NoreturnLoc, diag::ext_noreturn_main);
10940     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10941       << FixItHint::CreateRemoval(NoreturnRange);
10942   }
10943   if (FD->isConstexpr()) {
10944     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10945         << FD->isConsteval()
10946         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10947     FD->setConstexprKind(CSK_unspecified);
10948   }
10949 
10950   if (getLangOpts().OpenCL) {
10951     Diag(FD->getLocation(), diag::err_opencl_no_main)
10952         << FD->hasAttr<OpenCLKernelAttr>();
10953     FD->setInvalidDecl();
10954     return;
10955   }
10956 
10957   QualType T = FD->getType();
10958   assert(T->isFunctionType() && "function decl is not of function type");
10959   const FunctionType* FT = T->castAs<FunctionType>();
10960 
10961   // Set default calling convention for main()
10962   if (FT->getCallConv() != CC_C) {
10963     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10964     FD->setType(QualType(FT, 0));
10965     T = Context.getCanonicalType(FD->getType());
10966   }
10967 
10968   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10969     // In C with GNU extensions we allow main() to have non-integer return
10970     // type, but we should warn about the extension, and we disable the
10971     // implicit-return-zero rule.
10972 
10973     // GCC in C mode accepts qualified 'int'.
10974     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10975       FD->setHasImplicitReturnZero(true);
10976     else {
10977       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10978       SourceRange RTRange = FD->getReturnTypeSourceRange();
10979       if (RTRange.isValid())
10980         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10981             << FixItHint::CreateReplacement(RTRange, "int");
10982     }
10983   } else {
10984     // In C and C++, main magically returns 0 if you fall off the end;
10985     // set the flag which tells us that.
10986     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10987 
10988     // All the standards say that main() should return 'int'.
10989     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10990       FD->setHasImplicitReturnZero(true);
10991     else {
10992       // Otherwise, this is just a flat-out error.
10993       SourceRange RTRange = FD->getReturnTypeSourceRange();
10994       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10995           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10996                                 : FixItHint());
10997       FD->setInvalidDecl(true);
10998     }
10999   }
11000 
11001   // Treat protoless main() as nullary.
11002   if (isa<FunctionNoProtoType>(FT)) return;
11003 
11004   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11005   unsigned nparams = FTP->getNumParams();
11006   assert(FD->getNumParams() == nparams);
11007 
11008   bool HasExtraParameters = (nparams > 3);
11009 
11010   if (FTP->isVariadic()) {
11011     Diag(FD->getLocation(), diag::ext_variadic_main);
11012     // FIXME: if we had information about the location of the ellipsis, we
11013     // could add a FixIt hint to remove it as a parameter.
11014   }
11015 
11016   // Darwin passes an undocumented fourth argument of type char**.  If
11017   // other platforms start sprouting these, the logic below will start
11018   // getting shifty.
11019   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11020     HasExtraParameters = false;
11021 
11022   if (HasExtraParameters) {
11023     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11024     FD->setInvalidDecl(true);
11025     nparams = 3;
11026   }
11027 
11028   // FIXME: a lot of the following diagnostics would be improved
11029   // if we had some location information about types.
11030 
11031   QualType CharPP =
11032     Context.getPointerType(Context.getPointerType(Context.CharTy));
11033   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11034 
11035   for (unsigned i = 0; i < nparams; ++i) {
11036     QualType AT = FTP->getParamType(i);
11037 
11038     bool mismatch = true;
11039 
11040     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11041       mismatch = false;
11042     else if (Expected[i] == CharPP) {
11043       // As an extension, the following forms are okay:
11044       //   char const **
11045       //   char const * const *
11046       //   char * const *
11047 
11048       QualifierCollector qs;
11049       const PointerType* PT;
11050       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11051           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11052           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11053                               Context.CharTy)) {
11054         qs.removeConst();
11055         mismatch = !qs.empty();
11056       }
11057     }
11058 
11059     if (mismatch) {
11060       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11061       // TODO: suggest replacing given type with expected type
11062       FD->setInvalidDecl(true);
11063     }
11064   }
11065 
11066   if (nparams == 1 && !FD->isInvalidDecl()) {
11067     Diag(FD->getLocation(), diag::warn_main_one_arg);
11068   }
11069 
11070   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11071     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11072     FD->setInvalidDecl();
11073   }
11074 }
11075 
11076 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11077   QualType T = FD->getType();
11078   assert(T->isFunctionType() && "function decl is not of function type");
11079   const FunctionType *FT = T->castAs<FunctionType>();
11080 
11081   // Set an implicit return of 'zero' if the function can return some integral,
11082   // enumeration, pointer or nullptr type.
11083   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11084       FT->getReturnType()->isAnyPointerType() ||
11085       FT->getReturnType()->isNullPtrType())
11086     // DllMain is exempt because a return value of zero means it failed.
11087     if (FD->getName() != "DllMain")
11088       FD->setHasImplicitReturnZero(true);
11089 
11090   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11091     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11092     FD->setInvalidDecl();
11093   }
11094 }
11095 
11096 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11097   // FIXME: Need strict checking.  In C89, we need to check for
11098   // any assignment, increment, decrement, function-calls, or
11099   // commas outside of a sizeof.  In C99, it's the same list,
11100   // except that the aforementioned are allowed in unevaluated
11101   // expressions.  Everything else falls under the
11102   // "may accept other forms of constant expressions" exception.
11103   //
11104   // Regular C++ code will not end up here (exceptions: language extensions,
11105   // OpenCL C++ etc), so the constant expression rules there don't matter.
11106   if (Init->isValueDependent()) {
11107     assert(Init->containsErrors() &&
11108            "Dependent code should only occur in error-recovery path.");
11109     return true;
11110   }
11111   const Expr *Culprit;
11112   if (Init->isConstantInitializer(Context, false, &Culprit))
11113     return false;
11114   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11115     << Culprit->getSourceRange();
11116   return true;
11117 }
11118 
11119 namespace {
11120   // Visits an initialization expression to see if OrigDecl is evaluated in
11121   // its own initialization and throws a warning if it does.
11122   class SelfReferenceChecker
11123       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11124     Sema &S;
11125     Decl *OrigDecl;
11126     bool isRecordType;
11127     bool isPODType;
11128     bool isReferenceType;
11129 
11130     bool isInitList;
11131     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11132 
11133   public:
11134     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11135 
11136     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11137                                                     S(S), OrigDecl(OrigDecl) {
11138       isPODType = false;
11139       isRecordType = false;
11140       isReferenceType = false;
11141       isInitList = false;
11142       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11143         isPODType = VD->getType().isPODType(S.Context);
11144         isRecordType = VD->getType()->isRecordType();
11145         isReferenceType = VD->getType()->isReferenceType();
11146       }
11147     }
11148 
11149     // For most expressions, just call the visitor.  For initializer lists,
11150     // track the index of the field being initialized since fields are
11151     // initialized in order allowing use of previously initialized fields.
11152     void CheckExpr(Expr *E) {
11153       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11154       if (!InitList) {
11155         Visit(E);
11156         return;
11157       }
11158 
11159       // Track and increment the index here.
11160       isInitList = true;
11161       InitFieldIndex.push_back(0);
11162       for (auto Child : InitList->children()) {
11163         CheckExpr(cast<Expr>(Child));
11164         ++InitFieldIndex.back();
11165       }
11166       InitFieldIndex.pop_back();
11167     }
11168 
11169     // Returns true if MemberExpr is checked and no further checking is needed.
11170     // Returns false if additional checking is required.
11171     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11172       llvm::SmallVector<FieldDecl*, 4> Fields;
11173       Expr *Base = E;
11174       bool ReferenceField = false;
11175 
11176       // Get the field members used.
11177       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11178         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11179         if (!FD)
11180           return false;
11181         Fields.push_back(FD);
11182         if (FD->getType()->isReferenceType())
11183           ReferenceField = true;
11184         Base = ME->getBase()->IgnoreParenImpCasts();
11185       }
11186 
11187       // Keep checking only if the base Decl is the same.
11188       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11189       if (!DRE || DRE->getDecl() != OrigDecl)
11190         return false;
11191 
11192       // A reference field can be bound to an unininitialized field.
11193       if (CheckReference && !ReferenceField)
11194         return true;
11195 
11196       // Convert FieldDecls to their index number.
11197       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11198       for (const FieldDecl *I : llvm::reverse(Fields))
11199         UsedFieldIndex.push_back(I->getFieldIndex());
11200 
11201       // See if a warning is needed by checking the first difference in index
11202       // numbers.  If field being used has index less than the field being
11203       // initialized, then the use is safe.
11204       for (auto UsedIter = UsedFieldIndex.begin(),
11205                 UsedEnd = UsedFieldIndex.end(),
11206                 OrigIter = InitFieldIndex.begin(),
11207                 OrigEnd = InitFieldIndex.end();
11208            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11209         if (*UsedIter < *OrigIter)
11210           return true;
11211         if (*UsedIter > *OrigIter)
11212           break;
11213       }
11214 
11215       // TODO: Add a different warning which will print the field names.
11216       HandleDeclRefExpr(DRE);
11217       return true;
11218     }
11219 
11220     // For most expressions, the cast is directly above the DeclRefExpr.
11221     // For conditional operators, the cast can be outside the conditional
11222     // operator if both expressions are DeclRefExpr's.
11223     void HandleValue(Expr *E) {
11224       E = E->IgnoreParens();
11225       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11226         HandleDeclRefExpr(DRE);
11227         return;
11228       }
11229 
11230       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11231         Visit(CO->getCond());
11232         HandleValue(CO->getTrueExpr());
11233         HandleValue(CO->getFalseExpr());
11234         return;
11235       }
11236 
11237       if (BinaryConditionalOperator *BCO =
11238               dyn_cast<BinaryConditionalOperator>(E)) {
11239         Visit(BCO->getCond());
11240         HandleValue(BCO->getFalseExpr());
11241         return;
11242       }
11243 
11244       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11245         HandleValue(OVE->getSourceExpr());
11246         return;
11247       }
11248 
11249       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11250         if (BO->getOpcode() == BO_Comma) {
11251           Visit(BO->getLHS());
11252           HandleValue(BO->getRHS());
11253           return;
11254         }
11255       }
11256 
11257       if (isa<MemberExpr>(E)) {
11258         if (isInitList) {
11259           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11260                                       false /*CheckReference*/))
11261             return;
11262         }
11263 
11264         Expr *Base = E->IgnoreParenImpCasts();
11265         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11266           // Check for static member variables and don't warn on them.
11267           if (!isa<FieldDecl>(ME->getMemberDecl()))
11268             return;
11269           Base = ME->getBase()->IgnoreParenImpCasts();
11270         }
11271         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11272           HandleDeclRefExpr(DRE);
11273         return;
11274       }
11275 
11276       Visit(E);
11277     }
11278 
11279     // Reference types not handled in HandleValue are handled here since all
11280     // uses of references are bad, not just r-value uses.
11281     void VisitDeclRefExpr(DeclRefExpr *E) {
11282       if (isReferenceType)
11283         HandleDeclRefExpr(E);
11284     }
11285 
11286     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11287       if (E->getCastKind() == CK_LValueToRValue) {
11288         HandleValue(E->getSubExpr());
11289         return;
11290       }
11291 
11292       Inherited::VisitImplicitCastExpr(E);
11293     }
11294 
11295     void VisitMemberExpr(MemberExpr *E) {
11296       if (isInitList) {
11297         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11298           return;
11299       }
11300 
11301       // Don't warn on arrays since they can be treated as pointers.
11302       if (E->getType()->canDecayToPointerType()) return;
11303 
11304       // Warn when a non-static method call is followed by non-static member
11305       // field accesses, which is followed by a DeclRefExpr.
11306       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11307       bool Warn = (MD && !MD->isStatic());
11308       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11309       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11310         if (!isa<FieldDecl>(ME->getMemberDecl()))
11311           Warn = false;
11312         Base = ME->getBase()->IgnoreParenImpCasts();
11313       }
11314 
11315       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11316         if (Warn)
11317           HandleDeclRefExpr(DRE);
11318         return;
11319       }
11320 
11321       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11322       // Visit that expression.
11323       Visit(Base);
11324     }
11325 
11326     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11327       Expr *Callee = E->getCallee();
11328 
11329       if (isa<UnresolvedLookupExpr>(Callee))
11330         return Inherited::VisitCXXOperatorCallExpr(E);
11331 
11332       Visit(Callee);
11333       for (auto Arg: E->arguments())
11334         HandleValue(Arg->IgnoreParenImpCasts());
11335     }
11336 
11337     void VisitUnaryOperator(UnaryOperator *E) {
11338       // For POD record types, addresses of its own members are well-defined.
11339       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11340           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11341         if (!isPODType)
11342           HandleValue(E->getSubExpr());
11343         return;
11344       }
11345 
11346       if (E->isIncrementDecrementOp()) {
11347         HandleValue(E->getSubExpr());
11348         return;
11349       }
11350 
11351       Inherited::VisitUnaryOperator(E);
11352     }
11353 
11354     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11355 
11356     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11357       if (E->getConstructor()->isCopyConstructor()) {
11358         Expr *ArgExpr = E->getArg(0);
11359         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11360           if (ILE->getNumInits() == 1)
11361             ArgExpr = ILE->getInit(0);
11362         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11363           if (ICE->getCastKind() == CK_NoOp)
11364             ArgExpr = ICE->getSubExpr();
11365         HandleValue(ArgExpr);
11366         return;
11367       }
11368       Inherited::VisitCXXConstructExpr(E);
11369     }
11370 
11371     void VisitCallExpr(CallExpr *E) {
11372       // Treat std::move as a use.
11373       if (E->isCallToStdMove()) {
11374         HandleValue(E->getArg(0));
11375         return;
11376       }
11377 
11378       Inherited::VisitCallExpr(E);
11379     }
11380 
11381     void VisitBinaryOperator(BinaryOperator *E) {
11382       if (E->isCompoundAssignmentOp()) {
11383         HandleValue(E->getLHS());
11384         Visit(E->getRHS());
11385         return;
11386       }
11387 
11388       Inherited::VisitBinaryOperator(E);
11389     }
11390 
11391     // A custom visitor for BinaryConditionalOperator is needed because the
11392     // regular visitor would check the condition and true expression separately
11393     // but both point to the same place giving duplicate diagnostics.
11394     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11395       Visit(E->getCond());
11396       Visit(E->getFalseExpr());
11397     }
11398 
11399     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11400       Decl* ReferenceDecl = DRE->getDecl();
11401       if (OrigDecl != ReferenceDecl) return;
11402       unsigned diag;
11403       if (isReferenceType) {
11404         diag = diag::warn_uninit_self_reference_in_reference_init;
11405       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11406         diag = diag::warn_static_self_reference_in_init;
11407       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11408                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11409                  DRE->getDecl()->getType()->isRecordType()) {
11410         diag = diag::warn_uninit_self_reference_in_init;
11411       } else {
11412         // Local variables will be handled by the CFG analysis.
11413         return;
11414       }
11415 
11416       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11417                             S.PDiag(diag)
11418                                 << DRE->getDecl() << OrigDecl->getLocation()
11419                                 << DRE->getSourceRange());
11420     }
11421   };
11422 
11423   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11424   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11425                                  bool DirectInit) {
11426     // Parameters arguments are occassionially constructed with itself,
11427     // for instance, in recursive functions.  Skip them.
11428     if (isa<ParmVarDecl>(OrigDecl))
11429       return;
11430 
11431     E = E->IgnoreParens();
11432 
11433     // Skip checking T a = a where T is not a record or reference type.
11434     // Doing so is a way to silence uninitialized warnings.
11435     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11436       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11437         if (ICE->getCastKind() == CK_LValueToRValue)
11438           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11439             if (DRE->getDecl() == OrigDecl)
11440               return;
11441 
11442     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11443   }
11444 } // end anonymous namespace
11445 
11446 namespace {
11447   // Simple wrapper to add the name of a variable or (if no variable is
11448   // available) a DeclarationName into a diagnostic.
11449   struct VarDeclOrName {
11450     VarDecl *VDecl;
11451     DeclarationName Name;
11452 
11453     friend const Sema::SemaDiagnosticBuilder &
11454     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11455       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11456     }
11457   };
11458 } // end anonymous namespace
11459 
11460 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11461                                             DeclarationName Name, QualType Type,
11462                                             TypeSourceInfo *TSI,
11463                                             SourceRange Range, bool DirectInit,
11464                                             Expr *Init) {
11465   bool IsInitCapture = !VDecl;
11466   assert((!VDecl || !VDecl->isInitCapture()) &&
11467          "init captures are expected to be deduced prior to initialization");
11468 
11469   VarDeclOrName VN{VDecl, Name};
11470 
11471   DeducedType *Deduced = Type->getContainedDeducedType();
11472   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11473 
11474   // C++11 [dcl.spec.auto]p3
11475   if (!Init) {
11476     assert(VDecl && "no init for init capture deduction?");
11477 
11478     // Except for class argument deduction, and then for an initializing
11479     // declaration only, i.e. no static at class scope or extern.
11480     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11481         VDecl->hasExternalStorage() ||
11482         VDecl->isStaticDataMember()) {
11483       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11484         << VDecl->getDeclName() << Type;
11485       return QualType();
11486     }
11487   }
11488 
11489   ArrayRef<Expr*> DeduceInits;
11490   if (Init)
11491     DeduceInits = Init;
11492 
11493   if (DirectInit) {
11494     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11495       DeduceInits = PL->exprs();
11496   }
11497 
11498   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11499     assert(VDecl && "non-auto type for init capture deduction?");
11500     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11501     InitializationKind Kind = InitializationKind::CreateForInit(
11502         VDecl->getLocation(), DirectInit, Init);
11503     // FIXME: Initialization should not be taking a mutable list of inits.
11504     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11505     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11506                                                        InitsCopy);
11507   }
11508 
11509   if (DirectInit) {
11510     if (auto *IL = dyn_cast<InitListExpr>(Init))
11511       DeduceInits = IL->inits();
11512   }
11513 
11514   // Deduction only works if we have exactly one source expression.
11515   if (DeduceInits.empty()) {
11516     // It isn't possible to write this directly, but it is possible to
11517     // end up in this situation with "auto x(some_pack...);"
11518     Diag(Init->getBeginLoc(), IsInitCapture
11519                                   ? diag::err_init_capture_no_expression
11520                                   : diag::err_auto_var_init_no_expression)
11521         << VN << Type << Range;
11522     return QualType();
11523   }
11524 
11525   if (DeduceInits.size() > 1) {
11526     Diag(DeduceInits[1]->getBeginLoc(),
11527          IsInitCapture ? diag::err_init_capture_multiple_expressions
11528                        : diag::err_auto_var_init_multiple_expressions)
11529         << VN << Type << Range;
11530     return QualType();
11531   }
11532 
11533   Expr *DeduceInit = DeduceInits[0];
11534   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11535     Diag(Init->getBeginLoc(), IsInitCapture
11536                                   ? diag::err_init_capture_paren_braces
11537                                   : diag::err_auto_var_init_paren_braces)
11538         << isa<InitListExpr>(Init) << VN << Type << Range;
11539     return QualType();
11540   }
11541 
11542   // Expressions default to 'id' when we're in a debugger.
11543   bool DefaultedAnyToId = false;
11544   if (getLangOpts().DebuggerCastResultToId &&
11545       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11546     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11547     if (Result.isInvalid()) {
11548       return QualType();
11549     }
11550     Init = Result.get();
11551     DefaultedAnyToId = true;
11552   }
11553 
11554   // C++ [dcl.decomp]p1:
11555   //   If the assignment-expression [...] has array type A and no ref-qualifier
11556   //   is present, e has type cv A
11557   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11558       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11559       DeduceInit->getType()->isConstantArrayType())
11560     return Context.getQualifiedType(DeduceInit->getType(),
11561                                     Type.getQualifiers());
11562 
11563   QualType DeducedType;
11564   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11565     if (!IsInitCapture)
11566       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11567     else if (isa<InitListExpr>(Init))
11568       Diag(Range.getBegin(),
11569            diag::err_init_capture_deduction_failure_from_init_list)
11570           << VN
11571           << (DeduceInit->getType().isNull() ? TSI->getType()
11572                                              : DeduceInit->getType())
11573           << DeduceInit->getSourceRange();
11574     else
11575       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11576           << VN << TSI->getType()
11577           << (DeduceInit->getType().isNull() ? TSI->getType()
11578                                              : DeduceInit->getType())
11579           << DeduceInit->getSourceRange();
11580   }
11581 
11582   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11583   // 'id' instead of a specific object type prevents most of our usual
11584   // checks.
11585   // We only want to warn outside of template instantiations, though:
11586   // inside a template, the 'id' could have come from a parameter.
11587   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11588       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11589     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11590     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11591   }
11592 
11593   return DeducedType;
11594 }
11595 
11596 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11597                                          Expr *Init) {
11598   assert(!Init || !Init->containsErrors());
11599   QualType DeducedType = deduceVarTypeFromInitializer(
11600       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11601       VDecl->getSourceRange(), DirectInit, Init);
11602   if (DeducedType.isNull()) {
11603     VDecl->setInvalidDecl();
11604     return true;
11605   }
11606 
11607   VDecl->setType(DeducedType);
11608   assert(VDecl->isLinkageValid());
11609 
11610   // In ARC, infer lifetime.
11611   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11612     VDecl->setInvalidDecl();
11613 
11614   if (getLangOpts().OpenCL)
11615     deduceOpenCLAddressSpace(VDecl);
11616 
11617   // If this is a redeclaration, check that the type we just deduced matches
11618   // the previously declared type.
11619   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11620     // We never need to merge the type, because we cannot form an incomplete
11621     // array of auto, nor deduce such a type.
11622     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11623   }
11624 
11625   // Check the deduced type is valid for a variable declaration.
11626   CheckVariableDeclarationType(VDecl);
11627   return VDecl->isInvalidDecl();
11628 }
11629 
11630 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11631                                               SourceLocation Loc) {
11632   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11633     Init = EWC->getSubExpr();
11634 
11635   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11636     Init = CE->getSubExpr();
11637 
11638   QualType InitType = Init->getType();
11639   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11640           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11641          "shouldn't be called if type doesn't have a non-trivial C struct");
11642   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11643     for (auto I : ILE->inits()) {
11644       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11645           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11646         continue;
11647       SourceLocation SL = I->getExprLoc();
11648       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11649     }
11650     return;
11651   }
11652 
11653   if (isa<ImplicitValueInitExpr>(Init)) {
11654     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11655       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11656                             NTCUK_Init);
11657   } else {
11658     // Assume all other explicit initializers involving copying some existing
11659     // object.
11660     // TODO: ignore any explicit initializers where we can guarantee
11661     // copy-elision.
11662     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11663       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11664   }
11665 }
11666 
11667 namespace {
11668 
11669 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11670   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11671   // in the source code or implicitly by the compiler if it is in a union
11672   // defined in a system header and has non-trivial ObjC ownership
11673   // qualifications. We don't want those fields to participate in determining
11674   // whether the containing union is non-trivial.
11675   return FD->hasAttr<UnavailableAttr>();
11676 }
11677 
11678 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11679     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11680                                     void> {
11681   using Super =
11682       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11683                                     void>;
11684 
11685   DiagNonTrivalCUnionDefaultInitializeVisitor(
11686       QualType OrigTy, SourceLocation OrigLoc,
11687       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11688       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11689 
11690   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11691                      const FieldDecl *FD, bool InNonTrivialUnion) {
11692     if (const auto *AT = S.Context.getAsArrayType(QT))
11693       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11694                                      InNonTrivialUnion);
11695     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11696   }
11697 
11698   void visitARCStrong(QualType QT, const FieldDecl *FD,
11699                       bool InNonTrivialUnion) {
11700     if (InNonTrivialUnion)
11701       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11702           << 1 << 0 << QT << FD->getName();
11703   }
11704 
11705   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11706     if (InNonTrivialUnion)
11707       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11708           << 1 << 0 << QT << FD->getName();
11709   }
11710 
11711   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11712     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11713     if (RD->isUnion()) {
11714       if (OrigLoc.isValid()) {
11715         bool IsUnion = false;
11716         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11717           IsUnion = OrigRD->isUnion();
11718         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11719             << 0 << OrigTy << IsUnion << UseContext;
11720         // Reset OrigLoc so that this diagnostic is emitted only once.
11721         OrigLoc = SourceLocation();
11722       }
11723       InNonTrivialUnion = true;
11724     }
11725 
11726     if (InNonTrivialUnion)
11727       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11728           << 0 << 0 << QT.getUnqualifiedType() << "";
11729 
11730     for (const FieldDecl *FD : RD->fields())
11731       if (!shouldIgnoreForRecordTriviality(FD))
11732         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11733   }
11734 
11735   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11736 
11737   // The non-trivial C union type or the struct/union type that contains a
11738   // non-trivial C union.
11739   QualType OrigTy;
11740   SourceLocation OrigLoc;
11741   Sema::NonTrivialCUnionContext UseContext;
11742   Sema &S;
11743 };
11744 
11745 struct DiagNonTrivalCUnionDestructedTypeVisitor
11746     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11747   using Super =
11748       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11749 
11750   DiagNonTrivalCUnionDestructedTypeVisitor(
11751       QualType OrigTy, SourceLocation OrigLoc,
11752       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11753       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11754 
11755   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11756                      const FieldDecl *FD, bool InNonTrivialUnion) {
11757     if (const auto *AT = S.Context.getAsArrayType(QT))
11758       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11759                                      InNonTrivialUnion);
11760     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11761   }
11762 
11763   void visitARCStrong(QualType QT, const FieldDecl *FD,
11764                       bool InNonTrivialUnion) {
11765     if (InNonTrivialUnion)
11766       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11767           << 1 << 1 << QT << FD->getName();
11768   }
11769 
11770   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11771     if (InNonTrivialUnion)
11772       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11773           << 1 << 1 << QT << FD->getName();
11774   }
11775 
11776   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11777     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11778     if (RD->isUnion()) {
11779       if (OrigLoc.isValid()) {
11780         bool IsUnion = false;
11781         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11782           IsUnion = OrigRD->isUnion();
11783         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11784             << 1 << OrigTy << IsUnion << UseContext;
11785         // Reset OrigLoc so that this diagnostic is emitted only once.
11786         OrigLoc = SourceLocation();
11787       }
11788       InNonTrivialUnion = true;
11789     }
11790 
11791     if (InNonTrivialUnion)
11792       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11793           << 0 << 1 << QT.getUnqualifiedType() << "";
11794 
11795     for (const FieldDecl *FD : RD->fields())
11796       if (!shouldIgnoreForRecordTriviality(FD))
11797         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11798   }
11799 
11800   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11801   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11802                           bool InNonTrivialUnion) {}
11803 
11804   // The non-trivial C union type or the struct/union type that contains a
11805   // non-trivial C union.
11806   QualType OrigTy;
11807   SourceLocation OrigLoc;
11808   Sema::NonTrivialCUnionContext UseContext;
11809   Sema &S;
11810 };
11811 
11812 struct DiagNonTrivalCUnionCopyVisitor
11813     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11814   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11815 
11816   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11817                                  Sema::NonTrivialCUnionContext UseContext,
11818                                  Sema &S)
11819       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11820 
11821   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11822                      const FieldDecl *FD, bool InNonTrivialUnion) {
11823     if (const auto *AT = S.Context.getAsArrayType(QT))
11824       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11825                                      InNonTrivialUnion);
11826     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11827   }
11828 
11829   void visitARCStrong(QualType QT, const FieldDecl *FD,
11830                       bool InNonTrivialUnion) {
11831     if (InNonTrivialUnion)
11832       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11833           << 1 << 2 << QT << FD->getName();
11834   }
11835 
11836   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11837     if (InNonTrivialUnion)
11838       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11839           << 1 << 2 << QT << FD->getName();
11840   }
11841 
11842   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11843     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11844     if (RD->isUnion()) {
11845       if (OrigLoc.isValid()) {
11846         bool IsUnion = false;
11847         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11848           IsUnion = OrigRD->isUnion();
11849         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11850             << 2 << OrigTy << IsUnion << UseContext;
11851         // Reset OrigLoc so that this diagnostic is emitted only once.
11852         OrigLoc = SourceLocation();
11853       }
11854       InNonTrivialUnion = true;
11855     }
11856 
11857     if (InNonTrivialUnion)
11858       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11859           << 0 << 2 << QT.getUnqualifiedType() << "";
11860 
11861     for (const FieldDecl *FD : RD->fields())
11862       if (!shouldIgnoreForRecordTriviality(FD))
11863         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11864   }
11865 
11866   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11867                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11868   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11869   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11870                             bool InNonTrivialUnion) {}
11871 
11872   // The non-trivial C union type or the struct/union type that contains a
11873   // non-trivial C union.
11874   QualType OrigTy;
11875   SourceLocation OrigLoc;
11876   Sema::NonTrivialCUnionContext UseContext;
11877   Sema &S;
11878 };
11879 
11880 } // namespace
11881 
11882 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11883                                  NonTrivialCUnionContext UseContext,
11884                                  unsigned NonTrivialKind) {
11885   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11886           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11887           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11888          "shouldn't be called if type doesn't have a non-trivial C union");
11889 
11890   if ((NonTrivialKind & NTCUK_Init) &&
11891       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11892     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11893         .visit(QT, nullptr, false);
11894   if ((NonTrivialKind & NTCUK_Destruct) &&
11895       QT.hasNonTrivialToPrimitiveDestructCUnion())
11896     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11897         .visit(QT, nullptr, false);
11898   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11899     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11900         .visit(QT, nullptr, false);
11901 }
11902 
11903 /// AddInitializerToDecl - Adds the initializer Init to the
11904 /// declaration dcl. If DirectInit is true, this is C++ direct
11905 /// initialization rather than copy initialization.
11906 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11907   // If there is no declaration, there was an error parsing it.  Just ignore
11908   // the initializer.
11909   if (!RealDecl || RealDecl->isInvalidDecl()) {
11910     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11911     return;
11912   }
11913 
11914   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11915     // Pure-specifiers are handled in ActOnPureSpecifier.
11916     Diag(Method->getLocation(), diag::err_member_function_initialization)
11917       << Method->getDeclName() << Init->getSourceRange();
11918     Method->setInvalidDecl();
11919     return;
11920   }
11921 
11922   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11923   if (!VDecl) {
11924     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11925     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11926     RealDecl->setInvalidDecl();
11927     return;
11928   }
11929 
11930   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11931   if (VDecl->getType()->isUndeducedType()) {
11932     // Attempt typo correction early so that the type of the init expression can
11933     // be deduced based on the chosen correction if the original init contains a
11934     // TypoExpr.
11935     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11936     if (!Res.isUsable()) {
11937       // There are unresolved typos in Init, just drop them.
11938       // FIXME: improve the recovery strategy to preserve the Init.
11939       RealDecl->setInvalidDecl();
11940       return;
11941     }
11942     if (Res.get()->containsErrors()) {
11943       // Invalidate the decl as we don't know the type for recovery-expr yet.
11944       RealDecl->setInvalidDecl();
11945       VDecl->setInit(Res.get());
11946       return;
11947     }
11948     Init = Res.get();
11949 
11950     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11951       return;
11952   }
11953 
11954   // dllimport cannot be used on variable definitions.
11955   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11956     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11957     VDecl->setInvalidDecl();
11958     return;
11959   }
11960 
11961   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11962     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11963     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11964     VDecl->setInvalidDecl();
11965     return;
11966   }
11967 
11968   if (!VDecl->getType()->isDependentType()) {
11969     // A definition must end up with a complete type, which means it must be
11970     // complete with the restriction that an array type might be completed by
11971     // the initializer; note that later code assumes this restriction.
11972     QualType BaseDeclType = VDecl->getType();
11973     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11974       BaseDeclType = Array->getElementType();
11975     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11976                             diag::err_typecheck_decl_incomplete_type)) {
11977       RealDecl->setInvalidDecl();
11978       return;
11979     }
11980 
11981     // The variable can not have an abstract class type.
11982     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11983                                diag::err_abstract_type_in_decl,
11984                                AbstractVariableType))
11985       VDecl->setInvalidDecl();
11986   }
11987 
11988   // If adding the initializer will turn this declaration into a definition,
11989   // and we already have a definition for this variable, diagnose or otherwise
11990   // handle the situation.
11991   VarDecl *Def;
11992   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11993       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11994       !VDecl->isThisDeclarationADemotedDefinition() &&
11995       checkVarDeclRedefinition(Def, VDecl))
11996     return;
11997 
11998   if (getLangOpts().CPlusPlus) {
11999     // C++ [class.static.data]p4
12000     //   If a static data member is of const integral or const
12001     //   enumeration type, its declaration in the class definition can
12002     //   specify a constant-initializer which shall be an integral
12003     //   constant expression (5.19). In that case, the member can appear
12004     //   in integral constant expressions. The member shall still be
12005     //   defined in a namespace scope if it is used in the program and the
12006     //   namespace scope definition shall not contain an initializer.
12007     //
12008     // We already performed a redefinition check above, but for static
12009     // data members we also need to check whether there was an in-class
12010     // declaration with an initializer.
12011     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12012       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12013           << VDecl->getDeclName();
12014       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12015            diag::note_previous_initializer)
12016           << 0;
12017       return;
12018     }
12019 
12020     if (VDecl->hasLocalStorage())
12021       setFunctionHasBranchProtectedScope();
12022 
12023     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12024       VDecl->setInvalidDecl();
12025       return;
12026     }
12027   }
12028 
12029   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12030   // a kernel function cannot be initialized."
12031   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12032     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12033     VDecl->setInvalidDecl();
12034     return;
12035   }
12036 
12037   // The LoaderUninitialized attribute acts as a definition (of undef).
12038   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12039     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12040     VDecl->setInvalidDecl();
12041     return;
12042   }
12043 
12044   // Get the decls type and save a reference for later, since
12045   // CheckInitializerTypes may change it.
12046   QualType DclT = VDecl->getType(), SavT = DclT;
12047 
12048   // Expressions default to 'id' when we're in a debugger
12049   // and we are assigning it to a variable of Objective-C pointer type.
12050   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12051       Init->getType() == Context.UnknownAnyTy) {
12052     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12053     if (Result.isInvalid()) {
12054       VDecl->setInvalidDecl();
12055       return;
12056     }
12057     Init = Result.get();
12058   }
12059 
12060   // Perform the initialization.
12061   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12062   if (!VDecl->isInvalidDecl()) {
12063     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12064     InitializationKind Kind = InitializationKind::CreateForInit(
12065         VDecl->getLocation(), DirectInit, Init);
12066 
12067     MultiExprArg Args = Init;
12068     if (CXXDirectInit)
12069       Args = MultiExprArg(CXXDirectInit->getExprs(),
12070                           CXXDirectInit->getNumExprs());
12071 
12072     // Try to correct any TypoExprs in the initialization arguments.
12073     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12074       ExprResult Res = CorrectDelayedTyposInExpr(
12075           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12076           [this, Entity, Kind](Expr *E) {
12077             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12078             return Init.Failed() ? ExprError() : E;
12079           });
12080       if (Res.isInvalid()) {
12081         VDecl->setInvalidDecl();
12082       } else if (Res.get() != Args[Idx]) {
12083         Args[Idx] = Res.get();
12084       }
12085     }
12086     if (VDecl->isInvalidDecl())
12087       return;
12088 
12089     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12090                                    /*TopLevelOfInitList=*/false,
12091                                    /*TreatUnavailableAsInvalid=*/false);
12092     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12093     if (Result.isInvalid()) {
12094       // If the provied initializer fails to initialize the var decl,
12095       // we attach a recovery expr for better recovery.
12096       auto RecoveryExpr =
12097           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12098       if (RecoveryExpr.get())
12099         VDecl->setInit(RecoveryExpr.get());
12100       return;
12101     }
12102 
12103     Init = Result.getAs<Expr>();
12104   }
12105 
12106   // Check for self-references within variable initializers.
12107   // Variables declared within a function/method body (except for references)
12108   // are handled by a dataflow analysis.
12109   // This is undefined behavior in C++, but valid in C.
12110   if (getLangOpts().CPlusPlus) {
12111     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12112         VDecl->getType()->isReferenceType()) {
12113       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12114     }
12115   }
12116 
12117   // If the type changed, it means we had an incomplete type that was
12118   // completed by the initializer. For example:
12119   //   int ary[] = { 1, 3, 5 };
12120   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12121   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12122     VDecl->setType(DclT);
12123 
12124   if (!VDecl->isInvalidDecl()) {
12125     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12126 
12127     if (VDecl->hasAttr<BlocksAttr>())
12128       checkRetainCycles(VDecl, Init);
12129 
12130     // It is safe to assign a weak reference into a strong variable.
12131     // Although this code can still have problems:
12132     //   id x = self.weakProp;
12133     //   id y = self.weakProp;
12134     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12135     // paths through the function. This should be revisited if
12136     // -Wrepeated-use-of-weak is made flow-sensitive.
12137     if (FunctionScopeInfo *FSI = getCurFunction())
12138       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12139            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12140           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12141                            Init->getBeginLoc()))
12142         FSI->markSafeWeakUse(Init);
12143   }
12144 
12145   // The initialization is usually a full-expression.
12146   //
12147   // FIXME: If this is a braced initialization of an aggregate, it is not
12148   // an expression, and each individual field initializer is a separate
12149   // full-expression. For instance, in:
12150   //
12151   //   struct Temp { ~Temp(); };
12152   //   struct S { S(Temp); };
12153   //   struct T { S a, b; } t = { Temp(), Temp() }
12154   //
12155   // we should destroy the first Temp before constructing the second.
12156   ExprResult Result =
12157       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12158                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12159   if (Result.isInvalid()) {
12160     VDecl->setInvalidDecl();
12161     return;
12162   }
12163   Init = Result.get();
12164 
12165   // Attach the initializer to the decl.
12166   VDecl->setInit(Init);
12167 
12168   if (VDecl->isLocalVarDecl()) {
12169     // Don't check the initializer if the declaration is malformed.
12170     if (VDecl->isInvalidDecl()) {
12171       // do nothing
12172 
12173     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12174     // This is true even in C++ for OpenCL.
12175     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12176       CheckForConstantInitializer(Init, DclT);
12177 
12178     // Otherwise, C++ does not restrict the initializer.
12179     } else if (getLangOpts().CPlusPlus) {
12180       // do nothing
12181 
12182     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12183     // static storage duration shall be constant expressions or string literals.
12184     } else if (VDecl->getStorageClass() == SC_Static) {
12185       CheckForConstantInitializer(Init, DclT);
12186 
12187     // C89 is stricter than C99 for aggregate initializers.
12188     // C89 6.5.7p3: All the expressions [...] in an initializer list
12189     // for an object that has aggregate or union type shall be
12190     // constant expressions.
12191     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12192                isa<InitListExpr>(Init)) {
12193       const Expr *Culprit;
12194       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12195         Diag(Culprit->getExprLoc(),
12196              diag::ext_aggregate_init_not_constant)
12197           << Culprit->getSourceRange();
12198       }
12199     }
12200 
12201     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12202       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12203         if (VDecl->hasLocalStorage())
12204           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12205   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12206              VDecl->getLexicalDeclContext()->isRecord()) {
12207     // This is an in-class initialization for a static data member, e.g.,
12208     //
12209     // struct S {
12210     //   static const int value = 17;
12211     // };
12212 
12213     // C++ [class.mem]p4:
12214     //   A member-declarator can contain a constant-initializer only
12215     //   if it declares a static member (9.4) of const integral or
12216     //   const enumeration type, see 9.4.2.
12217     //
12218     // C++11 [class.static.data]p3:
12219     //   If a non-volatile non-inline const static data member is of integral
12220     //   or enumeration type, its declaration in the class definition can
12221     //   specify a brace-or-equal-initializer in which every initializer-clause
12222     //   that is an assignment-expression is a constant expression. A static
12223     //   data member of literal type can be declared in the class definition
12224     //   with the constexpr specifier; if so, its declaration shall specify a
12225     //   brace-or-equal-initializer in which every initializer-clause that is
12226     //   an assignment-expression is a constant expression.
12227 
12228     // Do nothing on dependent types.
12229     if (DclT->isDependentType()) {
12230 
12231     // Allow any 'static constexpr' members, whether or not they are of literal
12232     // type. We separately check that every constexpr variable is of literal
12233     // type.
12234     } else if (VDecl->isConstexpr()) {
12235 
12236     // Require constness.
12237     } else if (!DclT.isConstQualified()) {
12238       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12239         << Init->getSourceRange();
12240       VDecl->setInvalidDecl();
12241 
12242     // We allow integer constant expressions in all cases.
12243     } else if (DclT->isIntegralOrEnumerationType()) {
12244       // Check whether the expression is a constant expression.
12245       SourceLocation Loc;
12246       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12247         // In C++11, a non-constexpr const static data member with an
12248         // in-class initializer cannot be volatile.
12249         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12250       else if (Init->isValueDependent())
12251         ; // Nothing to check.
12252       else if (Init->isIntegerConstantExpr(Context, &Loc))
12253         ; // Ok, it's an ICE!
12254       else if (Init->getType()->isScopedEnumeralType() &&
12255                Init->isCXX11ConstantExpr(Context))
12256         ; // Ok, it is a scoped-enum constant expression.
12257       else if (Init->isEvaluatable(Context)) {
12258         // If we can constant fold the initializer through heroics, accept it,
12259         // but report this as a use of an extension for -pedantic.
12260         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12261           << Init->getSourceRange();
12262       } else {
12263         // Otherwise, this is some crazy unknown case.  Report the issue at the
12264         // location provided by the isIntegerConstantExpr failed check.
12265         Diag(Loc, diag::err_in_class_initializer_non_constant)
12266           << Init->getSourceRange();
12267         VDecl->setInvalidDecl();
12268       }
12269 
12270     // We allow foldable floating-point constants as an extension.
12271     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12272       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12273       // it anyway and provide a fixit to add the 'constexpr'.
12274       if (getLangOpts().CPlusPlus11) {
12275         Diag(VDecl->getLocation(),
12276              diag::ext_in_class_initializer_float_type_cxx11)
12277             << DclT << Init->getSourceRange();
12278         Diag(VDecl->getBeginLoc(),
12279              diag::note_in_class_initializer_float_type_cxx11)
12280             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12281       } else {
12282         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12283           << DclT << Init->getSourceRange();
12284 
12285         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12286           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12287             << Init->getSourceRange();
12288           VDecl->setInvalidDecl();
12289         }
12290       }
12291 
12292     // Suggest adding 'constexpr' in C++11 for literal types.
12293     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12294       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12295           << DclT << Init->getSourceRange()
12296           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12297       VDecl->setConstexpr(true);
12298 
12299     } else {
12300       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12301         << DclT << Init->getSourceRange();
12302       VDecl->setInvalidDecl();
12303     }
12304   } else if (VDecl->isFileVarDecl()) {
12305     // In C, extern is typically used to avoid tentative definitions when
12306     // declaring variables in headers, but adding an intializer makes it a
12307     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12308     // In C++, extern is often used to give implictly static const variables
12309     // external linkage, so don't warn in that case. If selectany is present,
12310     // this might be header code intended for C and C++ inclusion, so apply the
12311     // C++ rules.
12312     if (VDecl->getStorageClass() == SC_Extern &&
12313         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12314          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12315         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12316         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12317       Diag(VDecl->getLocation(), diag::warn_extern_init);
12318 
12319     // In Microsoft C++ mode, a const variable defined in namespace scope has
12320     // external linkage by default if the variable is declared with
12321     // __declspec(dllexport).
12322     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12323         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12324         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12325       VDecl->setStorageClass(SC_Extern);
12326 
12327     // C99 6.7.8p4. All file scoped initializers need to be constant.
12328     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12329       CheckForConstantInitializer(Init, DclT);
12330   }
12331 
12332   QualType InitType = Init->getType();
12333   if (!InitType.isNull() &&
12334       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12335        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12336     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12337 
12338   // We will represent direct-initialization similarly to copy-initialization:
12339   //    int x(1);  -as-> int x = 1;
12340   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12341   //
12342   // Clients that want to distinguish between the two forms, can check for
12343   // direct initializer using VarDecl::getInitStyle().
12344   // A major benefit is that clients that don't particularly care about which
12345   // exactly form was it (like the CodeGen) can handle both cases without
12346   // special case code.
12347 
12348   // C++ 8.5p11:
12349   // The form of initialization (using parentheses or '=') is generally
12350   // insignificant, but does matter when the entity being initialized has a
12351   // class type.
12352   if (CXXDirectInit) {
12353     assert(DirectInit && "Call-style initializer must be direct init.");
12354     VDecl->setInitStyle(VarDecl::CallInit);
12355   } else if (DirectInit) {
12356     // This must be list-initialization. No other way is direct-initialization.
12357     VDecl->setInitStyle(VarDecl::ListInit);
12358   }
12359 
12360   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12361     DeclsToCheckForDeferredDiags.push_back(VDecl);
12362   CheckCompleteVariableDeclaration(VDecl);
12363 }
12364 
12365 /// ActOnInitializerError - Given that there was an error parsing an
12366 /// initializer for the given declaration, try to return to some form
12367 /// of sanity.
12368 void Sema::ActOnInitializerError(Decl *D) {
12369   // Our main concern here is re-establishing invariants like "a
12370   // variable's type is either dependent or complete".
12371   if (!D || D->isInvalidDecl()) return;
12372 
12373   VarDecl *VD = dyn_cast<VarDecl>(D);
12374   if (!VD) return;
12375 
12376   // Bindings are not usable if we can't make sense of the initializer.
12377   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12378     for (auto *BD : DD->bindings())
12379       BD->setInvalidDecl();
12380 
12381   // Auto types are meaningless if we can't make sense of the initializer.
12382   if (VD->getType()->isUndeducedType()) {
12383     D->setInvalidDecl();
12384     return;
12385   }
12386 
12387   QualType Ty = VD->getType();
12388   if (Ty->isDependentType()) return;
12389 
12390   // Require a complete type.
12391   if (RequireCompleteType(VD->getLocation(),
12392                           Context.getBaseElementType(Ty),
12393                           diag::err_typecheck_decl_incomplete_type)) {
12394     VD->setInvalidDecl();
12395     return;
12396   }
12397 
12398   // Require a non-abstract type.
12399   if (RequireNonAbstractType(VD->getLocation(), Ty,
12400                              diag::err_abstract_type_in_decl,
12401                              AbstractVariableType)) {
12402     VD->setInvalidDecl();
12403     return;
12404   }
12405 
12406   // Don't bother complaining about constructors or destructors,
12407   // though.
12408 }
12409 
12410 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12411   // If there is no declaration, there was an error parsing it. Just ignore it.
12412   if (!RealDecl)
12413     return;
12414 
12415   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12416     QualType Type = Var->getType();
12417 
12418     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12419     if (isa<DecompositionDecl>(RealDecl)) {
12420       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12421       Var->setInvalidDecl();
12422       return;
12423     }
12424 
12425     if (Type->isUndeducedType() &&
12426         DeduceVariableDeclarationType(Var, false, nullptr))
12427       return;
12428 
12429     // C++11 [class.static.data]p3: A static data member can be declared with
12430     // the constexpr specifier; if so, its declaration shall specify
12431     // a brace-or-equal-initializer.
12432     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12433     // the definition of a variable [...] or the declaration of a static data
12434     // member.
12435     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12436         !Var->isThisDeclarationADemotedDefinition()) {
12437       if (Var->isStaticDataMember()) {
12438         // C++1z removes the relevant rule; the in-class declaration is always
12439         // a definition there.
12440         if (!getLangOpts().CPlusPlus17 &&
12441             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12442           Diag(Var->getLocation(),
12443                diag::err_constexpr_static_mem_var_requires_init)
12444               << Var;
12445           Var->setInvalidDecl();
12446           return;
12447         }
12448       } else {
12449         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12450         Var->setInvalidDecl();
12451         return;
12452       }
12453     }
12454 
12455     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12456     // be initialized.
12457     if (!Var->isInvalidDecl() &&
12458         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12459         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12460       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12461       Var->setInvalidDecl();
12462       return;
12463     }
12464 
12465     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12466       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12467         if (!RD->hasTrivialDefaultConstructor()) {
12468           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12469           Var->setInvalidDecl();
12470           return;
12471         }
12472       }
12473       if (Var->getStorageClass() == SC_Extern) {
12474         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12475             << Var;
12476         Var->setInvalidDecl();
12477         return;
12478       }
12479     }
12480 
12481     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12482     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12483         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12484       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12485                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12486 
12487 
12488     switch (DefKind) {
12489     case VarDecl::Definition:
12490       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12491         break;
12492 
12493       // We have an out-of-line definition of a static data member
12494       // that has an in-class initializer, so we type-check this like
12495       // a declaration.
12496       //
12497       LLVM_FALLTHROUGH;
12498 
12499     case VarDecl::DeclarationOnly:
12500       // It's only a declaration.
12501 
12502       // Block scope. C99 6.7p7: If an identifier for an object is
12503       // declared with no linkage (C99 6.2.2p6), the type for the
12504       // object shall be complete.
12505       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12506           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12507           RequireCompleteType(Var->getLocation(), Type,
12508                               diag::err_typecheck_decl_incomplete_type))
12509         Var->setInvalidDecl();
12510 
12511       // Make sure that the type is not abstract.
12512       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12513           RequireNonAbstractType(Var->getLocation(), Type,
12514                                  diag::err_abstract_type_in_decl,
12515                                  AbstractVariableType))
12516         Var->setInvalidDecl();
12517       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12518           Var->getStorageClass() == SC_PrivateExtern) {
12519         Diag(Var->getLocation(), diag::warn_private_extern);
12520         Diag(Var->getLocation(), diag::note_private_extern);
12521       }
12522 
12523       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12524           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12525         ExternalDeclarations.push_back(Var);
12526 
12527       return;
12528 
12529     case VarDecl::TentativeDefinition:
12530       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12531       // object that has file scope without an initializer, and without a
12532       // storage-class specifier or with the storage-class specifier "static",
12533       // constitutes a tentative definition. Note: A tentative definition with
12534       // external linkage is valid (C99 6.2.2p5).
12535       if (!Var->isInvalidDecl()) {
12536         if (const IncompleteArrayType *ArrayT
12537                                     = Context.getAsIncompleteArrayType(Type)) {
12538           if (RequireCompleteSizedType(
12539                   Var->getLocation(), ArrayT->getElementType(),
12540                   diag::err_array_incomplete_or_sizeless_type))
12541             Var->setInvalidDecl();
12542         } else if (Var->getStorageClass() == SC_Static) {
12543           // C99 6.9.2p3: If the declaration of an identifier for an object is
12544           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12545           // declared type shall not be an incomplete type.
12546           // NOTE: code such as the following
12547           //     static struct s;
12548           //     struct s { int a; };
12549           // is accepted by gcc. Hence here we issue a warning instead of
12550           // an error and we do not invalidate the static declaration.
12551           // NOTE: to avoid multiple warnings, only check the first declaration.
12552           if (Var->isFirstDecl())
12553             RequireCompleteType(Var->getLocation(), Type,
12554                                 diag::ext_typecheck_decl_incomplete_type);
12555         }
12556       }
12557 
12558       // Record the tentative definition; we're done.
12559       if (!Var->isInvalidDecl())
12560         TentativeDefinitions.push_back(Var);
12561       return;
12562     }
12563 
12564     // Provide a specific diagnostic for uninitialized variable
12565     // definitions with incomplete array type.
12566     if (Type->isIncompleteArrayType()) {
12567       Diag(Var->getLocation(),
12568            diag::err_typecheck_incomplete_array_needs_initializer);
12569       Var->setInvalidDecl();
12570       return;
12571     }
12572 
12573     // Provide a specific diagnostic for uninitialized variable
12574     // definitions with reference type.
12575     if (Type->isReferenceType()) {
12576       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12577           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12578       Var->setInvalidDecl();
12579       return;
12580     }
12581 
12582     // Do not attempt to type-check the default initializer for a
12583     // variable with dependent type.
12584     if (Type->isDependentType())
12585       return;
12586 
12587     if (Var->isInvalidDecl())
12588       return;
12589 
12590     if (!Var->hasAttr<AliasAttr>()) {
12591       if (RequireCompleteType(Var->getLocation(),
12592                               Context.getBaseElementType(Type),
12593                               diag::err_typecheck_decl_incomplete_type)) {
12594         Var->setInvalidDecl();
12595         return;
12596       }
12597     } else {
12598       return;
12599     }
12600 
12601     // The variable can not have an abstract class type.
12602     if (RequireNonAbstractType(Var->getLocation(), Type,
12603                                diag::err_abstract_type_in_decl,
12604                                AbstractVariableType)) {
12605       Var->setInvalidDecl();
12606       return;
12607     }
12608 
12609     // Check for jumps past the implicit initializer.  C++0x
12610     // clarifies that this applies to a "variable with automatic
12611     // storage duration", not a "local variable".
12612     // C++11 [stmt.dcl]p3
12613     //   A program that jumps from a point where a variable with automatic
12614     //   storage duration is not in scope to a point where it is in scope is
12615     //   ill-formed unless the variable has scalar type, class type with a
12616     //   trivial default constructor and a trivial destructor, a cv-qualified
12617     //   version of one of these types, or an array of one of the preceding
12618     //   types and is declared without an initializer.
12619     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12620       if (const RecordType *Record
12621             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12622         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12623         // Mark the function (if we're in one) for further checking even if the
12624         // looser rules of C++11 do not require such checks, so that we can
12625         // diagnose incompatibilities with C++98.
12626         if (!CXXRecord->isPOD())
12627           setFunctionHasBranchProtectedScope();
12628       }
12629     }
12630     // In OpenCL, we can't initialize objects in the __local address space,
12631     // even implicitly, so don't synthesize an implicit initializer.
12632     if (getLangOpts().OpenCL &&
12633         Var->getType().getAddressSpace() == LangAS::opencl_local)
12634       return;
12635     // C++03 [dcl.init]p9:
12636     //   If no initializer is specified for an object, and the
12637     //   object is of (possibly cv-qualified) non-POD class type (or
12638     //   array thereof), the object shall be default-initialized; if
12639     //   the object is of const-qualified type, the underlying class
12640     //   type shall have a user-declared default
12641     //   constructor. Otherwise, if no initializer is specified for
12642     //   a non- static object, the object and its subobjects, if
12643     //   any, have an indeterminate initial value); if the object
12644     //   or any of its subobjects are of const-qualified type, the
12645     //   program is ill-formed.
12646     // C++0x [dcl.init]p11:
12647     //   If no initializer is specified for an object, the object is
12648     //   default-initialized; [...].
12649     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12650     InitializationKind Kind
12651       = InitializationKind::CreateDefault(Var->getLocation());
12652 
12653     InitializationSequence InitSeq(*this, Entity, Kind, None);
12654     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12655 
12656     if (Init.get()) {
12657       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12658       // This is important for template substitution.
12659       Var->setInitStyle(VarDecl::CallInit);
12660     } else if (Init.isInvalid()) {
12661       // If default-init fails, attach a recovery-expr initializer to track
12662       // that initialization was attempted and failed.
12663       auto RecoveryExpr =
12664           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12665       if (RecoveryExpr.get())
12666         Var->setInit(RecoveryExpr.get());
12667     }
12668 
12669     CheckCompleteVariableDeclaration(Var);
12670   }
12671 }
12672 
12673 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12674   // If there is no declaration, there was an error parsing it. Ignore it.
12675   if (!D)
12676     return;
12677 
12678   VarDecl *VD = dyn_cast<VarDecl>(D);
12679   if (!VD) {
12680     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12681     D->setInvalidDecl();
12682     return;
12683   }
12684 
12685   VD->setCXXForRangeDecl(true);
12686 
12687   // for-range-declaration cannot be given a storage class specifier.
12688   int Error = -1;
12689   switch (VD->getStorageClass()) {
12690   case SC_None:
12691     break;
12692   case SC_Extern:
12693     Error = 0;
12694     break;
12695   case SC_Static:
12696     Error = 1;
12697     break;
12698   case SC_PrivateExtern:
12699     Error = 2;
12700     break;
12701   case SC_Auto:
12702     Error = 3;
12703     break;
12704   case SC_Register:
12705     Error = 4;
12706     break;
12707   }
12708   if (Error != -1) {
12709     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12710         << VD << Error;
12711     D->setInvalidDecl();
12712   }
12713 }
12714 
12715 StmtResult
12716 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12717                                  IdentifierInfo *Ident,
12718                                  ParsedAttributes &Attrs,
12719                                  SourceLocation AttrEnd) {
12720   // C++1y [stmt.iter]p1:
12721   //   A range-based for statement of the form
12722   //      for ( for-range-identifier : for-range-initializer ) statement
12723   //   is equivalent to
12724   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12725   DeclSpec DS(Attrs.getPool().getFactory());
12726 
12727   const char *PrevSpec;
12728   unsigned DiagID;
12729   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12730                      getPrintingPolicy());
12731 
12732   Declarator D(DS, DeclaratorContext::ForContext);
12733   D.SetIdentifier(Ident, IdentLoc);
12734   D.takeAttributes(Attrs, AttrEnd);
12735 
12736   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12737                 IdentLoc);
12738   Decl *Var = ActOnDeclarator(S, D);
12739   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12740   FinalizeDeclaration(Var);
12741   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12742                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12743 }
12744 
12745 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12746   if (var->isInvalidDecl()) return;
12747 
12748   if (getLangOpts().OpenCL) {
12749     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12750     // initialiser
12751     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12752         !var->hasInit()) {
12753       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12754           << 1 /*Init*/;
12755       var->setInvalidDecl();
12756       return;
12757     }
12758   }
12759 
12760   // In Objective-C, don't allow jumps past the implicit initialization of a
12761   // local retaining variable.
12762   if (getLangOpts().ObjC &&
12763       var->hasLocalStorage()) {
12764     switch (var->getType().getObjCLifetime()) {
12765     case Qualifiers::OCL_None:
12766     case Qualifiers::OCL_ExplicitNone:
12767     case Qualifiers::OCL_Autoreleasing:
12768       break;
12769 
12770     case Qualifiers::OCL_Weak:
12771     case Qualifiers::OCL_Strong:
12772       setFunctionHasBranchProtectedScope();
12773       break;
12774     }
12775   }
12776 
12777   if (var->hasLocalStorage() &&
12778       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12779     setFunctionHasBranchProtectedScope();
12780 
12781   // Warn about externally-visible variables being defined without a
12782   // prior declaration.  We only want to do this for global
12783   // declarations, but we also specifically need to avoid doing it for
12784   // class members because the linkage of an anonymous class can
12785   // change if it's later given a typedef name.
12786   if (var->isThisDeclarationADefinition() &&
12787       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12788       var->isExternallyVisible() && var->hasLinkage() &&
12789       !var->isInline() && !var->getDescribedVarTemplate() &&
12790       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12791       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12792       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12793                                   var->getLocation())) {
12794     // Find a previous declaration that's not a definition.
12795     VarDecl *prev = var->getPreviousDecl();
12796     while (prev && prev->isThisDeclarationADefinition())
12797       prev = prev->getPreviousDecl();
12798 
12799     if (!prev) {
12800       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12801       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12802           << /* variable */ 0;
12803     }
12804   }
12805 
12806   // Cache the result of checking for constant initialization.
12807   Optional<bool> CacheHasConstInit;
12808   const Expr *CacheCulprit = nullptr;
12809   auto checkConstInit = [&]() mutable {
12810     if (!CacheHasConstInit)
12811       CacheHasConstInit = var->getInit()->isConstantInitializer(
12812             Context, var->getType()->isReferenceType(), &CacheCulprit);
12813     return *CacheHasConstInit;
12814   };
12815 
12816   if (var->getTLSKind() == VarDecl::TLS_Static) {
12817     if (var->getType().isDestructedType()) {
12818       // GNU C++98 edits for __thread, [basic.start.term]p3:
12819       //   The type of an object with thread storage duration shall not
12820       //   have a non-trivial destructor.
12821       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12822       if (getLangOpts().CPlusPlus11)
12823         Diag(var->getLocation(), diag::note_use_thread_local);
12824     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12825       if (!checkConstInit()) {
12826         // GNU C++98 edits for __thread, [basic.start.init]p4:
12827         //   An object of thread storage duration shall not require dynamic
12828         //   initialization.
12829         // FIXME: Need strict checking here.
12830         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12831           << CacheCulprit->getSourceRange();
12832         if (getLangOpts().CPlusPlus11)
12833           Diag(var->getLocation(), diag::note_use_thread_local);
12834       }
12835     }
12836   }
12837 
12838   // Apply section attributes and pragmas to global variables.
12839   bool GlobalStorage = var->hasGlobalStorage();
12840   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12841       !inTemplateInstantiation()) {
12842     PragmaStack<StringLiteral *> *Stack = nullptr;
12843     int SectionFlags = ASTContext::PSF_Read;
12844     if (var->getType().isConstQualified())
12845       Stack = &ConstSegStack;
12846     else if (!var->getInit()) {
12847       Stack = &BSSSegStack;
12848       SectionFlags |= ASTContext::PSF_Write;
12849     } else {
12850       Stack = &DataSegStack;
12851       SectionFlags |= ASTContext::PSF_Write;
12852     }
12853     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12854       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12855         SectionFlags |= ASTContext::PSF_Implicit;
12856       UnifySection(SA->getName(), SectionFlags, var);
12857     } else if (Stack->CurrentValue) {
12858       SectionFlags |= ASTContext::PSF_Implicit;
12859       auto SectionName = Stack->CurrentValue->getString();
12860       var->addAttr(SectionAttr::CreateImplicit(
12861           Context, SectionName, Stack->CurrentPragmaLocation,
12862           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12863       if (UnifySection(SectionName, SectionFlags, var))
12864         var->dropAttr<SectionAttr>();
12865     }
12866 
12867     // Apply the init_seg attribute if this has an initializer.  If the
12868     // initializer turns out to not be dynamic, we'll end up ignoring this
12869     // attribute.
12870     if (CurInitSeg && var->getInit())
12871       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12872                                                CurInitSegLoc,
12873                                                AttributeCommonInfo::AS_Pragma));
12874   }
12875 
12876   // All the following checks are C++ only.
12877   if (!getLangOpts().CPlusPlus) {
12878       // If this variable must be emitted, add it as an initializer for the
12879       // current module.
12880      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12881        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12882      return;
12883   }
12884 
12885   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12886     CheckCompleteDecompositionDeclaration(DD);
12887 
12888   QualType type = var->getType();
12889   if (type->isDependentType()) return;
12890 
12891   if (var->hasAttr<BlocksAttr>())
12892     getCurFunction()->addByrefBlockVar(var);
12893 
12894   Expr *Init = var->getInit();
12895   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12896   QualType baseType = Context.getBaseElementType(type);
12897 
12898   if (Init && !Init->isValueDependent()) {
12899     if (var->isConstexpr()) {
12900       SmallVector<PartialDiagnosticAt, 8> Notes;
12901       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12902         SourceLocation DiagLoc = var->getLocation();
12903         // If the note doesn't add any useful information other than a source
12904         // location, fold it into the primary diagnostic.
12905         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12906               diag::note_invalid_subexpr_in_const_expr) {
12907           DiagLoc = Notes[0].first;
12908           Notes.clear();
12909         }
12910         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12911           << var << Init->getSourceRange();
12912         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12913           Diag(Notes[I].first, Notes[I].second);
12914       }
12915     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12916       // Check whether the initializer of a const variable of integral or
12917       // enumeration type is an ICE now, since we can't tell whether it was
12918       // initialized by a constant expression if we check later.
12919       var->checkInitIsICE();
12920     }
12921 
12922     // Don't emit further diagnostics about constexpr globals since they
12923     // were just diagnosed.
12924     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12925       // FIXME: Need strict checking in C++03 here.
12926       bool DiagErr = getLangOpts().CPlusPlus11
12927           ? !var->checkInitIsICE() : !checkConstInit();
12928       if (DiagErr) {
12929         auto *Attr = var->getAttr<ConstInitAttr>();
12930         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12931           << Init->getSourceRange();
12932         Diag(Attr->getLocation(),
12933              diag::note_declared_required_constant_init_here)
12934             << Attr->getRange() << Attr->isConstinit();
12935         if (getLangOpts().CPlusPlus11) {
12936           APValue Value;
12937           SmallVector<PartialDiagnosticAt, 8> Notes;
12938           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12939           for (auto &it : Notes)
12940             Diag(it.first, it.second);
12941         } else {
12942           Diag(CacheCulprit->getExprLoc(),
12943                diag::note_invalid_subexpr_in_const_expr)
12944               << CacheCulprit->getSourceRange();
12945         }
12946       }
12947     }
12948     else if (!var->isConstexpr() && IsGlobal &&
12949              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12950                                     var->getLocation())) {
12951       // Warn about globals which don't have a constant initializer.  Don't
12952       // warn about globals with a non-trivial destructor because we already
12953       // warned about them.
12954       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12955       if (!(RD && !RD->hasTrivialDestructor())) {
12956         if (!checkConstInit())
12957           Diag(var->getLocation(), diag::warn_global_constructor)
12958             << Init->getSourceRange();
12959       }
12960     }
12961   }
12962 
12963   // Require the destructor.
12964   if (const RecordType *recordType = baseType->getAs<RecordType>())
12965     FinalizeVarWithDestructor(var, recordType);
12966 
12967   // If this variable must be emitted, add it as an initializer for the current
12968   // module.
12969   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12970     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12971 }
12972 
12973 /// Determines if a variable's alignment is dependent.
12974 static bool hasDependentAlignment(VarDecl *VD) {
12975   if (VD->getType()->isDependentType())
12976     return true;
12977   for (auto *I : VD->specific_attrs<AlignedAttr>())
12978     if (I->isAlignmentDependent())
12979       return true;
12980   return false;
12981 }
12982 
12983 /// Check if VD needs to be dllexport/dllimport due to being in a
12984 /// dllexport/import function.
12985 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12986   assert(VD->isStaticLocal());
12987 
12988   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12989 
12990   // Find outermost function when VD is in lambda function.
12991   while (FD && !getDLLAttr(FD) &&
12992          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12993          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12994     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12995   }
12996 
12997   if (!FD)
12998     return;
12999 
13000   // Static locals inherit dll attributes from their function.
13001   if (Attr *A = getDLLAttr(FD)) {
13002     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13003     NewAttr->setInherited(true);
13004     VD->addAttr(NewAttr);
13005   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13006     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13007     NewAttr->setInherited(true);
13008     VD->addAttr(NewAttr);
13009 
13010     // Export this function to enforce exporting this static variable even
13011     // if it is not used in this compilation unit.
13012     if (!FD->hasAttr<DLLExportAttr>())
13013       FD->addAttr(NewAttr);
13014 
13015   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13016     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13017     NewAttr->setInherited(true);
13018     VD->addAttr(NewAttr);
13019   }
13020 }
13021 
13022 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13023 /// any semantic actions necessary after any initializer has been attached.
13024 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13025   // Note that we are no longer parsing the initializer for this declaration.
13026   ParsingInitForAutoVars.erase(ThisDecl);
13027 
13028   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13029   if (!VD)
13030     return;
13031 
13032   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13033   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13034       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13035     if (PragmaClangBSSSection.Valid)
13036       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13037           Context, PragmaClangBSSSection.SectionName,
13038           PragmaClangBSSSection.PragmaLocation,
13039           AttributeCommonInfo::AS_Pragma));
13040     if (PragmaClangDataSection.Valid)
13041       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13042           Context, PragmaClangDataSection.SectionName,
13043           PragmaClangDataSection.PragmaLocation,
13044           AttributeCommonInfo::AS_Pragma));
13045     if (PragmaClangRodataSection.Valid)
13046       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13047           Context, PragmaClangRodataSection.SectionName,
13048           PragmaClangRodataSection.PragmaLocation,
13049           AttributeCommonInfo::AS_Pragma));
13050     if (PragmaClangRelroSection.Valid)
13051       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13052           Context, PragmaClangRelroSection.SectionName,
13053           PragmaClangRelroSection.PragmaLocation,
13054           AttributeCommonInfo::AS_Pragma));
13055   }
13056 
13057   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13058     for (auto *BD : DD->bindings()) {
13059       FinalizeDeclaration(BD);
13060     }
13061   }
13062 
13063   checkAttributesAfterMerging(*this, *VD);
13064 
13065   // Perform TLS alignment check here after attributes attached to the variable
13066   // which may affect the alignment have been processed. Only perform the check
13067   // if the target has a maximum TLS alignment (zero means no constraints).
13068   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13069     // Protect the check so that it's not performed on dependent types and
13070     // dependent alignments (we can't determine the alignment in that case).
13071     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13072         !VD->isInvalidDecl()) {
13073       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13074       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13075         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13076           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13077           << (unsigned)MaxAlignChars.getQuantity();
13078       }
13079     }
13080   }
13081 
13082   if (VD->isStaticLocal()) {
13083     CheckStaticLocalForDllExport(VD);
13084 
13085     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13086       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13087       // function, only __shared__ variables or variables without any device
13088       // memory qualifiers may be declared with static storage class.
13089       // Note: It is unclear how a function-scope non-const static variable
13090       // without device memory qualifier is implemented, therefore only static
13091       // const variable without device memory qualifier is allowed.
13092       [&]() {
13093         if (!getLangOpts().CUDA)
13094           return;
13095         if (VD->hasAttr<CUDASharedAttr>())
13096           return;
13097         if (VD->getType().isConstQualified() &&
13098             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13099           return;
13100         if (CUDADiagIfDeviceCode(VD->getLocation(),
13101                                  diag::err_device_static_local_var)
13102             << CurrentCUDATarget())
13103           VD->setInvalidDecl();
13104       }();
13105     }
13106   }
13107 
13108   // Perform check for initializers of device-side global variables.
13109   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13110   // 7.5). We must also apply the same checks to all __shared__
13111   // variables whether they are local or not. CUDA also allows
13112   // constant initializers for __constant__ and __device__ variables.
13113   if (getLangOpts().CUDA)
13114     checkAllowedCUDAInitializer(VD);
13115 
13116   // Grab the dllimport or dllexport attribute off of the VarDecl.
13117   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13118 
13119   // Imported static data members cannot be defined out-of-line.
13120   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13121     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13122         VD->isThisDeclarationADefinition()) {
13123       // We allow definitions of dllimport class template static data members
13124       // with a warning.
13125       CXXRecordDecl *Context =
13126         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13127       bool IsClassTemplateMember =
13128           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13129           Context->getDescribedClassTemplate();
13130 
13131       Diag(VD->getLocation(),
13132            IsClassTemplateMember
13133                ? diag::warn_attribute_dllimport_static_field_definition
13134                : diag::err_attribute_dllimport_static_field_definition);
13135       Diag(IA->getLocation(), diag::note_attribute);
13136       if (!IsClassTemplateMember)
13137         VD->setInvalidDecl();
13138     }
13139   }
13140 
13141   // dllimport/dllexport variables cannot be thread local, their TLS index
13142   // isn't exported with the variable.
13143   if (DLLAttr && VD->getTLSKind()) {
13144     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13145     if (F && getDLLAttr(F)) {
13146       assert(VD->isStaticLocal());
13147       // But if this is a static local in a dlimport/dllexport function, the
13148       // function will never be inlined, which means the var would never be
13149       // imported, so having it marked import/export is safe.
13150     } else {
13151       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13152                                                                     << DLLAttr;
13153       VD->setInvalidDecl();
13154     }
13155   }
13156 
13157   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13158     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13159       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13160       VD->dropAttr<UsedAttr>();
13161     }
13162   }
13163 
13164   const DeclContext *DC = VD->getDeclContext();
13165   // If there's a #pragma GCC visibility in scope, and this isn't a class
13166   // member, set the visibility of this variable.
13167   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13168     AddPushedVisibilityAttribute(VD);
13169 
13170   // FIXME: Warn on unused var template partial specializations.
13171   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13172     MarkUnusedFileScopedDecl(VD);
13173 
13174   // Now we have parsed the initializer and can update the table of magic
13175   // tag values.
13176   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13177       !VD->getType()->isIntegralOrEnumerationType())
13178     return;
13179 
13180   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13181     const Expr *MagicValueExpr = VD->getInit();
13182     if (!MagicValueExpr) {
13183       continue;
13184     }
13185     Optional<llvm::APSInt> MagicValueInt;
13186     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13187       Diag(I->getRange().getBegin(),
13188            diag::err_type_tag_for_datatype_not_ice)
13189         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13190       continue;
13191     }
13192     if (MagicValueInt->getActiveBits() > 64) {
13193       Diag(I->getRange().getBegin(),
13194            diag::err_type_tag_for_datatype_too_large)
13195         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13196       continue;
13197     }
13198     uint64_t MagicValue = MagicValueInt->getZExtValue();
13199     RegisterTypeTagForDatatype(I->getArgumentKind(),
13200                                MagicValue,
13201                                I->getMatchingCType(),
13202                                I->getLayoutCompatible(),
13203                                I->getMustBeNull());
13204   }
13205 }
13206 
13207 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13208   auto *VD = dyn_cast<VarDecl>(DD);
13209   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13210 }
13211 
13212 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13213                                                    ArrayRef<Decl *> Group) {
13214   SmallVector<Decl*, 8> Decls;
13215 
13216   if (DS.isTypeSpecOwned())
13217     Decls.push_back(DS.getRepAsDecl());
13218 
13219   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13220   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13221   bool DiagnosedMultipleDecomps = false;
13222   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13223   bool DiagnosedNonDeducedAuto = false;
13224 
13225   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13226     if (Decl *D = Group[i]) {
13227       // For declarators, there are some additional syntactic-ish checks we need
13228       // to perform.
13229       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13230         if (!FirstDeclaratorInGroup)
13231           FirstDeclaratorInGroup = DD;
13232         if (!FirstDecompDeclaratorInGroup)
13233           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13234         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13235             !hasDeducedAuto(DD))
13236           FirstNonDeducedAutoInGroup = DD;
13237 
13238         if (FirstDeclaratorInGroup != DD) {
13239           // A decomposition declaration cannot be combined with any other
13240           // declaration in the same group.
13241           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13242             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13243                  diag::err_decomp_decl_not_alone)
13244                 << FirstDeclaratorInGroup->getSourceRange()
13245                 << DD->getSourceRange();
13246             DiagnosedMultipleDecomps = true;
13247           }
13248 
13249           // A declarator that uses 'auto' in any way other than to declare a
13250           // variable with a deduced type cannot be combined with any other
13251           // declarator in the same group.
13252           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13253             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13254                  diag::err_auto_non_deduced_not_alone)
13255                 << FirstNonDeducedAutoInGroup->getType()
13256                        ->hasAutoForTrailingReturnType()
13257                 << FirstDeclaratorInGroup->getSourceRange()
13258                 << DD->getSourceRange();
13259             DiagnosedNonDeducedAuto = true;
13260           }
13261         }
13262       }
13263 
13264       Decls.push_back(D);
13265     }
13266   }
13267 
13268   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13269     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13270       handleTagNumbering(Tag, S);
13271       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13272           getLangOpts().CPlusPlus)
13273         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13274     }
13275   }
13276 
13277   return BuildDeclaratorGroup(Decls);
13278 }
13279 
13280 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13281 /// group, performing any necessary semantic checking.
13282 Sema::DeclGroupPtrTy
13283 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13284   // C++14 [dcl.spec.auto]p7: (DR1347)
13285   //   If the type that replaces the placeholder type is not the same in each
13286   //   deduction, the program is ill-formed.
13287   if (Group.size() > 1) {
13288     QualType Deduced;
13289     VarDecl *DeducedDecl = nullptr;
13290     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13291       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13292       if (!D || D->isInvalidDecl())
13293         break;
13294       DeducedType *DT = D->getType()->getContainedDeducedType();
13295       if (!DT || DT->getDeducedType().isNull())
13296         continue;
13297       if (Deduced.isNull()) {
13298         Deduced = DT->getDeducedType();
13299         DeducedDecl = D;
13300       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13301         auto *AT = dyn_cast<AutoType>(DT);
13302         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13303                         diag::err_auto_different_deductions)
13304                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13305                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13306                    << D->getDeclName();
13307         if (DeducedDecl->hasInit())
13308           Dia << DeducedDecl->getInit()->getSourceRange();
13309         if (D->getInit())
13310           Dia << D->getInit()->getSourceRange();
13311         D->setInvalidDecl();
13312         break;
13313       }
13314     }
13315   }
13316 
13317   ActOnDocumentableDecls(Group);
13318 
13319   return DeclGroupPtrTy::make(
13320       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13321 }
13322 
13323 void Sema::ActOnDocumentableDecl(Decl *D) {
13324   ActOnDocumentableDecls(D);
13325 }
13326 
13327 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13328   // Don't parse the comment if Doxygen diagnostics are ignored.
13329   if (Group.empty() || !Group[0])
13330     return;
13331 
13332   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13333                       Group[0]->getLocation()) &&
13334       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13335                       Group[0]->getLocation()))
13336     return;
13337 
13338   if (Group.size() >= 2) {
13339     // This is a decl group.  Normally it will contain only declarations
13340     // produced from declarator list.  But in case we have any definitions or
13341     // additional declaration references:
13342     //   'typedef struct S {} S;'
13343     //   'typedef struct S *S;'
13344     //   'struct S *pS;'
13345     // FinalizeDeclaratorGroup adds these as separate declarations.
13346     Decl *MaybeTagDecl = Group[0];
13347     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13348       Group = Group.slice(1);
13349     }
13350   }
13351 
13352   // FIMXE: We assume every Decl in the group is in the same file.
13353   // This is false when preprocessor constructs the group from decls in
13354   // different files (e. g. macros or #include).
13355   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13356 }
13357 
13358 /// Common checks for a parameter-declaration that should apply to both function
13359 /// parameters and non-type template parameters.
13360 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13361   // Check that there are no default arguments inside the type of this
13362   // parameter.
13363   if (getLangOpts().CPlusPlus)
13364     CheckExtraCXXDefaultArguments(D);
13365 
13366   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13367   if (D.getCXXScopeSpec().isSet()) {
13368     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13369       << D.getCXXScopeSpec().getRange();
13370   }
13371 
13372   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13373   // simple identifier except [...irrelevant cases...].
13374   switch (D.getName().getKind()) {
13375   case UnqualifiedIdKind::IK_Identifier:
13376     break;
13377 
13378   case UnqualifiedIdKind::IK_OperatorFunctionId:
13379   case UnqualifiedIdKind::IK_ConversionFunctionId:
13380   case UnqualifiedIdKind::IK_LiteralOperatorId:
13381   case UnqualifiedIdKind::IK_ConstructorName:
13382   case UnqualifiedIdKind::IK_DestructorName:
13383   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13384   case UnqualifiedIdKind::IK_DeductionGuideName:
13385     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13386       << GetNameForDeclarator(D).getName();
13387     break;
13388 
13389   case UnqualifiedIdKind::IK_TemplateId:
13390   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13391     // GetNameForDeclarator would not produce a useful name in this case.
13392     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13393     break;
13394   }
13395 }
13396 
13397 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13398 /// to introduce parameters into function prototype scope.
13399 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13400   const DeclSpec &DS = D.getDeclSpec();
13401 
13402   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13403 
13404   // C++03 [dcl.stc]p2 also permits 'auto'.
13405   StorageClass SC = SC_None;
13406   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13407     SC = SC_Register;
13408     // In C++11, the 'register' storage class specifier is deprecated.
13409     // In C++17, it is not allowed, but we tolerate it as an extension.
13410     if (getLangOpts().CPlusPlus11) {
13411       Diag(DS.getStorageClassSpecLoc(),
13412            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13413                                      : diag::warn_deprecated_register)
13414         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13415     }
13416   } else if (getLangOpts().CPlusPlus &&
13417              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13418     SC = SC_Auto;
13419   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13420     Diag(DS.getStorageClassSpecLoc(),
13421          diag::err_invalid_storage_class_in_func_decl);
13422     D.getMutableDeclSpec().ClearStorageClassSpecs();
13423   }
13424 
13425   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13426     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13427       << DeclSpec::getSpecifierName(TSCS);
13428   if (DS.isInlineSpecified())
13429     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13430         << getLangOpts().CPlusPlus17;
13431   if (DS.hasConstexprSpecifier())
13432     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13433         << 0 << D.getDeclSpec().getConstexprSpecifier();
13434 
13435   DiagnoseFunctionSpecifiers(DS);
13436 
13437   CheckFunctionOrTemplateParamDeclarator(S, D);
13438 
13439   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13440   QualType parmDeclType = TInfo->getType();
13441 
13442   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13443   IdentifierInfo *II = D.getIdentifier();
13444   if (II) {
13445     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13446                    ForVisibleRedeclaration);
13447     LookupName(R, S);
13448     if (R.isSingleResult()) {
13449       NamedDecl *PrevDecl = R.getFoundDecl();
13450       if (PrevDecl->isTemplateParameter()) {
13451         // Maybe we will complain about the shadowed template parameter.
13452         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13453         // Just pretend that we didn't see the previous declaration.
13454         PrevDecl = nullptr;
13455       } else if (S->isDeclScope(PrevDecl)) {
13456         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13457         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13458 
13459         // Recover by removing the name
13460         II = nullptr;
13461         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13462         D.setInvalidType(true);
13463       }
13464     }
13465   }
13466 
13467   // Temporarily put parameter variables in the translation unit, not
13468   // the enclosing context.  This prevents them from accidentally
13469   // looking like class members in C++.
13470   ParmVarDecl *New =
13471       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13472                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13473 
13474   if (D.isInvalidType())
13475     New->setInvalidDecl();
13476 
13477   assert(S->isFunctionPrototypeScope());
13478   assert(S->getFunctionPrototypeDepth() >= 1);
13479   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13480                     S->getNextFunctionPrototypeIndex());
13481 
13482   // Add the parameter declaration into this scope.
13483   S->AddDecl(New);
13484   if (II)
13485     IdResolver.AddDecl(New);
13486 
13487   ProcessDeclAttributes(S, New, D);
13488 
13489   if (D.getDeclSpec().isModulePrivateSpecified())
13490     Diag(New->getLocation(), diag::err_module_private_local)
13491         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13492         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13493 
13494   if (New->hasAttr<BlocksAttr>()) {
13495     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13496   }
13497 
13498   if (getLangOpts().OpenCL)
13499     deduceOpenCLAddressSpace(New);
13500 
13501   return New;
13502 }
13503 
13504 /// Synthesizes a variable for a parameter arising from a
13505 /// typedef.
13506 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13507                                               SourceLocation Loc,
13508                                               QualType T) {
13509   /* FIXME: setting StartLoc == Loc.
13510      Would it be worth to modify callers so as to provide proper source
13511      location for the unnamed parameters, embedding the parameter's type? */
13512   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13513                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13514                                            SC_None, nullptr);
13515   Param->setImplicit();
13516   return Param;
13517 }
13518 
13519 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13520   // Don't diagnose unused-parameter errors in template instantiations; we
13521   // will already have done so in the template itself.
13522   if (inTemplateInstantiation())
13523     return;
13524 
13525   for (const ParmVarDecl *Parameter : Parameters) {
13526     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13527         !Parameter->hasAttr<UnusedAttr>()) {
13528       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13529         << Parameter->getDeclName();
13530     }
13531   }
13532 }
13533 
13534 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13535     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13536   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13537     return;
13538 
13539   // Warn if the return value is pass-by-value and larger than the specified
13540   // threshold.
13541   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13542     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13543     if (Size > LangOpts.NumLargeByValueCopy)
13544       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13545   }
13546 
13547   // Warn if any parameter is pass-by-value and larger than the specified
13548   // threshold.
13549   for (const ParmVarDecl *Parameter : Parameters) {
13550     QualType T = Parameter->getType();
13551     if (T->isDependentType() || !T.isPODType(Context))
13552       continue;
13553     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13554     if (Size > LangOpts.NumLargeByValueCopy)
13555       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13556           << Parameter << Size;
13557   }
13558 }
13559 
13560 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13561                                   SourceLocation NameLoc, IdentifierInfo *Name,
13562                                   QualType T, TypeSourceInfo *TSInfo,
13563                                   StorageClass SC) {
13564   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13565   if (getLangOpts().ObjCAutoRefCount &&
13566       T.getObjCLifetime() == Qualifiers::OCL_None &&
13567       T->isObjCLifetimeType()) {
13568 
13569     Qualifiers::ObjCLifetime lifetime;
13570 
13571     // Special cases for arrays:
13572     //   - if it's const, use __unsafe_unretained
13573     //   - otherwise, it's an error
13574     if (T->isArrayType()) {
13575       if (!T.isConstQualified()) {
13576         if (DelayedDiagnostics.shouldDelayDiagnostics())
13577           DelayedDiagnostics.add(
13578               sema::DelayedDiagnostic::makeForbiddenType(
13579               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13580         else
13581           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13582               << TSInfo->getTypeLoc().getSourceRange();
13583       }
13584       lifetime = Qualifiers::OCL_ExplicitNone;
13585     } else {
13586       lifetime = T->getObjCARCImplicitLifetime();
13587     }
13588     T = Context.getLifetimeQualifiedType(T, lifetime);
13589   }
13590 
13591   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13592                                          Context.getAdjustedParameterType(T),
13593                                          TSInfo, SC, nullptr);
13594 
13595   // Make a note if we created a new pack in the scope of a lambda, so that
13596   // we know that references to that pack must also be expanded within the
13597   // lambda scope.
13598   if (New->isParameterPack())
13599     if (auto *LSI = getEnclosingLambda())
13600       LSI->LocalPacks.push_back(New);
13601 
13602   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13603       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13604     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13605                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13606 
13607   // Parameters can not be abstract class types.
13608   // For record types, this is done by the AbstractClassUsageDiagnoser once
13609   // the class has been completely parsed.
13610   if (!CurContext->isRecord() &&
13611       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13612                              AbstractParamType))
13613     New->setInvalidDecl();
13614 
13615   // Parameter declarators cannot be interface types. All ObjC objects are
13616   // passed by reference.
13617   if (T->isObjCObjectType()) {
13618     SourceLocation TypeEndLoc =
13619         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13620     Diag(NameLoc,
13621          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13622       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13623     T = Context.getObjCObjectPointerType(T);
13624     New->setType(T);
13625   }
13626 
13627   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13628   // duration shall not be qualified by an address-space qualifier."
13629   // Since all parameters have automatic store duration, they can not have
13630   // an address space.
13631   if (T.getAddressSpace() != LangAS::Default &&
13632       // OpenCL allows function arguments declared to be an array of a type
13633       // to be qualified with an address space.
13634       !(getLangOpts().OpenCL &&
13635         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13636     Diag(NameLoc, diag::err_arg_with_address_space);
13637     New->setInvalidDecl();
13638   }
13639 
13640   return New;
13641 }
13642 
13643 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13644                                            SourceLocation LocAfterDecls) {
13645   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13646 
13647   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13648   // for a K&R function.
13649   if (!FTI.hasPrototype) {
13650     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13651       --i;
13652       if (FTI.Params[i].Param == nullptr) {
13653         SmallString<256> Code;
13654         llvm::raw_svector_ostream(Code)
13655             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13656         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13657             << FTI.Params[i].Ident
13658             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13659 
13660         // Implicitly declare the argument as type 'int' for lack of a better
13661         // type.
13662         AttributeFactory attrs;
13663         DeclSpec DS(attrs);
13664         const char* PrevSpec; // unused
13665         unsigned DiagID; // unused
13666         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13667                            DiagID, Context.getPrintingPolicy());
13668         // Use the identifier location for the type source range.
13669         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13670         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13671         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13672         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13673         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13674       }
13675     }
13676   }
13677 }
13678 
13679 Decl *
13680 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13681                               MultiTemplateParamsArg TemplateParameterLists,
13682                               SkipBodyInfo *SkipBody) {
13683   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13684   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13685   Scope *ParentScope = FnBodyScope->getParent();
13686 
13687   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13688   // we define a non-templated function definition, we will create a declaration
13689   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13690   // The base function declaration will have the equivalent of an `omp declare
13691   // variant` annotation which specifies the mangled definition as a
13692   // specialization function under the OpenMP context defined as part of the
13693   // `omp begin declare variant`.
13694   FunctionDecl *BaseFD = nullptr;
13695   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13696       TemplateParameterLists.empty())
13697     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13698         ParentScope, D);
13699 
13700   D.setFunctionDefinitionKind(FDK_Definition);
13701   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13702   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13703 
13704   if (BaseFD)
13705     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13706         cast<FunctionDecl>(Dcl), BaseFD);
13707 
13708   return Dcl;
13709 }
13710 
13711 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13712   Consumer.HandleInlineFunctionDefinition(D);
13713 }
13714 
13715 static bool
13716 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13717                                 const FunctionDecl *&PossiblePrototype) {
13718   // Don't warn about invalid declarations.
13719   if (FD->isInvalidDecl())
13720     return false;
13721 
13722   // Or declarations that aren't global.
13723   if (!FD->isGlobal())
13724     return false;
13725 
13726   // Don't warn about C++ member functions.
13727   if (isa<CXXMethodDecl>(FD))
13728     return false;
13729 
13730   // Don't warn about 'main'.
13731   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13732     if (IdentifierInfo *II = FD->getIdentifier())
13733       if (II->isStr("main"))
13734         return false;
13735 
13736   // Don't warn about inline functions.
13737   if (FD->isInlined())
13738     return false;
13739 
13740   // Don't warn about function templates.
13741   if (FD->getDescribedFunctionTemplate())
13742     return false;
13743 
13744   // Don't warn about function template specializations.
13745   if (FD->isFunctionTemplateSpecialization())
13746     return false;
13747 
13748   // Don't warn for OpenCL kernels.
13749   if (FD->hasAttr<OpenCLKernelAttr>())
13750     return false;
13751 
13752   // Don't warn on explicitly deleted functions.
13753   if (FD->isDeleted())
13754     return false;
13755 
13756   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13757        Prev; Prev = Prev->getPreviousDecl()) {
13758     // Ignore any declarations that occur in function or method
13759     // scope, because they aren't visible from the header.
13760     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13761       continue;
13762 
13763     PossiblePrototype = Prev;
13764     return Prev->getType()->isFunctionNoProtoType();
13765   }
13766 
13767   return true;
13768 }
13769 
13770 void
13771 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13772                                    const FunctionDecl *EffectiveDefinition,
13773                                    SkipBodyInfo *SkipBody) {
13774   const FunctionDecl *Definition = EffectiveDefinition;
13775   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13776     // If this is a friend function defined in a class template, it does not
13777     // have a body until it is used, nevertheless it is a definition, see
13778     // [temp.inst]p2:
13779     //
13780     // ... for the purpose of determining whether an instantiated redeclaration
13781     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13782     // corresponds to a definition in the template is considered to be a
13783     // definition.
13784     //
13785     // The following code must produce redefinition error:
13786     //
13787     //     template<typename T> struct C20 { friend void func_20() {} };
13788     //     C20<int> c20i;
13789     //     void func_20() {}
13790     //
13791     for (auto I : FD->redecls()) {
13792       if (I != FD && !I->isInvalidDecl() &&
13793           I->getFriendObjectKind() != Decl::FOK_None) {
13794         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13795           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13796             // A merged copy of the same function, instantiated as a member of
13797             // the same class, is OK.
13798             if (declaresSameEntity(OrigFD, Original) &&
13799                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13800                                    cast<Decl>(FD->getLexicalDeclContext())))
13801               continue;
13802           }
13803 
13804           if (Original->isThisDeclarationADefinition()) {
13805             Definition = I;
13806             break;
13807           }
13808         }
13809       }
13810     }
13811   }
13812 
13813   if (!Definition)
13814     // Similar to friend functions a friend function template may be a
13815     // definition and do not have a body if it is instantiated in a class
13816     // template.
13817     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13818       for (auto I : FTD->redecls()) {
13819         auto D = cast<FunctionTemplateDecl>(I);
13820         if (D != FTD) {
13821           assert(!D->isThisDeclarationADefinition() &&
13822                  "More than one definition in redeclaration chain");
13823           if (D->getFriendObjectKind() != Decl::FOK_None)
13824             if (FunctionTemplateDecl *FT =
13825                                        D->getInstantiatedFromMemberTemplate()) {
13826               if (FT->isThisDeclarationADefinition()) {
13827                 Definition = D->getTemplatedDecl();
13828                 break;
13829               }
13830             }
13831         }
13832       }
13833     }
13834 
13835   if (!Definition)
13836     return;
13837 
13838   if (canRedefineFunction(Definition, getLangOpts()))
13839     return;
13840 
13841   // Don't emit an error when this is redefinition of a typo-corrected
13842   // definition.
13843   if (TypoCorrectedFunctionDefinitions.count(Definition))
13844     return;
13845 
13846   // If we don't have a visible definition of the function, and it's inline or
13847   // a template, skip the new definition.
13848   if (SkipBody && !hasVisibleDefinition(Definition) &&
13849       (Definition->getFormalLinkage() == InternalLinkage ||
13850        Definition->isInlined() ||
13851        Definition->getDescribedFunctionTemplate() ||
13852        Definition->getNumTemplateParameterLists())) {
13853     SkipBody->ShouldSkip = true;
13854     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13855     if (auto *TD = Definition->getDescribedFunctionTemplate())
13856       makeMergedDefinitionVisible(TD);
13857     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13858     return;
13859   }
13860 
13861   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13862       Definition->getStorageClass() == SC_Extern)
13863     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13864         << FD << getLangOpts().CPlusPlus;
13865   else
13866     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13867 
13868   Diag(Definition->getLocation(), diag::note_previous_definition);
13869   FD->setInvalidDecl();
13870 }
13871 
13872 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13873                                    Sema &S) {
13874   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13875 
13876   LambdaScopeInfo *LSI = S.PushLambdaScope();
13877   LSI->CallOperator = CallOperator;
13878   LSI->Lambda = LambdaClass;
13879   LSI->ReturnType = CallOperator->getReturnType();
13880   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13881 
13882   if (LCD == LCD_None)
13883     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13884   else if (LCD == LCD_ByCopy)
13885     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13886   else if (LCD == LCD_ByRef)
13887     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13888   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13889 
13890   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13891   LSI->Mutable = !CallOperator->isConst();
13892 
13893   // Add the captures to the LSI so they can be noted as already
13894   // captured within tryCaptureVar.
13895   auto I = LambdaClass->field_begin();
13896   for (const auto &C : LambdaClass->captures()) {
13897     if (C.capturesVariable()) {
13898       VarDecl *VD = C.getCapturedVar();
13899       if (VD->isInitCapture())
13900         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13901       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13902       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13903           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13904           /*EllipsisLoc*/C.isPackExpansion()
13905                          ? C.getEllipsisLoc() : SourceLocation(),
13906           I->getType(), /*Invalid*/false);
13907 
13908     } else if (C.capturesThis()) {
13909       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13910                           C.getCaptureKind() == LCK_StarThis);
13911     } else {
13912       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13913                              I->getType());
13914     }
13915     ++I;
13916   }
13917 }
13918 
13919 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13920                                     SkipBodyInfo *SkipBody) {
13921   if (!D) {
13922     // Parsing the function declaration failed in some way. Push on a fake scope
13923     // anyway so we can try to parse the function body.
13924     PushFunctionScope();
13925     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13926     return D;
13927   }
13928 
13929   FunctionDecl *FD = nullptr;
13930 
13931   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13932     FD = FunTmpl->getTemplatedDecl();
13933   else
13934     FD = cast<FunctionDecl>(D);
13935 
13936   // Do not push if it is a lambda because one is already pushed when building
13937   // the lambda in ActOnStartOfLambdaDefinition().
13938   if (!isLambdaCallOperator(FD))
13939     PushExpressionEvaluationContext(
13940         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13941                           : ExprEvalContexts.back().Context);
13942 
13943   // Check for defining attributes before the check for redefinition.
13944   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13945     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13946     FD->dropAttr<AliasAttr>();
13947     FD->setInvalidDecl();
13948   }
13949   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13950     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13951     FD->dropAttr<IFuncAttr>();
13952     FD->setInvalidDecl();
13953   }
13954 
13955   // See if this is a redefinition. If 'will have body' is already set, then
13956   // these checks were already performed when it was set.
13957   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13958     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13959 
13960     // If we're skipping the body, we're done. Don't enter the scope.
13961     if (SkipBody && SkipBody->ShouldSkip)
13962       return D;
13963   }
13964 
13965   // Mark this function as "will have a body eventually".  This lets users to
13966   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13967   // this function.
13968   FD->setWillHaveBody();
13969 
13970   // If we are instantiating a generic lambda call operator, push
13971   // a LambdaScopeInfo onto the function stack.  But use the information
13972   // that's already been calculated (ActOnLambdaExpr) to prime the current
13973   // LambdaScopeInfo.
13974   // When the template operator is being specialized, the LambdaScopeInfo,
13975   // has to be properly restored so that tryCaptureVariable doesn't try
13976   // and capture any new variables. In addition when calculating potential
13977   // captures during transformation of nested lambdas, it is necessary to
13978   // have the LSI properly restored.
13979   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13980     assert(inTemplateInstantiation() &&
13981            "There should be an active template instantiation on the stack "
13982            "when instantiating a generic lambda!");
13983     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13984   } else {
13985     // Enter a new function scope
13986     PushFunctionScope();
13987   }
13988 
13989   // Builtin functions cannot be defined.
13990   if (unsigned BuiltinID = FD->getBuiltinID()) {
13991     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13992         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13993       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13994       FD->setInvalidDecl();
13995     }
13996   }
13997 
13998   // The return type of a function definition must be complete
13999   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14000   QualType ResultType = FD->getReturnType();
14001   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14002       !FD->isInvalidDecl() &&
14003       RequireCompleteType(FD->getLocation(), ResultType,
14004                           diag::err_func_def_incomplete_result))
14005     FD->setInvalidDecl();
14006 
14007   if (FnBodyScope)
14008     PushDeclContext(FnBodyScope, FD);
14009 
14010   // Check the validity of our function parameters
14011   CheckParmsForFunctionDef(FD->parameters(),
14012                            /*CheckParameterNames=*/true);
14013 
14014   // Add non-parameter declarations already in the function to the current
14015   // scope.
14016   if (FnBodyScope) {
14017     for (Decl *NPD : FD->decls()) {
14018       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14019       if (!NonParmDecl)
14020         continue;
14021       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14022              "parameters should not be in newly created FD yet");
14023 
14024       // If the decl has a name, make it accessible in the current scope.
14025       if (NonParmDecl->getDeclName())
14026         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14027 
14028       // Similarly, dive into enums and fish their constants out, making them
14029       // accessible in this scope.
14030       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14031         for (auto *EI : ED->enumerators())
14032           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14033       }
14034     }
14035   }
14036 
14037   // Introduce our parameters into the function scope
14038   for (auto Param : FD->parameters()) {
14039     Param->setOwningFunction(FD);
14040 
14041     // If this has an identifier, add it to the scope stack.
14042     if (Param->getIdentifier() && FnBodyScope) {
14043       CheckShadow(FnBodyScope, Param);
14044 
14045       PushOnScopeChains(Param, FnBodyScope);
14046     }
14047   }
14048 
14049   // Ensure that the function's exception specification is instantiated.
14050   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14051     ResolveExceptionSpec(D->getLocation(), FPT);
14052 
14053   // dllimport cannot be applied to non-inline function definitions.
14054   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14055       !FD->isTemplateInstantiation()) {
14056     assert(!FD->hasAttr<DLLExportAttr>());
14057     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14058     FD->setInvalidDecl();
14059     return D;
14060   }
14061   // We want to attach documentation to original Decl (which might be
14062   // a function template).
14063   ActOnDocumentableDecl(D);
14064   if (getCurLexicalContext()->isObjCContainer() &&
14065       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14066       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14067     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14068 
14069   return D;
14070 }
14071 
14072 /// Given the set of return statements within a function body,
14073 /// compute the variables that are subject to the named return value
14074 /// optimization.
14075 ///
14076 /// Each of the variables that is subject to the named return value
14077 /// optimization will be marked as NRVO variables in the AST, and any
14078 /// return statement that has a marked NRVO variable as its NRVO candidate can
14079 /// use the named return value optimization.
14080 ///
14081 /// This function applies a very simplistic algorithm for NRVO: if every return
14082 /// statement in the scope of a variable has the same NRVO candidate, that
14083 /// candidate is an NRVO variable.
14084 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14085   ReturnStmt **Returns = Scope->Returns.data();
14086 
14087   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14088     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14089       if (!NRVOCandidate->isNRVOVariable())
14090         Returns[I]->setNRVOCandidate(nullptr);
14091     }
14092   }
14093 }
14094 
14095 bool Sema::canDelayFunctionBody(const Declarator &D) {
14096   // We can't delay parsing the body of a constexpr function template (yet).
14097   if (D.getDeclSpec().hasConstexprSpecifier())
14098     return false;
14099 
14100   // We can't delay parsing the body of a function template with a deduced
14101   // return type (yet).
14102   if (D.getDeclSpec().hasAutoTypeSpec()) {
14103     // If the placeholder introduces a non-deduced trailing return type,
14104     // we can still delay parsing it.
14105     if (D.getNumTypeObjects()) {
14106       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14107       if (Outer.Kind == DeclaratorChunk::Function &&
14108           Outer.Fun.hasTrailingReturnType()) {
14109         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14110         return Ty.isNull() || !Ty->isUndeducedType();
14111       }
14112     }
14113     return false;
14114   }
14115 
14116   return true;
14117 }
14118 
14119 bool Sema::canSkipFunctionBody(Decl *D) {
14120   // We cannot skip the body of a function (or function template) which is
14121   // constexpr, since we may need to evaluate its body in order to parse the
14122   // rest of the file.
14123   // We cannot skip the body of a function with an undeduced return type,
14124   // because any callers of that function need to know the type.
14125   if (const FunctionDecl *FD = D->getAsFunction()) {
14126     if (FD->isConstexpr())
14127       return false;
14128     // We can't simply call Type::isUndeducedType here, because inside template
14129     // auto can be deduced to a dependent type, which is not considered
14130     // "undeduced".
14131     if (FD->getReturnType()->getContainedDeducedType())
14132       return false;
14133   }
14134   return Consumer.shouldSkipFunctionBody(D);
14135 }
14136 
14137 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14138   if (!Decl)
14139     return nullptr;
14140   if (FunctionDecl *FD = Decl->getAsFunction())
14141     FD->setHasSkippedBody();
14142   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14143     MD->setHasSkippedBody();
14144   return Decl;
14145 }
14146 
14147 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14148   return ActOnFinishFunctionBody(D, BodyArg, false);
14149 }
14150 
14151 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14152 /// body.
14153 class ExitFunctionBodyRAII {
14154 public:
14155   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14156   ~ExitFunctionBodyRAII() {
14157     if (!IsLambda)
14158       S.PopExpressionEvaluationContext();
14159   }
14160 
14161 private:
14162   Sema &S;
14163   bool IsLambda = false;
14164 };
14165 
14166 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14167   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14168 
14169   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14170     if (EscapeInfo.count(BD))
14171       return EscapeInfo[BD];
14172 
14173     bool R = false;
14174     const BlockDecl *CurBD = BD;
14175 
14176     do {
14177       R = !CurBD->doesNotEscape();
14178       if (R)
14179         break;
14180       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14181     } while (CurBD);
14182 
14183     return EscapeInfo[BD] = R;
14184   };
14185 
14186   // If the location where 'self' is implicitly retained is inside a escaping
14187   // block, emit a diagnostic.
14188   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14189        S.ImplicitlyRetainedSelfLocs)
14190     if (IsOrNestedInEscapingBlock(P.second))
14191       S.Diag(P.first, diag::warn_implicitly_retains_self)
14192           << FixItHint::CreateInsertion(P.first, "self->");
14193 }
14194 
14195 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14196                                     bool IsInstantiation) {
14197   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14198 
14199   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14200   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14201 
14202   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14203     CheckCompletedCoroutineBody(FD, Body);
14204 
14205   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14206   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14207   // meant to pop the context added in ActOnStartOfFunctionDef().
14208   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14209 
14210   if (FD) {
14211     FD->setBody(Body);
14212     FD->setWillHaveBody(false);
14213 
14214     if (getLangOpts().CPlusPlus14) {
14215       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14216           FD->getReturnType()->isUndeducedType()) {
14217         // If the function has a deduced result type but contains no 'return'
14218         // statements, the result type as written must be exactly 'auto', and
14219         // the deduced result type is 'void'.
14220         if (!FD->getReturnType()->getAs<AutoType>()) {
14221           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14222               << FD->getReturnType();
14223           FD->setInvalidDecl();
14224         } else {
14225           // Substitute 'void' for the 'auto' in the type.
14226           TypeLoc ResultType = getReturnTypeLoc(FD);
14227           Context.adjustDeducedFunctionResultType(
14228               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14229         }
14230       }
14231     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14232       // In C++11, we don't use 'auto' deduction rules for lambda call
14233       // operators because we don't support return type deduction.
14234       auto *LSI = getCurLambda();
14235       if (LSI->HasImplicitReturnType) {
14236         deduceClosureReturnType(*LSI);
14237 
14238         // C++11 [expr.prim.lambda]p4:
14239         //   [...] if there are no return statements in the compound-statement
14240         //   [the deduced type is] the type void
14241         QualType RetType =
14242             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14243 
14244         // Update the return type to the deduced type.
14245         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14246         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14247                                             Proto->getExtProtoInfo()));
14248       }
14249     }
14250 
14251     // If the function implicitly returns zero (like 'main') or is naked,
14252     // don't complain about missing return statements.
14253     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14254       WP.disableCheckFallThrough();
14255 
14256     // MSVC permits the use of pure specifier (=0) on function definition,
14257     // defined at class scope, warn about this non-standard construct.
14258     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14259       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14260 
14261     if (!FD->isInvalidDecl()) {
14262       // Don't diagnose unused parameters of defaulted or deleted functions.
14263       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14264         DiagnoseUnusedParameters(FD->parameters());
14265       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14266                                              FD->getReturnType(), FD);
14267 
14268       // If this is a structor, we need a vtable.
14269       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14270         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14271       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14272         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14273 
14274       // Try to apply the named return value optimization. We have to check
14275       // if we can do this here because lambdas keep return statements around
14276       // to deduce an implicit return type.
14277       if (FD->getReturnType()->isRecordType() &&
14278           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14279         computeNRVO(Body, getCurFunction());
14280     }
14281 
14282     // GNU warning -Wmissing-prototypes:
14283     //   Warn if a global function is defined without a previous
14284     //   prototype declaration. This warning is issued even if the
14285     //   definition itself provides a prototype. The aim is to detect
14286     //   global functions that fail to be declared in header files.
14287     const FunctionDecl *PossiblePrototype = nullptr;
14288     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14289       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14290 
14291       if (PossiblePrototype) {
14292         // We found a declaration that is not a prototype,
14293         // but that could be a zero-parameter prototype
14294         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14295           TypeLoc TL = TI->getTypeLoc();
14296           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14297             Diag(PossiblePrototype->getLocation(),
14298                  diag::note_declaration_not_a_prototype)
14299                 << (FD->getNumParams() != 0)
14300                 << (FD->getNumParams() == 0
14301                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14302                         : FixItHint{});
14303         }
14304       } else {
14305         // Returns true if the token beginning at this Loc is `const`.
14306         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14307                                 const LangOptions &LangOpts) {
14308           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14309           if (LocInfo.first.isInvalid())
14310             return false;
14311 
14312           bool Invalid = false;
14313           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14314           if (Invalid)
14315             return false;
14316 
14317           if (LocInfo.second > Buffer.size())
14318             return false;
14319 
14320           const char *LexStart = Buffer.data() + LocInfo.second;
14321           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14322 
14323           return StartTok.consume_front("const") &&
14324                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14325                   StartTok.startswith("/*") || StartTok.startswith("//"));
14326         };
14327 
14328         auto findBeginLoc = [&]() {
14329           // If the return type has `const` qualifier, we want to insert
14330           // `static` before `const` (and not before the typename).
14331           if ((FD->getReturnType()->isAnyPointerType() &&
14332                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14333               FD->getReturnType().isConstQualified()) {
14334             // But only do this if we can determine where the `const` is.
14335 
14336             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14337                              getLangOpts()))
14338 
14339               return FD->getBeginLoc();
14340           }
14341           return FD->getTypeSpecStartLoc();
14342         };
14343         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14344             << /* function */ 1
14345             << (FD->getStorageClass() == SC_None
14346                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14347                     : FixItHint{});
14348       }
14349 
14350       // GNU warning -Wstrict-prototypes
14351       //   Warn if K&R function is defined without a previous declaration.
14352       //   This warning is issued only if the definition itself does not provide
14353       //   a prototype. Only K&R definitions do not provide a prototype.
14354       if (!FD->hasWrittenPrototype()) {
14355         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14356         TypeLoc TL = TI->getTypeLoc();
14357         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14358         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14359       }
14360     }
14361 
14362     // Warn on CPUDispatch with an actual body.
14363     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14364       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14365         if (!CmpndBody->body_empty())
14366           Diag(CmpndBody->body_front()->getBeginLoc(),
14367                diag::warn_dispatch_body_ignored);
14368 
14369     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14370       const CXXMethodDecl *KeyFunction;
14371       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14372           MD->isVirtual() &&
14373           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14374           MD == KeyFunction->getCanonicalDecl()) {
14375         // Update the key-function state if necessary for this ABI.
14376         if (FD->isInlined() &&
14377             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14378           Context.setNonKeyFunction(MD);
14379 
14380           // If the newly-chosen key function is already defined, then we
14381           // need to mark the vtable as used retroactively.
14382           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14383           const FunctionDecl *Definition;
14384           if (KeyFunction && KeyFunction->isDefined(Definition))
14385             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14386         } else {
14387           // We just defined they key function; mark the vtable as used.
14388           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14389         }
14390       }
14391     }
14392 
14393     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14394            "Function parsing confused");
14395   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14396     assert(MD == getCurMethodDecl() && "Method parsing confused");
14397     MD->setBody(Body);
14398     if (!MD->isInvalidDecl()) {
14399       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14400                                              MD->getReturnType(), MD);
14401 
14402       if (Body)
14403         computeNRVO(Body, getCurFunction());
14404     }
14405     if (getCurFunction()->ObjCShouldCallSuper) {
14406       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14407           << MD->getSelector().getAsString();
14408       getCurFunction()->ObjCShouldCallSuper = false;
14409     }
14410     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14411       const ObjCMethodDecl *InitMethod = nullptr;
14412       bool isDesignated =
14413           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14414       assert(isDesignated && InitMethod);
14415       (void)isDesignated;
14416 
14417       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14418         auto IFace = MD->getClassInterface();
14419         if (!IFace)
14420           return false;
14421         auto SuperD = IFace->getSuperClass();
14422         if (!SuperD)
14423           return false;
14424         return SuperD->getIdentifier() ==
14425             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14426       };
14427       // Don't issue this warning for unavailable inits or direct subclasses
14428       // of NSObject.
14429       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14430         Diag(MD->getLocation(),
14431              diag::warn_objc_designated_init_missing_super_call);
14432         Diag(InitMethod->getLocation(),
14433              diag::note_objc_designated_init_marked_here);
14434       }
14435       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14436     }
14437     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14438       // Don't issue this warning for unavaialable inits.
14439       if (!MD->isUnavailable())
14440         Diag(MD->getLocation(),
14441              diag::warn_objc_secondary_init_missing_init_call);
14442       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14443     }
14444 
14445     diagnoseImplicitlyRetainedSelf(*this);
14446   } else {
14447     // Parsing the function declaration failed in some way. Pop the fake scope
14448     // we pushed on.
14449     PopFunctionScopeInfo(ActivePolicy, dcl);
14450     return nullptr;
14451   }
14452 
14453   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14454     DiagnoseUnguardedAvailabilityViolations(dcl);
14455 
14456   assert(!getCurFunction()->ObjCShouldCallSuper &&
14457          "This should only be set for ObjC methods, which should have been "
14458          "handled in the block above.");
14459 
14460   // Verify and clean out per-function state.
14461   if (Body && (!FD || !FD->isDefaulted())) {
14462     // C++ constructors that have function-try-blocks can't have return
14463     // statements in the handlers of that block. (C++ [except.handle]p14)
14464     // Verify this.
14465     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14466       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14467 
14468     // Verify that gotos and switch cases don't jump into scopes illegally.
14469     if (getCurFunction()->NeedsScopeChecking() &&
14470         !PP.isCodeCompletionEnabled())
14471       DiagnoseInvalidJumps(Body);
14472 
14473     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14474       if (!Destructor->getParent()->isDependentType())
14475         CheckDestructor(Destructor);
14476 
14477       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14478                                              Destructor->getParent());
14479     }
14480 
14481     // If any errors have occurred, clear out any temporaries that may have
14482     // been leftover. This ensures that these temporaries won't be picked up for
14483     // deletion in some later function.
14484     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14485         getDiagnostics().getSuppressAllDiagnostics()) {
14486       DiscardCleanupsInEvaluationContext();
14487     }
14488     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14489         !isa<FunctionTemplateDecl>(dcl)) {
14490       // Since the body is valid, issue any analysis-based warnings that are
14491       // enabled.
14492       ActivePolicy = &WP;
14493     }
14494 
14495     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14496         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14497       FD->setInvalidDecl();
14498 
14499     if (FD && FD->hasAttr<NakedAttr>()) {
14500       for (const Stmt *S : Body->children()) {
14501         // Allow local register variables without initializer as they don't
14502         // require prologue.
14503         bool RegisterVariables = false;
14504         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14505           for (const auto *Decl : DS->decls()) {
14506             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14507               RegisterVariables =
14508                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14509               if (!RegisterVariables)
14510                 break;
14511             }
14512           }
14513         }
14514         if (RegisterVariables)
14515           continue;
14516         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14517           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14518           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14519           FD->setInvalidDecl();
14520           break;
14521         }
14522       }
14523     }
14524 
14525     assert(ExprCleanupObjects.size() ==
14526                ExprEvalContexts.back().NumCleanupObjects &&
14527            "Leftover temporaries in function");
14528     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14529     assert(MaybeODRUseExprs.empty() &&
14530            "Leftover expressions for odr-use checking");
14531   }
14532 
14533   if (!IsInstantiation)
14534     PopDeclContext();
14535 
14536   PopFunctionScopeInfo(ActivePolicy, dcl);
14537   // If any errors have occurred, clear out any temporaries that may have
14538   // been leftover. This ensures that these temporaries won't be picked up for
14539   // deletion in some later function.
14540   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14541     DiscardCleanupsInEvaluationContext();
14542   }
14543 
14544   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14545     auto ES = getEmissionStatus(FD);
14546     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14547         ES == Sema::FunctionEmissionStatus::Unknown)
14548       DeclsToCheckForDeferredDiags.push_back(FD);
14549   }
14550 
14551   return dcl;
14552 }
14553 
14554 /// When we finish delayed parsing of an attribute, we must attach it to the
14555 /// relevant Decl.
14556 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14557                                        ParsedAttributes &Attrs) {
14558   // Always attach attributes to the underlying decl.
14559   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14560     D = TD->getTemplatedDecl();
14561   ProcessDeclAttributeList(S, D, Attrs);
14562 
14563   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14564     if (Method->isStatic())
14565       checkThisInStaticMemberFunctionAttributes(Method);
14566 }
14567 
14568 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14569 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14570 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14571                                           IdentifierInfo &II, Scope *S) {
14572   // Find the scope in which the identifier is injected and the corresponding
14573   // DeclContext.
14574   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14575   // In that case, we inject the declaration into the translation unit scope
14576   // instead.
14577   Scope *BlockScope = S;
14578   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14579     BlockScope = BlockScope->getParent();
14580 
14581   Scope *ContextScope = BlockScope;
14582   while (!ContextScope->getEntity())
14583     ContextScope = ContextScope->getParent();
14584   ContextRAII SavedContext(*this, ContextScope->getEntity());
14585 
14586   // Before we produce a declaration for an implicitly defined
14587   // function, see whether there was a locally-scoped declaration of
14588   // this name as a function or variable. If so, use that
14589   // (non-visible) declaration, and complain about it.
14590   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14591   if (ExternCPrev) {
14592     // We still need to inject the function into the enclosing block scope so
14593     // that later (non-call) uses can see it.
14594     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14595 
14596     // C89 footnote 38:
14597     //   If in fact it is not defined as having type "function returning int",
14598     //   the behavior is undefined.
14599     if (!isa<FunctionDecl>(ExternCPrev) ||
14600         !Context.typesAreCompatible(
14601             cast<FunctionDecl>(ExternCPrev)->getType(),
14602             Context.getFunctionNoProtoType(Context.IntTy))) {
14603       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14604           << ExternCPrev << !getLangOpts().C99;
14605       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14606       return ExternCPrev;
14607     }
14608   }
14609 
14610   // Extension in C99.  Legal in C90, but warn about it.
14611   unsigned diag_id;
14612   if (II.getName().startswith("__builtin_"))
14613     diag_id = diag::warn_builtin_unknown;
14614   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14615   else if (getLangOpts().OpenCL)
14616     diag_id = diag::err_opencl_implicit_function_decl;
14617   else if (getLangOpts().C99)
14618     diag_id = diag::ext_implicit_function_decl;
14619   else
14620     diag_id = diag::warn_implicit_function_decl;
14621   Diag(Loc, diag_id) << &II;
14622 
14623   // If we found a prior declaration of this function, don't bother building
14624   // another one. We've already pushed that one into scope, so there's nothing
14625   // more to do.
14626   if (ExternCPrev)
14627     return ExternCPrev;
14628 
14629   // Because typo correction is expensive, only do it if the implicit
14630   // function declaration is going to be treated as an error.
14631   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14632     TypoCorrection Corrected;
14633     DeclFilterCCC<FunctionDecl> CCC{};
14634     if (S && (Corrected =
14635                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14636                               S, nullptr, CCC, CTK_NonError)))
14637       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14638                    /*ErrorRecovery*/false);
14639   }
14640 
14641   // Set a Declarator for the implicit definition: int foo();
14642   const char *Dummy;
14643   AttributeFactory attrFactory;
14644   DeclSpec DS(attrFactory);
14645   unsigned DiagID;
14646   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14647                                   Context.getPrintingPolicy());
14648   (void)Error; // Silence warning.
14649   assert(!Error && "Error setting up implicit decl!");
14650   SourceLocation NoLoc;
14651   Declarator D(DS, DeclaratorContext::BlockContext);
14652   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14653                                              /*IsAmbiguous=*/false,
14654                                              /*LParenLoc=*/NoLoc,
14655                                              /*Params=*/nullptr,
14656                                              /*NumParams=*/0,
14657                                              /*EllipsisLoc=*/NoLoc,
14658                                              /*RParenLoc=*/NoLoc,
14659                                              /*RefQualifierIsLvalueRef=*/true,
14660                                              /*RefQualifierLoc=*/NoLoc,
14661                                              /*MutableLoc=*/NoLoc, EST_None,
14662                                              /*ESpecRange=*/SourceRange(),
14663                                              /*Exceptions=*/nullptr,
14664                                              /*ExceptionRanges=*/nullptr,
14665                                              /*NumExceptions=*/0,
14666                                              /*NoexceptExpr=*/nullptr,
14667                                              /*ExceptionSpecTokens=*/nullptr,
14668                                              /*DeclsInPrototype=*/None, Loc,
14669                                              Loc, D),
14670                 std::move(DS.getAttributes()), SourceLocation());
14671   D.SetIdentifier(&II, Loc);
14672 
14673   // Insert this function into the enclosing block scope.
14674   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14675   FD->setImplicit();
14676 
14677   AddKnownFunctionAttributes(FD);
14678 
14679   return FD;
14680 }
14681 
14682 /// If this function is a C++ replaceable global allocation function
14683 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14684 /// adds any function attributes that we know a priori based on the standard.
14685 ///
14686 /// We need to check for duplicate attributes both here and where user-written
14687 /// attributes are applied to declarations.
14688 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14689     FunctionDecl *FD) {
14690   if (FD->isInvalidDecl())
14691     return;
14692 
14693   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14694       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14695     return;
14696 
14697   Optional<unsigned> AlignmentParam;
14698   bool IsNothrow = false;
14699   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14700     return;
14701 
14702   // C++2a [basic.stc.dynamic.allocation]p4:
14703   //   An allocation function that has a non-throwing exception specification
14704   //   indicates failure by returning a null pointer value. Any other allocation
14705   //   function never returns a null pointer value and indicates failure only by
14706   //   throwing an exception [...]
14707   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14708     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14709 
14710   // C++2a [basic.stc.dynamic.allocation]p2:
14711   //   An allocation function attempts to allocate the requested amount of
14712   //   storage. [...] If the request succeeds, the value returned by a
14713   //   replaceable allocation function is a [...] pointer value p0 different
14714   //   from any previously returned value p1 [...]
14715   //
14716   // However, this particular information is being added in codegen,
14717   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14718 
14719   // C++2a [basic.stc.dynamic.allocation]p2:
14720   //   An allocation function attempts to allocate the requested amount of
14721   //   storage. If it is successful, it returns the address of the start of a
14722   //   block of storage whose length in bytes is at least as large as the
14723   //   requested size.
14724   if (!FD->hasAttr<AllocSizeAttr>()) {
14725     FD->addAttr(AllocSizeAttr::CreateImplicit(
14726         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14727         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14728   }
14729 
14730   // C++2a [basic.stc.dynamic.allocation]p3:
14731   //   For an allocation function [...], the pointer returned on a successful
14732   //   call shall represent the address of storage that is aligned as follows:
14733   //   (3.1) If the allocation function takes an argument of type
14734   //         std​::​align_­val_­t, the storage will have the alignment
14735   //         specified by the value of this argument.
14736   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14737     FD->addAttr(AllocAlignAttr::CreateImplicit(
14738         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14739   }
14740 
14741   // FIXME:
14742   // C++2a [basic.stc.dynamic.allocation]p3:
14743   //   For an allocation function [...], the pointer returned on a successful
14744   //   call shall represent the address of storage that is aligned as follows:
14745   //   (3.2) Otherwise, if the allocation function is named operator new[],
14746   //         the storage is aligned for any object that does not have
14747   //         new-extended alignment ([basic.align]) and is no larger than the
14748   //         requested size.
14749   //   (3.3) Otherwise, the storage is aligned for any object that does not
14750   //         have new-extended alignment and is of the requested size.
14751 }
14752 
14753 /// Adds any function attributes that we know a priori based on
14754 /// the declaration of this function.
14755 ///
14756 /// These attributes can apply both to implicitly-declared builtins
14757 /// (like __builtin___printf_chk) or to library-declared functions
14758 /// like NSLog or printf.
14759 ///
14760 /// We need to check for duplicate attributes both here and where user-written
14761 /// attributes are applied to declarations.
14762 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14763   if (FD->isInvalidDecl())
14764     return;
14765 
14766   // If this is a built-in function, map its builtin attributes to
14767   // actual attributes.
14768   if (unsigned BuiltinID = FD->getBuiltinID()) {
14769     // Handle printf-formatting attributes.
14770     unsigned FormatIdx;
14771     bool HasVAListArg;
14772     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14773       if (!FD->hasAttr<FormatAttr>()) {
14774         const char *fmt = "printf";
14775         unsigned int NumParams = FD->getNumParams();
14776         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14777             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14778           fmt = "NSString";
14779         FD->addAttr(FormatAttr::CreateImplicit(Context,
14780                                                &Context.Idents.get(fmt),
14781                                                FormatIdx+1,
14782                                                HasVAListArg ? 0 : FormatIdx+2,
14783                                                FD->getLocation()));
14784       }
14785     }
14786     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14787                                              HasVAListArg)) {
14788      if (!FD->hasAttr<FormatAttr>())
14789        FD->addAttr(FormatAttr::CreateImplicit(Context,
14790                                               &Context.Idents.get("scanf"),
14791                                               FormatIdx+1,
14792                                               HasVAListArg ? 0 : FormatIdx+2,
14793                                               FD->getLocation()));
14794     }
14795 
14796     // Handle automatically recognized callbacks.
14797     SmallVector<int, 4> Encoding;
14798     if (!FD->hasAttr<CallbackAttr>() &&
14799         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14800       FD->addAttr(CallbackAttr::CreateImplicit(
14801           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14802 
14803     // Mark const if we don't care about errno and that is the only thing
14804     // preventing the function from being const. This allows IRgen to use LLVM
14805     // intrinsics for such functions.
14806     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14807         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14808       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14809 
14810     // We make "fma" on some platforms const because we know it does not set
14811     // errno in those environments even though it could set errno based on the
14812     // C standard.
14813     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14814     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14815         !FD->hasAttr<ConstAttr>()) {
14816       switch (BuiltinID) {
14817       case Builtin::BI__builtin_fma:
14818       case Builtin::BI__builtin_fmaf:
14819       case Builtin::BI__builtin_fmal:
14820       case Builtin::BIfma:
14821       case Builtin::BIfmaf:
14822       case Builtin::BIfmal:
14823         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14824         break;
14825       default:
14826         break;
14827       }
14828     }
14829 
14830     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14831         !FD->hasAttr<ReturnsTwiceAttr>())
14832       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14833                                          FD->getLocation()));
14834     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14835       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14836     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14837       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14838     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14839       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14840     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14841         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14842       // Add the appropriate attribute, depending on the CUDA compilation mode
14843       // and which target the builtin belongs to. For example, during host
14844       // compilation, aux builtins are __device__, while the rest are __host__.
14845       if (getLangOpts().CUDAIsDevice !=
14846           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14847         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14848       else
14849         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14850     }
14851   }
14852 
14853   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14854 
14855   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14856   // throw, add an implicit nothrow attribute to any extern "C" function we come
14857   // across.
14858   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14859       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14860     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14861     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14862       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14863   }
14864 
14865   IdentifierInfo *Name = FD->getIdentifier();
14866   if (!Name)
14867     return;
14868   if ((!getLangOpts().CPlusPlus &&
14869        FD->getDeclContext()->isTranslationUnit()) ||
14870       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14871        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14872        LinkageSpecDecl::lang_c)) {
14873     // Okay: this could be a libc/libm/Objective-C function we know
14874     // about.
14875   } else
14876     return;
14877 
14878   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14879     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14880     // target-specific builtins, perhaps?
14881     if (!FD->hasAttr<FormatAttr>())
14882       FD->addAttr(FormatAttr::CreateImplicit(Context,
14883                                              &Context.Idents.get("printf"), 2,
14884                                              Name->isStr("vasprintf") ? 0 : 3,
14885                                              FD->getLocation()));
14886   }
14887 
14888   if (Name->isStr("__CFStringMakeConstantString")) {
14889     // We already have a __builtin___CFStringMakeConstantString,
14890     // but builds that use -fno-constant-cfstrings don't go through that.
14891     if (!FD->hasAttr<FormatArgAttr>())
14892       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14893                                                 FD->getLocation()));
14894   }
14895 }
14896 
14897 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14898                                     TypeSourceInfo *TInfo) {
14899   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14900   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14901 
14902   if (!TInfo) {
14903     assert(D.isInvalidType() && "no declarator info for valid type");
14904     TInfo = Context.getTrivialTypeSourceInfo(T);
14905   }
14906 
14907   // Scope manipulation handled by caller.
14908   TypedefDecl *NewTD =
14909       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14910                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14911 
14912   // Bail out immediately if we have an invalid declaration.
14913   if (D.isInvalidType()) {
14914     NewTD->setInvalidDecl();
14915     return NewTD;
14916   }
14917 
14918   if (D.getDeclSpec().isModulePrivateSpecified()) {
14919     if (CurContext->isFunctionOrMethod())
14920       Diag(NewTD->getLocation(), diag::err_module_private_local)
14921           << 2 << NewTD
14922           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14923           << FixItHint::CreateRemoval(
14924                  D.getDeclSpec().getModulePrivateSpecLoc());
14925     else
14926       NewTD->setModulePrivate();
14927   }
14928 
14929   // C++ [dcl.typedef]p8:
14930   //   If the typedef declaration defines an unnamed class (or
14931   //   enum), the first typedef-name declared by the declaration
14932   //   to be that class type (or enum type) is used to denote the
14933   //   class type (or enum type) for linkage purposes only.
14934   // We need to check whether the type was declared in the declaration.
14935   switch (D.getDeclSpec().getTypeSpecType()) {
14936   case TST_enum:
14937   case TST_struct:
14938   case TST_interface:
14939   case TST_union:
14940   case TST_class: {
14941     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14942     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14943     break;
14944   }
14945 
14946   default:
14947     break;
14948   }
14949 
14950   return NewTD;
14951 }
14952 
14953 /// Check that this is a valid underlying type for an enum declaration.
14954 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14955   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14956   QualType T = TI->getType();
14957 
14958   if (T->isDependentType())
14959     return false;
14960 
14961   // This doesn't use 'isIntegralType' despite the error message mentioning
14962   // integral type because isIntegralType would also allow enum types in C.
14963   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14964     if (BT->isInteger())
14965       return false;
14966 
14967   if (T->isExtIntType())
14968     return false;
14969 
14970   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14971 }
14972 
14973 /// Check whether this is a valid redeclaration of a previous enumeration.
14974 /// \return true if the redeclaration was invalid.
14975 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14976                                   QualType EnumUnderlyingTy, bool IsFixed,
14977                                   const EnumDecl *Prev) {
14978   if (IsScoped != Prev->isScoped()) {
14979     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14980       << Prev->isScoped();
14981     Diag(Prev->getLocation(), diag::note_previous_declaration);
14982     return true;
14983   }
14984 
14985   if (IsFixed && Prev->isFixed()) {
14986     if (!EnumUnderlyingTy->isDependentType() &&
14987         !Prev->getIntegerType()->isDependentType() &&
14988         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14989                                         Prev->getIntegerType())) {
14990       // TODO: Highlight the underlying type of the redeclaration.
14991       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14992         << EnumUnderlyingTy << Prev->getIntegerType();
14993       Diag(Prev->getLocation(), diag::note_previous_declaration)
14994           << Prev->getIntegerTypeRange();
14995       return true;
14996     }
14997   } else if (IsFixed != Prev->isFixed()) {
14998     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14999       << Prev->isFixed();
15000     Diag(Prev->getLocation(), diag::note_previous_declaration);
15001     return true;
15002   }
15003 
15004   return false;
15005 }
15006 
15007 /// Get diagnostic %select index for tag kind for
15008 /// redeclaration diagnostic message.
15009 /// WARNING: Indexes apply to particular diagnostics only!
15010 ///
15011 /// \returns diagnostic %select index.
15012 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15013   switch (Tag) {
15014   case TTK_Struct: return 0;
15015   case TTK_Interface: return 1;
15016   case TTK_Class:  return 2;
15017   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15018   }
15019 }
15020 
15021 /// Determine if tag kind is a class-key compatible with
15022 /// class for redeclaration (class, struct, or __interface).
15023 ///
15024 /// \returns true iff the tag kind is compatible.
15025 static bool isClassCompatTagKind(TagTypeKind Tag)
15026 {
15027   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15028 }
15029 
15030 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15031                                              TagTypeKind TTK) {
15032   if (isa<TypedefDecl>(PrevDecl))
15033     return NTK_Typedef;
15034   else if (isa<TypeAliasDecl>(PrevDecl))
15035     return NTK_TypeAlias;
15036   else if (isa<ClassTemplateDecl>(PrevDecl))
15037     return NTK_Template;
15038   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15039     return NTK_TypeAliasTemplate;
15040   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15041     return NTK_TemplateTemplateArgument;
15042   switch (TTK) {
15043   case TTK_Struct:
15044   case TTK_Interface:
15045   case TTK_Class:
15046     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15047   case TTK_Union:
15048     return NTK_NonUnion;
15049   case TTK_Enum:
15050     return NTK_NonEnum;
15051   }
15052   llvm_unreachable("invalid TTK");
15053 }
15054 
15055 /// Determine whether a tag with a given kind is acceptable
15056 /// as a redeclaration of the given tag declaration.
15057 ///
15058 /// \returns true if the new tag kind is acceptable, false otherwise.
15059 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15060                                         TagTypeKind NewTag, bool isDefinition,
15061                                         SourceLocation NewTagLoc,
15062                                         const IdentifierInfo *Name) {
15063   // C++ [dcl.type.elab]p3:
15064   //   The class-key or enum keyword present in the
15065   //   elaborated-type-specifier shall agree in kind with the
15066   //   declaration to which the name in the elaborated-type-specifier
15067   //   refers. This rule also applies to the form of
15068   //   elaborated-type-specifier that declares a class-name or
15069   //   friend class since it can be construed as referring to the
15070   //   definition of the class. Thus, in any
15071   //   elaborated-type-specifier, the enum keyword shall be used to
15072   //   refer to an enumeration (7.2), the union class-key shall be
15073   //   used to refer to a union (clause 9), and either the class or
15074   //   struct class-key shall be used to refer to a class (clause 9)
15075   //   declared using the class or struct class-key.
15076   TagTypeKind OldTag = Previous->getTagKind();
15077   if (OldTag != NewTag &&
15078       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15079     return false;
15080 
15081   // Tags are compatible, but we might still want to warn on mismatched tags.
15082   // Non-class tags can't be mismatched at this point.
15083   if (!isClassCompatTagKind(NewTag))
15084     return true;
15085 
15086   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15087   // by our warning analysis. We don't want to warn about mismatches with (eg)
15088   // declarations in system headers that are designed to be specialized, but if
15089   // a user asks us to warn, we should warn if their code contains mismatched
15090   // declarations.
15091   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15092     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15093                                       Loc);
15094   };
15095   if (IsIgnoredLoc(NewTagLoc))
15096     return true;
15097 
15098   auto IsIgnored = [&](const TagDecl *Tag) {
15099     return IsIgnoredLoc(Tag->getLocation());
15100   };
15101   while (IsIgnored(Previous)) {
15102     Previous = Previous->getPreviousDecl();
15103     if (!Previous)
15104       return true;
15105     OldTag = Previous->getTagKind();
15106   }
15107 
15108   bool isTemplate = false;
15109   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15110     isTemplate = Record->getDescribedClassTemplate();
15111 
15112   if (inTemplateInstantiation()) {
15113     if (OldTag != NewTag) {
15114       // In a template instantiation, do not offer fix-its for tag mismatches
15115       // since they usually mess up the template instead of fixing the problem.
15116       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15117         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15118         << getRedeclDiagFromTagKind(OldTag);
15119       // FIXME: Note previous location?
15120     }
15121     return true;
15122   }
15123 
15124   if (isDefinition) {
15125     // On definitions, check all previous tags and issue a fix-it for each
15126     // one that doesn't match the current tag.
15127     if (Previous->getDefinition()) {
15128       // Don't suggest fix-its for redefinitions.
15129       return true;
15130     }
15131 
15132     bool previousMismatch = false;
15133     for (const TagDecl *I : Previous->redecls()) {
15134       if (I->getTagKind() != NewTag) {
15135         // Ignore previous declarations for which the warning was disabled.
15136         if (IsIgnored(I))
15137           continue;
15138 
15139         if (!previousMismatch) {
15140           previousMismatch = true;
15141           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15142             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15143             << getRedeclDiagFromTagKind(I->getTagKind());
15144         }
15145         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15146           << getRedeclDiagFromTagKind(NewTag)
15147           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15148                TypeWithKeyword::getTagTypeKindName(NewTag));
15149       }
15150     }
15151     return true;
15152   }
15153 
15154   // Identify the prevailing tag kind: this is the kind of the definition (if
15155   // there is a non-ignored definition), or otherwise the kind of the prior
15156   // (non-ignored) declaration.
15157   const TagDecl *PrevDef = Previous->getDefinition();
15158   if (PrevDef && IsIgnored(PrevDef))
15159     PrevDef = nullptr;
15160   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15161   if (Redecl->getTagKind() != NewTag) {
15162     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15163       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15164       << getRedeclDiagFromTagKind(OldTag);
15165     Diag(Redecl->getLocation(), diag::note_previous_use);
15166 
15167     // If there is a previous definition, suggest a fix-it.
15168     if (PrevDef) {
15169       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15170         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15171         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15172              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15173     }
15174   }
15175 
15176   return true;
15177 }
15178 
15179 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15180 /// from an outer enclosing namespace or file scope inside a friend declaration.
15181 /// This should provide the commented out code in the following snippet:
15182 ///   namespace N {
15183 ///     struct X;
15184 ///     namespace M {
15185 ///       struct Y { friend struct /*N::*/ X; };
15186 ///     }
15187 ///   }
15188 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15189                                          SourceLocation NameLoc) {
15190   // While the decl is in a namespace, do repeated lookup of that name and see
15191   // if we get the same namespace back.  If we do not, continue until
15192   // translation unit scope, at which point we have a fully qualified NNS.
15193   SmallVector<IdentifierInfo *, 4> Namespaces;
15194   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15195   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15196     // This tag should be declared in a namespace, which can only be enclosed by
15197     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15198     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15199     if (!Namespace || Namespace->isAnonymousNamespace())
15200       return FixItHint();
15201     IdentifierInfo *II = Namespace->getIdentifier();
15202     Namespaces.push_back(II);
15203     NamedDecl *Lookup = SemaRef.LookupSingleName(
15204         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15205     if (Lookup == Namespace)
15206       break;
15207   }
15208 
15209   // Once we have all the namespaces, reverse them to go outermost first, and
15210   // build an NNS.
15211   SmallString<64> Insertion;
15212   llvm::raw_svector_ostream OS(Insertion);
15213   if (DC->isTranslationUnit())
15214     OS << "::";
15215   std::reverse(Namespaces.begin(), Namespaces.end());
15216   for (auto *II : Namespaces)
15217     OS << II->getName() << "::";
15218   return FixItHint::CreateInsertion(NameLoc, Insertion);
15219 }
15220 
15221 /// Determine whether a tag originally declared in context \p OldDC can
15222 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15223 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15224 /// using-declaration).
15225 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15226                                          DeclContext *NewDC) {
15227   OldDC = OldDC->getRedeclContext();
15228   NewDC = NewDC->getRedeclContext();
15229 
15230   if (OldDC->Equals(NewDC))
15231     return true;
15232 
15233   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15234   // encloses the other).
15235   if (S.getLangOpts().MSVCCompat &&
15236       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15237     return true;
15238 
15239   return false;
15240 }
15241 
15242 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15243 /// former case, Name will be non-null.  In the later case, Name will be null.
15244 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15245 /// reference/declaration/definition of a tag.
15246 ///
15247 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15248 /// trailing-type-specifier) other than one in an alias-declaration.
15249 ///
15250 /// \param SkipBody If non-null, will be set to indicate if the caller should
15251 /// skip the definition of this tag and treat it as if it were a declaration.
15252 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15253                      SourceLocation KWLoc, CXXScopeSpec &SS,
15254                      IdentifierInfo *Name, SourceLocation NameLoc,
15255                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15256                      SourceLocation ModulePrivateLoc,
15257                      MultiTemplateParamsArg TemplateParameterLists,
15258                      bool &OwnedDecl, bool &IsDependent,
15259                      SourceLocation ScopedEnumKWLoc,
15260                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15261                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15262                      SkipBodyInfo *SkipBody) {
15263   // If this is not a definition, it must have a name.
15264   IdentifierInfo *OrigName = Name;
15265   assert((Name != nullptr || TUK == TUK_Definition) &&
15266          "Nameless record must be a definition!");
15267   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15268 
15269   OwnedDecl = false;
15270   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15271   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15272 
15273   // FIXME: Check member specializations more carefully.
15274   bool isMemberSpecialization = false;
15275   bool Invalid = false;
15276 
15277   // We only need to do this matching if we have template parameters
15278   // or a scope specifier, which also conveniently avoids this work
15279   // for non-C++ cases.
15280   if (TemplateParameterLists.size() > 0 ||
15281       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15282     if (TemplateParameterList *TemplateParams =
15283             MatchTemplateParametersToScopeSpecifier(
15284                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15285                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15286       if (Kind == TTK_Enum) {
15287         Diag(KWLoc, diag::err_enum_template);
15288         return nullptr;
15289       }
15290 
15291       if (TemplateParams->size() > 0) {
15292         // This is a declaration or definition of a class template (which may
15293         // be a member of another template).
15294 
15295         if (Invalid)
15296           return nullptr;
15297 
15298         OwnedDecl = false;
15299         DeclResult Result = CheckClassTemplate(
15300             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15301             AS, ModulePrivateLoc,
15302             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15303             TemplateParameterLists.data(), SkipBody);
15304         return Result.get();
15305       } else {
15306         // The "template<>" header is extraneous.
15307         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15308           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15309         isMemberSpecialization = true;
15310       }
15311     }
15312 
15313     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15314         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15315       return nullptr;
15316   }
15317 
15318   // Figure out the underlying type if this a enum declaration. We need to do
15319   // this early, because it's needed to detect if this is an incompatible
15320   // redeclaration.
15321   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15322   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15323 
15324   if (Kind == TTK_Enum) {
15325     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15326       // No underlying type explicitly specified, or we failed to parse the
15327       // type, default to int.
15328       EnumUnderlying = Context.IntTy.getTypePtr();
15329     } else if (UnderlyingType.get()) {
15330       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15331       // integral type; any cv-qualification is ignored.
15332       TypeSourceInfo *TI = nullptr;
15333       GetTypeFromParser(UnderlyingType.get(), &TI);
15334       EnumUnderlying = TI;
15335 
15336       if (CheckEnumUnderlyingType(TI))
15337         // Recover by falling back to int.
15338         EnumUnderlying = Context.IntTy.getTypePtr();
15339 
15340       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15341                                           UPPC_FixedUnderlyingType))
15342         EnumUnderlying = Context.IntTy.getTypePtr();
15343 
15344     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15345       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15346       // of 'int'. However, if this is an unfixed forward declaration, don't set
15347       // the underlying type unless the user enables -fms-compatibility. This
15348       // makes unfixed forward declared enums incomplete and is more conforming.
15349       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15350         EnumUnderlying = Context.IntTy.getTypePtr();
15351     }
15352   }
15353 
15354   DeclContext *SearchDC = CurContext;
15355   DeclContext *DC = CurContext;
15356   bool isStdBadAlloc = false;
15357   bool isStdAlignValT = false;
15358 
15359   RedeclarationKind Redecl = forRedeclarationInCurContext();
15360   if (TUK == TUK_Friend || TUK == TUK_Reference)
15361     Redecl = NotForRedeclaration;
15362 
15363   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15364   /// implemented asks for structural equivalence checking, the returned decl
15365   /// here is passed back to the parser, allowing the tag body to be parsed.
15366   auto createTagFromNewDecl = [&]() -> TagDecl * {
15367     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15368     // If there is an identifier, use the location of the identifier as the
15369     // location of the decl, otherwise use the location of the struct/union
15370     // keyword.
15371     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15372     TagDecl *New = nullptr;
15373 
15374     if (Kind == TTK_Enum) {
15375       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15376                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15377       // If this is an undefined enum, bail.
15378       if (TUK != TUK_Definition && !Invalid)
15379         return nullptr;
15380       if (EnumUnderlying) {
15381         EnumDecl *ED = cast<EnumDecl>(New);
15382         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15383           ED->setIntegerTypeSourceInfo(TI);
15384         else
15385           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15386         ED->setPromotionType(ED->getIntegerType());
15387       }
15388     } else { // struct/union
15389       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15390                                nullptr);
15391     }
15392 
15393     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15394       // Add alignment attributes if necessary; these attributes are checked
15395       // when the ASTContext lays out the structure.
15396       //
15397       // It is important for implementing the correct semantics that this
15398       // happen here (in ActOnTag). The #pragma pack stack is
15399       // maintained as a result of parser callbacks which can occur at
15400       // many points during the parsing of a struct declaration (because
15401       // the #pragma tokens are effectively skipped over during the
15402       // parsing of the struct).
15403       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15404         AddAlignmentAttributesForRecord(RD);
15405         AddMsStructLayoutForRecord(RD);
15406       }
15407     }
15408     New->setLexicalDeclContext(CurContext);
15409     return New;
15410   };
15411 
15412   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15413   if (Name && SS.isNotEmpty()) {
15414     // We have a nested-name tag ('struct foo::bar').
15415 
15416     // Check for invalid 'foo::'.
15417     if (SS.isInvalid()) {
15418       Name = nullptr;
15419       goto CreateNewDecl;
15420     }
15421 
15422     // If this is a friend or a reference to a class in a dependent
15423     // context, don't try to make a decl for it.
15424     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15425       DC = computeDeclContext(SS, false);
15426       if (!DC) {
15427         IsDependent = true;
15428         return nullptr;
15429       }
15430     } else {
15431       DC = computeDeclContext(SS, true);
15432       if (!DC) {
15433         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15434           << SS.getRange();
15435         return nullptr;
15436       }
15437     }
15438 
15439     if (RequireCompleteDeclContext(SS, DC))
15440       return nullptr;
15441 
15442     SearchDC = DC;
15443     // Look-up name inside 'foo::'.
15444     LookupQualifiedName(Previous, DC);
15445 
15446     if (Previous.isAmbiguous())
15447       return nullptr;
15448 
15449     if (Previous.empty()) {
15450       // Name lookup did not find anything. However, if the
15451       // nested-name-specifier refers to the current instantiation,
15452       // and that current instantiation has any dependent base
15453       // classes, we might find something at instantiation time: treat
15454       // this as a dependent elaborated-type-specifier.
15455       // But this only makes any sense for reference-like lookups.
15456       if (Previous.wasNotFoundInCurrentInstantiation() &&
15457           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15458         IsDependent = true;
15459         return nullptr;
15460       }
15461 
15462       // A tag 'foo::bar' must already exist.
15463       Diag(NameLoc, diag::err_not_tag_in_scope)
15464         << Kind << Name << DC << SS.getRange();
15465       Name = nullptr;
15466       Invalid = true;
15467       goto CreateNewDecl;
15468     }
15469   } else if (Name) {
15470     // C++14 [class.mem]p14:
15471     //   If T is the name of a class, then each of the following shall have a
15472     //   name different from T:
15473     //    -- every member of class T that is itself a type
15474     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15475         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15476       return nullptr;
15477 
15478     // If this is a named struct, check to see if there was a previous forward
15479     // declaration or definition.
15480     // FIXME: We're looking into outer scopes here, even when we
15481     // shouldn't be. Doing so can result in ambiguities that we
15482     // shouldn't be diagnosing.
15483     LookupName(Previous, S);
15484 
15485     // When declaring or defining a tag, ignore ambiguities introduced
15486     // by types using'ed into this scope.
15487     if (Previous.isAmbiguous() &&
15488         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15489       LookupResult::Filter F = Previous.makeFilter();
15490       while (F.hasNext()) {
15491         NamedDecl *ND = F.next();
15492         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15493                 SearchDC->getRedeclContext()))
15494           F.erase();
15495       }
15496       F.done();
15497     }
15498 
15499     // C++11 [namespace.memdef]p3:
15500     //   If the name in a friend declaration is neither qualified nor
15501     //   a template-id and the declaration is a function or an
15502     //   elaborated-type-specifier, the lookup to determine whether
15503     //   the entity has been previously declared shall not consider
15504     //   any scopes outside the innermost enclosing namespace.
15505     //
15506     // MSVC doesn't implement the above rule for types, so a friend tag
15507     // declaration may be a redeclaration of a type declared in an enclosing
15508     // scope.  They do implement this rule for friend functions.
15509     //
15510     // Does it matter that this should be by scope instead of by
15511     // semantic context?
15512     if (!Previous.empty() && TUK == TUK_Friend) {
15513       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15514       LookupResult::Filter F = Previous.makeFilter();
15515       bool FriendSawTagOutsideEnclosingNamespace = false;
15516       while (F.hasNext()) {
15517         NamedDecl *ND = F.next();
15518         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15519         if (DC->isFileContext() &&
15520             !EnclosingNS->Encloses(ND->getDeclContext())) {
15521           if (getLangOpts().MSVCCompat)
15522             FriendSawTagOutsideEnclosingNamespace = true;
15523           else
15524             F.erase();
15525         }
15526       }
15527       F.done();
15528 
15529       // Diagnose this MSVC extension in the easy case where lookup would have
15530       // unambiguously found something outside the enclosing namespace.
15531       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15532         NamedDecl *ND = Previous.getFoundDecl();
15533         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15534             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15535       }
15536     }
15537 
15538     // Note:  there used to be some attempt at recovery here.
15539     if (Previous.isAmbiguous())
15540       return nullptr;
15541 
15542     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15543       // FIXME: This makes sure that we ignore the contexts associated
15544       // with C structs, unions, and enums when looking for a matching
15545       // tag declaration or definition. See the similar lookup tweak
15546       // in Sema::LookupName; is there a better way to deal with this?
15547       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15548         SearchDC = SearchDC->getParent();
15549     }
15550   }
15551 
15552   if (Previous.isSingleResult() &&
15553       Previous.getFoundDecl()->isTemplateParameter()) {
15554     // Maybe we will complain about the shadowed template parameter.
15555     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15556     // Just pretend that we didn't see the previous declaration.
15557     Previous.clear();
15558   }
15559 
15560   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15561       DC->Equals(getStdNamespace())) {
15562     if (Name->isStr("bad_alloc")) {
15563       // This is a declaration of or a reference to "std::bad_alloc".
15564       isStdBadAlloc = true;
15565 
15566       // If std::bad_alloc has been implicitly declared (but made invisible to
15567       // name lookup), fill in this implicit declaration as the previous
15568       // declaration, so that the declarations get chained appropriately.
15569       if (Previous.empty() && StdBadAlloc)
15570         Previous.addDecl(getStdBadAlloc());
15571     } else if (Name->isStr("align_val_t")) {
15572       isStdAlignValT = true;
15573       if (Previous.empty() && StdAlignValT)
15574         Previous.addDecl(getStdAlignValT());
15575     }
15576   }
15577 
15578   // If we didn't find a previous declaration, and this is a reference
15579   // (or friend reference), move to the correct scope.  In C++, we
15580   // also need to do a redeclaration lookup there, just in case
15581   // there's a shadow friend decl.
15582   if (Name && Previous.empty() &&
15583       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15584     if (Invalid) goto CreateNewDecl;
15585     assert(SS.isEmpty());
15586 
15587     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15588       // C++ [basic.scope.pdecl]p5:
15589       //   -- for an elaborated-type-specifier of the form
15590       //
15591       //          class-key identifier
15592       //
15593       //      if the elaborated-type-specifier is used in the
15594       //      decl-specifier-seq or parameter-declaration-clause of a
15595       //      function defined in namespace scope, the identifier is
15596       //      declared as a class-name in the namespace that contains
15597       //      the declaration; otherwise, except as a friend
15598       //      declaration, the identifier is declared in the smallest
15599       //      non-class, non-function-prototype scope that contains the
15600       //      declaration.
15601       //
15602       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15603       // C structs and unions.
15604       //
15605       // It is an error in C++ to declare (rather than define) an enum
15606       // type, including via an elaborated type specifier.  We'll
15607       // diagnose that later; for now, declare the enum in the same
15608       // scope as we would have picked for any other tag type.
15609       //
15610       // GNU C also supports this behavior as part of its incomplete
15611       // enum types extension, while GNU C++ does not.
15612       //
15613       // Find the context where we'll be declaring the tag.
15614       // FIXME: We would like to maintain the current DeclContext as the
15615       // lexical context,
15616       SearchDC = getTagInjectionContext(SearchDC);
15617 
15618       // Find the scope where we'll be declaring the tag.
15619       S = getTagInjectionScope(S, getLangOpts());
15620     } else {
15621       assert(TUK == TUK_Friend);
15622       // C++ [namespace.memdef]p3:
15623       //   If a friend declaration in a non-local class first declares a
15624       //   class or function, the friend class or function is a member of
15625       //   the innermost enclosing namespace.
15626       SearchDC = SearchDC->getEnclosingNamespaceContext();
15627     }
15628 
15629     // In C++, we need to do a redeclaration lookup to properly
15630     // diagnose some problems.
15631     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15632     // hidden declaration so that we don't get ambiguity errors when using a
15633     // type declared by an elaborated-type-specifier.  In C that is not correct
15634     // and we should instead merge compatible types found by lookup.
15635     if (getLangOpts().CPlusPlus) {
15636       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15637       LookupQualifiedName(Previous, SearchDC);
15638     } else {
15639       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15640       LookupName(Previous, S);
15641     }
15642   }
15643 
15644   // If we have a known previous declaration to use, then use it.
15645   if (Previous.empty() && SkipBody && SkipBody->Previous)
15646     Previous.addDecl(SkipBody->Previous);
15647 
15648   if (!Previous.empty()) {
15649     NamedDecl *PrevDecl = Previous.getFoundDecl();
15650     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15651 
15652     // It's okay to have a tag decl in the same scope as a typedef
15653     // which hides a tag decl in the same scope.  Finding this
15654     // insanity with a redeclaration lookup can only actually happen
15655     // in C++.
15656     //
15657     // This is also okay for elaborated-type-specifiers, which is
15658     // technically forbidden by the current standard but which is
15659     // okay according to the likely resolution of an open issue;
15660     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15661     if (getLangOpts().CPlusPlus) {
15662       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15663         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15664           TagDecl *Tag = TT->getDecl();
15665           if (Tag->getDeclName() == Name &&
15666               Tag->getDeclContext()->getRedeclContext()
15667                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15668             PrevDecl = Tag;
15669             Previous.clear();
15670             Previous.addDecl(Tag);
15671             Previous.resolveKind();
15672           }
15673         }
15674       }
15675     }
15676 
15677     // If this is a redeclaration of a using shadow declaration, it must
15678     // declare a tag in the same context. In MSVC mode, we allow a
15679     // redefinition if either context is within the other.
15680     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15681       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15682       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15683           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15684           !(OldTag && isAcceptableTagRedeclContext(
15685                           *this, OldTag->getDeclContext(), SearchDC))) {
15686         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15687         Diag(Shadow->getTargetDecl()->getLocation(),
15688              diag::note_using_decl_target);
15689         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15690             << 0;
15691         // Recover by ignoring the old declaration.
15692         Previous.clear();
15693         goto CreateNewDecl;
15694       }
15695     }
15696 
15697     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15698       // If this is a use of a previous tag, or if the tag is already declared
15699       // in the same scope (so that the definition/declaration completes or
15700       // rementions the tag), reuse the decl.
15701       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15702           isDeclInScope(DirectPrevDecl, SearchDC, S,
15703                         SS.isNotEmpty() || isMemberSpecialization)) {
15704         // Make sure that this wasn't declared as an enum and now used as a
15705         // struct or something similar.
15706         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15707                                           TUK == TUK_Definition, KWLoc,
15708                                           Name)) {
15709           bool SafeToContinue
15710             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15711                Kind != TTK_Enum);
15712           if (SafeToContinue)
15713             Diag(KWLoc, diag::err_use_with_wrong_tag)
15714               << Name
15715               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15716                                               PrevTagDecl->getKindName());
15717           else
15718             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15719           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15720 
15721           if (SafeToContinue)
15722             Kind = PrevTagDecl->getTagKind();
15723           else {
15724             // Recover by making this an anonymous redefinition.
15725             Name = nullptr;
15726             Previous.clear();
15727             Invalid = true;
15728           }
15729         }
15730 
15731         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15732           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15733           if (TUK == TUK_Reference || TUK == TUK_Friend)
15734             return PrevTagDecl;
15735 
15736           QualType EnumUnderlyingTy;
15737           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15738             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15739           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15740             EnumUnderlyingTy = QualType(T, 0);
15741 
15742           // All conflicts with previous declarations are recovered by
15743           // returning the previous declaration, unless this is a definition,
15744           // in which case we want the caller to bail out.
15745           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15746                                      ScopedEnum, EnumUnderlyingTy,
15747                                      IsFixed, PrevEnum))
15748             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15749         }
15750 
15751         // C++11 [class.mem]p1:
15752         //   A member shall not be declared twice in the member-specification,
15753         //   except that a nested class or member class template can be declared
15754         //   and then later defined.
15755         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15756             S->isDeclScope(PrevDecl)) {
15757           Diag(NameLoc, diag::ext_member_redeclared);
15758           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15759         }
15760 
15761         if (!Invalid) {
15762           // If this is a use, just return the declaration we found, unless
15763           // we have attributes.
15764           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15765             if (!Attrs.empty()) {
15766               // FIXME: Diagnose these attributes. For now, we create a new
15767               // declaration to hold them.
15768             } else if (TUK == TUK_Reference &&
15769                        (PrevTagDecl->getFriendObjectKind() ==
15770                             Decl::FOK_Undeclared ||
15771                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15772                        SS.isEmpty()) {
15773               // This declaration is a reference to an existing entity, but
15774               // has different visibility from that entity: it either makes
15775               // a friend visible or it makes a type visible in a new module.
15776               // In either case, create a new declaration. We only do this if
15777               // the declaration would have meant the same thing if no prior
15778               // declaration were found, that is, if it was found in the same
15779               // scope where we would have injected a declaration.
15780               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15781                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15782                 return PrevTagDecl;
15783               // This is in the injected scope, create a new declaration in
15784               // that scope.
15785               S = getTagInjectionScope(S, getLangOpts());
15786             } else {
15787               return PrevTagDecl;
15788             }
15789           }
15790 
15791           // Diagnose attempts to redefine a tag.
15792           if (TUK == TUK_Definition) {
15793             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15794               // If we're defining a specialization and the previous definition
15795               // is from an implicit instantiation, don't emit an error
15796               // here; we'll catch this in the general case below.
15797               bool IsExplicitSpecializationAfterInstantiation = false;
15798               if (isMemberSpecialization) {
15799                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15800                   IsExplicitSpecializationAfterInstantiation =
15801                     RD->getTemplateSpecializationKind() !=
15802                     TSK_ExplicitSpecialization;
15803                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15804                   IsExplicitSpecializationAfterInstantiation =
15805                     ED->getTemplateSpecializationKind() !=
15806                     TSK_ExplicitSpecialization;
15807               }
15808 
15809               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15810               // not keep more that one definition around (merge them). However,
15811               // ensure the decl passes the structural compatibility check in
15812               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15813               NamedDecl *Hidden = nullptr;
15814               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15815                 // There is a definition of this tag, but it is not visible. We
15816                 // explicitly make use of C++'s one definition rule here, and
15817                 // assume that this definition is identical to the hidden one
15818                 // we already have. Make the existing definition visible and
15819                 // use it in place of this one.
15820                 if (!getLangOpts().CPlusPlus) {
15821                   // Postpone making the old definition visible until after we
15822                   // complete parsing the new one and do the structural
15823                   // comparison.
15824                   SkipBody->CheckSameAsPrevious = true;
15825                   SkipBody->New = createTagFromNewDecl();
15826                   SkipBody->Previous = Def;
15827                   return Def;
15828                 } else {
15829                   SkipBody->ShouldSkip = true;
15830                   SkipBody->Previous = Def;
15831                   makeMergedDefinitionVisible(Hidden);
15832                   // Carry on and handle it like a normal definition. We'll
15833                   // skip starting the definitiion later.
15834                 }
15835               } else if (!IsExplicitSpecializationAfterInstantiation) {
15836                 // A redeclaration in function prototype scope in C isn't
15837                 // visible elsewhere, so merely issue a warning.
15838                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15839                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15840                 else
15841                   Diag(NameLoc, diag::err_redefinition) << Name;
15842                 notePreviousDefinition(Def,
15843                                        NameLoc.isValid() ? NameLoc : KWLoc);
15844                 // If this is a redefinition, recover by making this
15845                 // struct be anonymous, which will make any later
15846                 // references get the previous definition.
15847                 Name = nullptr;
15848                 Previous.clear();
15849                 Invalid = true;
15850               }
15851             } else {
15852               // If the type is currently being defined, complain
15853               // about a nested redefinition.
15854               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15855               if (TD->isBeingDefined()) {
15856                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15857                 Diag(PrevTagDecl->getLocation(),
15858                      diag::note_previous_definition);
15859                 Name = nullptr;
15860                 Previous.clear();
15861                 Invalid = true;
15862               }
15863             }
15864 
15865             // Okay, this is definition of a previously declared or referenced
15866             // tag. We're going to create a new Decl for it.
15867           }
15868 
15869           // Okay, we're going to make a redeclaration.  If this is some kind
15870           // of reference, make sure we build the redeclaration in the same DC
15871           // as the original, and ignore the current access specifier.
15872           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15873             SearchDC = PrevTagDecl->getDeclContext();
15874             AS = AS_none;
15875           }
15876         }
15877         // If we get here we have (another) forward declaration or we
15878         // have a definition.  Just create a new decl.
15879 
15880       } else {
15881         // If we get here, this is a definition of a new tag type in a nested
15882         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15883         // new decl/type.  We set PrevDecl to NULL so that the entities
15884         // have distinct types.
15885         Previous.clear();
15886       }
15887       // If we get here, we're going to create a new Decl. If PrevDecl
15888       // is non-NULL, it's a definition of the tag declared by
15889       // PrevDecl. If it's NULL, we have a new definition.
15890 
15891     // Otherwise, PrevDecl is not a tag, but was found with tag
15892     // lookup.  This is only actually possible in C++, where a few
15893     // things like templates still live in the tag namespace.
15894     } else {
15895       // Use a better diagnostic if an elaborated-type-specifier
15896       // found the wrong kind of type on the first
15897       // (non-redeclaration) lookup.
15898       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15899           !Previous.isForRedeclaration()) {
15900         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15901         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15902                                                        << Kind;
15903         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15904         Invalid = true;
15905 
15906       // Otherwise, only diagnose if the declaration is in scope.
15907       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15908                                 SS.isNotEmpty() || isMemberSpecialization)) {
15909         // do nothing
15910 
15911       // Diagnose implicit declarations introduced by elaborated types.
15912       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15913         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15914         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15915         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15916         Invalid = true;
15917 
15918       // Otherwise it's a declaration.  Call out a particularly common
15919       // case here.
15920       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15921         unsigned Kind = 0;
15922         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15923         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15924           << Name << Kind << TND->getUnderlyingType();
15925         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15926         Invalid = true;
15927 
15928       // Otherwise, diagnose.
15929       } else {
15930         // The tag name clashes with something else in the target scope,
15931         // issue an error and recover by making this tag be anonymous.
15932         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15933         notePreviousDefinition(PrevDecl, NameLoc);
15934         Name = nullptr;
15935         Invalid = true;
15936       }
15937 
15938       // The existing declaration isn't relevant to us; we're in a
15939       // new scope, so clear out the previous declaration.
15940       Previous.clear();
15941     }
15942   }
15943 
15944 CreateNewDecl:
15945 
15946   TagDecl *PrevDecl = nullptr;
15947   if (Previous.isSingleResult())
15948     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15949 
15950   // If there is an identifier, use the location of the identifier as the
15951   // location of the decl, otherwise use the location of the struct/union
15952   // keyword.
15953   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15954 
15955   // Otherwise, create a new declaration. If there is a previous
15956   // declaration of the same entity, the two will be linked via
15957   // PrevDecl.
15958   TagDecl *New;
15959 
15960   if (Kind == TTK_Enum) {
15961     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15962     // enum X { A, B, C } D;    D should chain to X.
15963     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15964                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15965                            ScopedEnumUsesClassTag, IsFixed);
15966 
15967     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15968       StdAlignValT = cast<EnumDecl>(New);
15969 
15970     // If this is an undefined enum, warn.
15971     if (TUK != TUK_Definition && !Invalid) {
15972       TagDecl *Def;
15973       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15974         // C++0x: 7.2p2: opaque-enum-declaration.
15975         // Conflicts are diagnosed above. Do nothing.
15976       }
15977       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15978         Diag(Loc, diag::ext_forward_ref_enum_def)
15979           << New;
15980         Diag(Def->getLocation(), diag::note_previous_definition);
15981       } else {
15982         unsigned DiagID = diag::ext_forward_ref_enum;
15983         if (getLangOpts().MSVCCompat)
15984           DiagID = diag::ext_ms_forward_ref_enum;
15985         else if (getLangOpts().CPlusPlus)
15986           DiagID = diag::err_forward_ref_enum;
15987         Diag(Loc, DiagID);
15988       }
15989     }
15990 
15991     if (EnumUnderlying) {
15992       EnumDecl *ED = cast<EnumDecl>(New);
15993       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15994         ED->setIntegerTypeSourceInfo(TI);
15995       else
15996         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15997       ED->setPromotionType(ED->getIntegerType());
15998       assert(ED->isComplete() && "enum with type should be complete");
15999     }
16000   } else {
16001     // struct/union/class
16002 
16003     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16004     // struct X { int A; } D;    D should chain to X.
16005     if (getLangOpts().CPlusPlus) {
16006       // FIXME: Look for a way to use RecordDecl for simple structs.
16007       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16008                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16009 
16010       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16011         StdBadAlloc = cast<CXXRecordDecl>(New);
16012     } else
16013       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16014                                cast_or_null<RecordDecl>(PrevDecl));
16015   }
16016 
16017   // C++11 [dcl.type]p3:
16018   //   A type-specifier-seq shall not define a class or enumeration [...].
16019   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16020       TUK == TUK_Definition) {
16021     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16022       << Context.getTagDeclType(New);
16023     Invalid = true;
16024   }
16025 
16026   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16027       DC->getDeclKind() == Decl::Enum) {
16028     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16029       << Context.getTagDeclType(New);
16030     Invalid = true;
16031   }
16032 
16033   // Maybe add qualifier info.
16034   if (SS.isNotEmpty()) {
16035     if (SS.isSet()) {
16036       // If this is either a declaration or a definition, check the
16037       // nested-name-specifier against the current context.
16038       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16039           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16040                                        isMemberSpecialization))
16041         Invalid = true;
16042 
16043       New->setQualifierInfo(SS.getWithLocInContext(Context));
16044       if (TemplateParameterLists.size() > 0) {
16045         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16046       }
16047     }
16048     else
16049       Invalid = true;
16050   }
16051 
16052   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16053     // Add alignment attributes if necessary; these attributes are checked when
16054     // the ASTContext lays out the structure.
16055     //
16056     // It is important for implementing the correct semantics that this
16057     // happen here (in ActOnTag). The #pragma pack stack is
16058     // maintained as a result of parser callbacks which can occur at
16059     // many points during the parsing of a struct declaration (because
16060     // the #pragma tokens are effectively skipped over during the
16061     // parsing of the struct).
16062     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16063       AddAlignmentAttributesForRecord(RD);
16064       AddMsStructLayoutForRecord(RD);
16065     }
16066   }
16067 
16068   if (ModulePrivateLoc.isValid()) {
16069     if (isMemberSpecialization)
16070       Diag(New->getLocation(), diag::err_module_private_specialization)
16071         << 2
16072         << FixItHint::CreateRemoval(ModulePrivateLoc);
16073     // __module_private__ does not apply to local classes. However, we only
16074     // diagnose this as an error when the declaration specifiers are
16075     // freestanding. Here, we just ignore the __module_private__.
16076     else if (!SearchDC->isFunctionOrMethod())
16077       New->setModulePrivate();
16078   }
16079 
16080   // If this is a specialization of a member class (of a class template),
16081   // check the specialization.
16082   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16083     Invalid = true;
16084 
16085   // If we're declaring or defining a tag in function prototype scope in C,
16086   // note that this type can only be used within the function and add it to
16087   // the list of decls to inject into the function definition scope.
16088   if ((Name || Kind == TTK_Enum) &&
16089       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16090     if (getLangOpts().CPlusPlus) {
16091       // C++ [dcl.fct]p6:
16092       //   Types shall not be defined in return or parameter types.
16093       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16094         Diag(Loc, diag::err_type_defined_in_param_type)
16095             << Name;
16096         Invalid = true;
16097       }
16098     } else if (!PrevDecl) {
16099       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16100     }
16101   }
16102 
16103   if (Invalid)
16104     New->setInvalidDecl();
16105 
16106   // Set the lexical context. If the tag has a C++ scope specifier, the
16107   // lexical context will be different from the semantic context.
16108   New->setLexicalDeclContext(CurContext);
16109 
16110   // Mark this as a friend decl if applicable.
16111   // In Microsoft mode, a friend declaration also acts as a forward
16112   // declaration so we always pass true to setObjectOfFriendDecl to make
16113   // the tag name visible.
16114   if (TUK == TUK_Friend)
16115     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16116 
16117   // Set the access specifier.
16118   if (!Invalid && SearchDC->isRecord())
16119     SetMemberAccessSpecifier(New, PrevDecl, AS);
16120 
16121   if (PrevDecl)
16122     CheckRedeclarationModuleOwnership(New, PrevDecl);
16123 
16124   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16125     New->startDefinition();
16126 
16127   ProcessDeclAttributeList(S, New, Attrs);
16128   AddPragmaAttributes(S, New);
16129 
16130   // If this has an identifier, add it to the scope stack.
16131   if (TUK == TUK_Friend) {
16132     // We might be replacing an existing declaration in the lookup tables;
16133     // if so, borrow its access specifier.
16134     if (PrevDecl)
16135       New->setAccess(PrevDecl->getAccess());
16136 
16137     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16138     DC->makeDeclVisibleInContext(New);
16139     if (Name) // can be null along some error paths
16140       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16141         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16142   } else if (Name) {
16143     S = getNonFieldDeclScope(S);
16144     PushOnScopeChains(New, S, true);
16145   } else {
16146     CurContext->addDecl(New);
16147   }
16148 
16149   // If this is the C FILE type, notify the AST context.
16150   if (IdentifierInfo *II = New->getIdentifier())
16151     if (!New->isInvalidDecl() &&
16152         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16153         II->isStr("FILE"))
16154       Context.setFILEDecl(New);
16155 
16156   if (PrevDecl)
16157     mergeDeclAttributes(New, PrevDecl);
16158 
16159   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16160     inferGslOwnerPointerAttribute(CXXRD);
16161 
16162   // If there's a #pragma GCC visibility in scope, set the visibility of this
16163   // record.
16164   AddPushedVisibilityAttribute(New);
16165 
16166   if (isMemberSpecialization && !New->isInvalidDecl())
16167     CompleteMemberSpecialization(New, Previous);
16168 
16169   OwnedDecl = true;
16170   // In C++, don't return an invalid declaration. We can't recover well from
16171   // the cases where we make the type anonymous.
16172   if (Invalid && getLangOpts().CPlusPlus) {
16173     if (New->isBeingDefined())
16174       if (auto RD = dyn_cast<RecordDecl>(New))
16175         RD->completeDefinition();
16176     return nullptr;
16177   } else if (SkipBody && SkipBody->ShouldSkip) {
16178     return SkipBody->Previous;
16179   } else {
16180     return New;
16181   }
16182 }
16183 
16184 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16185   AdjustDeclIfTemplate(TagD);
16186   TagDecl *Tag = cast<TagDecl>(TagD);
16187 
16188   // Enter the tag context.
16189   PushDeclContext(S, Tag);
16190 
16191   ActOnDocumentableDecl(TagD);
16192 
16193   // If there's a #pragma GCC visibility in scope, set the visibility of this
16194   // record.
16195   AddPushedVisibilityAttribute(Tag);
16196 }
16197 
16198 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16199                                     SkipBodyInfo &SkipBody) {
16200   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16201     return false;
16202 
16203   // Make the previous decl visible.
16204   makeMergedDefinitionVisible(SkipBody.Previous);
16205   return true;
16206 }
16207 
16208 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16209   assert(isa<ObjCContainerDecl>(IDecl) &&
16210          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16211   DeclContext *OCD = cast<DeclContext>(IDecl);
16212   assert(OCD->getLexicalParent() == CurContext &&
16213       "The next DeclContext should be lexically contained in the current one.");
16214   CurContext = OCD;
16215   return IDecl;
16216 }
16217 
16218 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16219                                            SourceLocation FinalLoc,
16220                                            bool IsFinalSpelledSealed,
16221                                            SourceLocation LBraceLoc) {
16222   AdjustDeclIfTemplate(TagD);
16223   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16224 
16225   FieldCollector->StartClass();
16226 
16227   if (!Record->getIdentifier())
16228     return;
16229 
16230   if (FinalLoc.isValid())
16231     Record->addAttr(FinalAttr::Create(
16232         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16233         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16234 
16235   // C++ [class]p2:
16236   //   [...] The class-name is also inserted into the scope of the
16237   //   class itself; this is known as the injected-class-name. For
16238   //   purposes of access checking, the injected-class-name is treated
16239   //   as if it were a public member name.
16240   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16241       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16242       Record->getLocation(), Record->getIdentifier(),
16243       /*PrevDecl=*/nullptr,
16244       /*DelayTypeCreation=*/true);
16245   Context.getTypeDeclType(InjectedClassName, Record);
16246   InjectedClassName->setImplicit();
16247   InjectedClassName->setAccess(AS_public);
16248   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16249       InjectedClassName->setDescribedClassTemplate(Template);
16250   PushOnScopeChains(InjectedClassName, S);
16251   assert(InjectedClassName->isInjectedClassName() &&
16252          "Broken injected-class-name");
16253 }
16254 
16255 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16256                                     SourceRange BraceRange) {
16257   AdjustDeclIfTemplate(TagD);
16258   TagDecl *Tag = cast<TagDecl>(TagD);
16259   Tag->setBraceRange(BraceRange);
16260 
16261   // Make sure we "complete" the definition even it is invalid.
16262   if (Tag->isBeingDefined()) {
16263     assert(Tag->isInvalidDecl() && "We should already have completed it");
16264     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16265       RD->completeDefinition();
16266   }
16267 
16268   if (isa<CXXRecordDecl>(Tag)) {
16269     FieldCollector->FinishClass();
16270   }
16271 
16272   // Exit this scope of this tag's definition.
16273   PopDeclContext();
16274 
16275   if (getCurLexicalContext()->isObjCContainer() &&
16276       Tag->getDeclContext()->isFileContext())
16277     Tag->setTopLevelDeclInObjCContainer();
16278 
16279   // Notify the consumer that we've defined a tag.
16280   if (!Tag->isInvalidDecl())
16281     Consumer.HandleTagDeclDefinition(Tag);
16282 }
16283 
16284 void Sema::ActOnObjCContainerFinishDefinition() {
16285   // Exit this scope of this interface definition.
16286   PopDeclContext();
16287 }
16288 
16289 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16290   assert(DC == CurContext && "Mismatch of container contexts");
16291   OriginalLexicalContext = DC;
16292   ActOnObjCContainerFinishDefinition();
16293 }
16294 
16295 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16296   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16297   OriginalLexicalContext = nullptr;
16298 }
16299 
16300 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16301   AdjustDeclIfTemplate(TagD);
16302   TagDecl *Tag = cast<TagDecl>(TagD);
16303   Tag->setInvalidDecl();
16304 
16305   // Make sure we "complete" the definition even it is invalid.
16306   if (Tag->isBeingDefined()) {
16307     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16308       RD->completeDefinition();
16309   }
16310 
16311   // We're undoing ActOnTagStartDefinition here, not
16312   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16313   // the FieldCollector.
16314 
16315   PopDeclContext();
16316 }
16317 
16318 // Note that FieldName may be null for anonymous bitfields.
16319 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16320                                 IdentifierInfo *FieldName,
16321                                 QualType FieldTy, bool IsMsStruct,
16322                                 Expr *BitWidth, bool *ZeroWidth) {
16323   assert(BitWidth);
16324   if (BitWidth->containsErrors())
16325     return ExprError();
16326 
16327   // Default to true; that shouldn't confuse checks for emptiness
16328   if (ZeroWidth)
16329     *ZeroWidth = true;
16330 
16331   // C99 6.7.2.1p4 - verify the field type.
16332   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16333   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16334     // Handle incomplete and sizeless types with a specific error.
16335     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16336                                  diag::err_field_incomplete_or_sizeless))
16337       return ExprError();
16338     if (FieldName)
16339       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16340         << FieldName << FieldTy << BitWidth->getSourceRange();
16341     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16342       << FieldTy << BitWidth->getSourceRange();
16343   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16344                                              UPPC_BitFieldWidth))
16345     return ExprError();
16346 
16347   // If the bit-width is type- or value-dependent, don't try to check
16348   // it now.
16349   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16350     return BitWidth;
16351 
16352   llvm::APSInt Value;
16353   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16354   if (ICE.isInvalid())
16355     return ICE;
16356   BitWidth = ICE.get();
16357 
16358   if (Value != 0 && ZeroWidth)
16359     *ZeroWidth = false;
16360 
16361   // Zero-width bitfield is ok for anonymous field.
16362   if (Value == 0 && FieldName)
16363     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16364 
16365   if (Value.isSigned() && Value.isNegative()) {
16366     if (FieldName)
16367       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16368                << FieldName << Value.toString(10);
16369     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16370       << Value.toString(10);
16371   }
16372 
16373   if (!FieldTy->isDependentType()) {
16374     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16375     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16376     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16377 
16378     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16379     // ABI.
16380     bool CStdConstraintViolation =
16381         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16382     bool MSBitfieldViolation =
16383         Value.ugt(TypeStorageSize) &&
16384         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16385     if (CStdConstraintViolation || MSBitfieldViolation) {
16386       unsigned DiagWidth =
16387           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16388       if (FieldName)
16389         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16390                << FieldName << (unsigned)Value.getZExtValue()
16391                << !CStdConstraintViolation << DiagWidth;
16392 
16393       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16394              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16395              << DiagWidth;
16396     }
16397 
16398     // Warn on types where the user might conceivably expect to get all
16399     // specified bits as value bits: that's all integral types other than
16400     // 'bool'.
16401     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16402       if (FieldName)
16403         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16404             << FieldName << (unsigned)Value.getZExtValue()
16405             << (unsigned)TypeWidth;
16406       else
16407         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16408             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16409     }
16410   }
16411 
16412   return BitWidth;
16413 }
16414 
16415 /// ActOnField - Each field of a C struct/union is passed into this in order
16416 /// to create a FieldDecl object for it.
16417 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16418                        Declarator &D, Expr *BitfieldWidth) {
16419   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16420                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16421                                /*InitStyle=*/ICIS_NoInit, AS_public);
16422   return Res;
16423 }
16424 
16425 /// HandleField - Analyze a field of a C struct or a C++ data member.
16426 ///
16427 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16428                              SourceLocation DeclStart,
16429                              Declarator &D, Expr *BitWidth,
16430                              InClassInitStyle InitStyle,
16431                              AccessSpecifier AS) {
16432   if (D.isDecompositionDeclarator()) {
16433     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16434     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16435       << Decomp.getSourceRange();
16436     return nullptr;
16437   }
16438 
16439   IdentifierInfo *II = D.getIdentifier();
16440   SourceLocation Loc = DeclStart;
16441   if (II) Loc = D.getIdentifierLoc();
16442 
16443   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16444   QualType T = TInfo->getType();
16445   if (getLangOpts().CPlusPlus) {
16446     CheckExtraCXXDefaultArguments(D);
16447 
16448     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16449                                         UPPC_DataMemberType)) {
16450       D.setInvalidType();
16451       T = Context.IntTy;
16452       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16453     }
16454   }
16455 
16456   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16457 
16458   if (D.getDeclSpec().isInlineSpecified())
16459     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16460         << getLangOpts().CPlusPlus17;
16461   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16462     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16463          diag::err_invalid_thread)
16464       << DeclSpec::getSpecifierName(TSCS);
16465 
16466   // Check to see if this name was declared as a member previously
16467   NamedDecl *PrevDecl = nullptr;
16468   LookupResult Previous(*this, II, Loc, LookupMemberName,
16469                         ForVisibleRedeclaration);
16470   LookupName(Previous, S);
16471   switch (Previous.getResultKind()) {
16472     case LookupResult::Found:
16473     case LookupResult::FoundUnresolvedValue:
16474       PrevDecl = Previous.getAsSingle<NamedDecl>();
16475       break;
16476 
16477     case LookupResult::FoundOverloaded:
16478       PrevDecl = Previous.getRepresentativeDecl();
16479       break;
16480 
16481     case LookupResult::NotFound:
16482     case LookupResult::NotFoundInCurrentInstantiation:
16483     case LookupResult::Ambiguous:
16484       break;
16485   }
16486   Previous.suppressDiagnostics();
16487 
16488   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16489     // Maybe we will complain about the shadowed template parameter.
16490     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16491     // Just pretend that we didn't see the previous declaration.
16492     PrevDecl = nullptr;
16493   }
16494 
16495   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16496     PrevDecl = nullptr;
16497 
16498   bool Mutable
16499     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16500   SourceLocation TSSL = D.getBeginLoc();
16501   FieldDecl *NewFD
16502     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16503                      TSSL, AS, PrevDecl, &D);
16504 
16505   if (NewFD->isInvalidDecl())
16506     Record->setInvalidDecl();
16507 
16508   if (D.getDeclSpec().isModulePrivateSpecified())
16509     NewFD->setModulePrivate();
16510 
16511   if (NewFD->isInvalidDecl() && PrevDecl) {
16512     // Don't introduce NewFD into scope; there's already something
16513     // with the same name in the same scope.
16514   } else if (II) {
16515     PushOnScopeChains(NewFD, S);
16516   } else
16517     Record->addDecl(NewFD);
16518 
16519   return NewFD;
16520 }
16521 
16522 /// Build a new FieldDecl and check its well-formedness.
16523 ///
16524 /// This routine builds a new FieldDecl given the fields name, type,
16525 /// record, etc. \p PrevDecl should refer to any previous declaration
16526 /// with the same name and in the same scope as the field to be
16527 /// created.
16528 ///
16529 /// \returns a new FieldDecl.
16530 ///
16531 /// \todo The Declarator argument is a hack. It will be removed once
16532 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16533                                 TypeSourceInfo *TInfo,
16534                                 RecordDecl *Record, SourceLocation Loc,
16535                                 bool Mutable, Expr *BitWidth,
16536                                 InClassInitStyle InitStyle,
16537                                 SourceLocation TSSL,
16538                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16539                                 Declarator *D) {
16540   IdentifierInfo *II = Name.getAsIdentifierInfo();
16541   bool InvalidDecl = false;
16542   if (D) InvalidDecl = D->isInvalidType();
16543 
16544   // If we receive a broken type, recover by assuming 'int' and
16545   // marking this declaration as invalid.
16546   if (T.isNull() || T->containsErrors()) {
16547     InvalidDecl = true;
16548     T = Context.IntTy;
16549   }
16550 
16551   QualType EltTy = Context.getBaseElementType(T);
16552   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16553     if (RequireCompleteSizedType(Loc, EltTy,
16554                                  diag::err_field_incomplete_or_sizeless)) {
16555       // Fields of incomplete type force their record to be invalid.
16556       Record->setInvalidDecl();
16557       InvalidDecl = true;
16558     } else {
16559       NamedDecl *Def;
16560       EltTy->isIncompleteType(&Def);
16561       if (Def && Def->isInvalidDecl()) {
16562         Record->setInvalidDecl();
16563         InvalidDecl = true;
16564       }
16565     }
16566   }
16567 
16568   // TR 18037 does not allow fields to be declared with address space
16569   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16570       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16571     Diag(Loc, diag::err_field_with_address_space);
16572     Record->setInvalidDecl();
16573     InvalidDecl = true;
16574   }
16575 
16576   if (LangOpts.OpenCL) {
16577     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16578     // used as structure or union field: image, sampler, event or block types.
16579     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16580         T->isBlockPointerType()) {
16581       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16582       Record->setInvalidDecl();
16583       InvalidDecl = true;
16584     }
16585     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16586     if (BitWidth) {
16587       Diag(Loc, diag::err_opencl_bitfields);
16588       InvalidDecl = true;
16589     }
16590   }
16591 
16592   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16593   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16594       T.hasQualifiers()) {
16595     InvalidDecl = true;
16596     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16597   }
16598 
16599   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16600   // than a variably modified type.
16601   if (!InvalidDecl && T->isVariablyModifiedType()) {
16602     bool SizeIsNegative;
16603     llvm::APSInt Oversized;
16604 
16605     TypeSourceInfo *FixedTInfo =
16606       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16607                                                     SizeIsNegative,
16608                                                     Oversized);
16609     if (FixedTInfo) {
16610       Diag(Loc, diag::warn_illegal_constant_array_size);
16611       TInfo = FixedTInfo;
16612       T = FixedTInfo->getType();
16613     } else {
16614       if (SizeIsNegative)
16615         Diag(Loc, diag::err_typecheck_negative_array_size);
16616       else if (Oversized.getBoolValue())
16617         Diag(Loc, diag::err_array_too_large)
16618           << Oversized.toString(10);
16619       else
16620         Diag(Loc, diag::err_typecheck_field_variable_size);
16621       InvalidDecl = true;
16622     }
16623   }
16624 
16625   // Fields can not have abstract class types
16626   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16627                                              diag::err_abstract_type_in_decl,
16628                                              AbstractFieldType))
16629     InvalidDecl = true;
16630 
16631   bool ZeroWidth = false;
16632   if (InvalidDecl)
16633     BitWidth = nullptr;
16634   // If this is declared as a bit-field, check the bit-field.
16635   if (BitWidth) {
16636     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16637                               &ZeroWidth).get();
16638     if (!BitWidth) {
16639       InvalidDecl = true;
16640       BitWidth = nullptr;
16641       ZeroWidth = false;
16642     }
16643 
16644     // Only data members can have in-class initializers.
16645     if (BitWidth && !II && InitStyle) {
16646       Diag(Loc, diag::err_anon_bitfield_init);
16647       InvalidDecl = true;
16648       BitWidth = nullptr;
16649       ZeroWidth = false;
16650     }
16651   }
16652 
16653   // Check that 'mutable' is consistent with the type of the declaration.
16654   if (!InvalidDecl && Mutable) {
16655     unsigned DiagID = 0;
16656     if (T->isReferenceType())
16657       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16658                                         : diag::err_mutable_reference;
16659     else if (T.isConstQualified())
16660       DiagID = diag::err_mutable_const;
16661 
16662     if (DiagID) {
16663       SourceLocation ErrLoc = Loc;
16664       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16665         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16666       Diag(ErrLoc, DiagID);
16667       if (DiagID != diag::ext_mutable_reference) {
16668         Mutable = false;
16669         InvalidDecl = true;
16670       }
16671     }
16672   }
16673 
16674   // C++11 [class.union]p8 (DR1460):
16675   //   At most one variant member of a union may have a
16676   //   brace-or-equal-initializer.
16677   if (InitStyle != ICIS_NoInit)
16678     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16679 
16680   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16681                                        BitWidth, Mutable, InitStyle);
16682   if (InvalidDecl)
16683     NewFD->setInvalidDecl();
16684 
16685   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16686     Diag(Loc, diag::err_duplicate_member) << II;
16687     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16688     NewFD->setInvalidDecl();
16689   }
16690 
16691   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16692     if (Record->isUnion()) {
16693       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16694         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16695         if (RDecl->getDefinition()) {
16696           // C++ [class.union]p1: An object of a class with a non-trivial
16697           // constructor, a non-trivial copy constructor, a non-trivial
16698           // destructor, or a non-trivial copy assignment operator
16699           // cannot be a member of a union, nor can an array of such
16700           // objects.
16701           if (CheckNontrivialField(NewFD))
16702             NewFD->setInvalidDecl();
16703         }
16704       }
16705 
16706       // C++ [class.union]p1: If a union contains a member of reference type,
16707       // the program is ill-formed, except when compiling with MSVC extensions
16708       // enabled.
16709       if (EltTy->isReferenceType()) {
16710         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16711                                     diag::ext_union_member_of_reference_type :
16712                                     diag::err_union_member_of_reference_type)
16713           << NewFD->getDeclName() << EltTy;
16714         if (!getLangOpts().MicrosoftExt)
16715           NewFD->setInvalidDecl();
16716       }
16717     }
16718   }
16719 
16720   // FIXME: We need to pass in the attributes given an AST
16721   // representation, not a parser representation.
16722   if (D) {
16723     // FIXME: The current scope is almost... but not entirely... correct here.
16724     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16725 
16726     if (NewFD->hasAttrs())
16727       CheckAlignasUnderalignment(NewFD);
16728   }
16729 
16730   // In auto-retain/release, infer strong retension for fields of
16731   // retainable type.
16732   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16733     NewFD->setInvalidDecl();
16734 
16735   if (T.isObjCGCWeak())
16736     Diag(Loc, diag::warn_attribute_weak_on_field);
16737 
16738   NewFD->setAccess(AS);
16739   return NewFD;
16740 }
16741 
16742 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16743   assert(FD);
16744   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16745 
16746   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16747     return false;
16748 
16749   QualType EltTy = Context.getBaseElementType(FD->getType());
16750   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16751     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16752     if (RDecl->getDefinition()) {
16753       // We check for copy constructors before constructors
16754       // because otherwise we'll never get complaints about
16755       // copy constructors.
16756 
16757       CXXSpecialMember member = CXXInvalid;
16758       // We're required to check for any non-trivial constructors. Since the
16759       // implicit default constructor is suppressed if there are any
16760       // user-declared constructors, we just need to check that there is a
16761       // trivial default constructor and a trivial copy constructor. (We don't
16762       // worry about move constructors here, since this is a C++98 check.)
16763       if (RDecl->hasNonTrivialCopyConstructor())
16764         member = CXXCopyConstructor;
16765       else if (!RDecl->hasTrivialDefaultConstructor())
16766         member = CXXDefaultConstructor;
16767       else if (RDecl->hasNonTrivialCopyAssignment())
16768         member = CXXCopyAssignment;
16769       else if (RDecl->hasNonTrivialDestructor())
16770         member = CXXDestructor;
16771 
16772       if (member != CXXInvalid) {
16773         if (!getLangOpts().CPlusPlus11 &&
16774             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16775           // Objective-C++ ARC: it is an error to have a non-trivial field of
16776           // a union. However, system headers in Objective-C programs
16777           // occasionally have Objective-C lifetime objects within unions,
16778           // and rather than cause the program to fail, we make those
16779           // members unavailable.
16780           SourceLocation Loc = FD->getLocation();
16781           if (getSourceManager().isInSystemHeader(Loc)) {
16782             if (!FD->hasAttr<UnavailableAttr>())
16783               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16784                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16785             return false;
16786           }
16787         }
16788 
16789         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16790                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16791                diag::err_illegal_union_or_anon_struct_member)
16792           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16793         DiagnoseNontrivial(RDecl, member);
16794         return !getLangOpts().CPlusPlus11;
16795       }
16796     }
16797   }
16798 
16799   return false;
16800 }
16801 
16802 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16803 ///  AST enum value.
16804 static ObjCIvarDecl::AccessControl
16805 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16806   switch (ivarVisibility) {
16807   default: llvm_unreachable("Unknown visitibility kind");
16808   case tok::objc_private: return ObjCIvarDecl::Private;
16809   case tok::objc_public: return ObjCIvarDecl::Public;
16810   case tok::objc_protected: return ObjCIvarDecl::Protected;
16811   case tok::objc_package: return ObjCIvarDecl::Package;
16812   }
16813 }
16814 
16815 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16816 /// in order to create an IvarDecl object for it.
16817 Decl *Sema::ActOnIvar(Scope *S,
16818                                 SourceLocation DeclStart,
16819                                 Declarator &D, Expr *BitfieldWidth,
16820                                 tok::ObjCKeywordKind Visibility) {
16821 
16822   IdentifierInfo *II = D.getIdentifier();
16823   Expr *BitWidth = (Expr*)BitfieldWidth;
16824   SourceLocation Loc = DeclStart;
16825   if (II) Loc = D.getIdentifierLoc();
16826 
16827   // FIXME: Unnamed fields can be handled in various different ways, for
16828   // example, unnamed unions inject all members into the struct namespace!
16829 
16830   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16831   QualType T = TInfo->getType();
16832 
16833   if (BitWidth) {
16834     // 6.7.2.1p3, 6.7.2.1p4
16835     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16836     if (!BitWidth)
16837       D.setInvalidType();
16838   } else {
16839     // Not a bitfield.
16840 
16841     // validate II.
16842 
16843   }
16844   if (T->isReferenceType()) {
16845     Diag(Loc, diag::err_ivar_reference_type);
16846     D.setInvalidType();
16847   }
16848   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16849   // than a variably modified type.
16850   else if (T->isVariablyModifiedType()) {
16851     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16852     D.setInvalidType();
16853   }
16854 
16855   // Get the visibility (access control) for this ivar.
16856   ObjCIvarDecl::AccessControl ac =
16857     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16858                                         : ObjCIvarDecl::None;
16859   // Must set ivar's DeclContext to its enclosing interface.
16860   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16861   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16862     return nullptr;
16863   ObjCContainerDecl *EnclosingContext;
16864   if (ObjCImplementationDecl *IMPDecl =
16865       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16866     if (LangOpts.ObjCRuntime.isFragile()) {
16867     // Case of ivar declared in an implementation. Context is that of its class.
16868       EnclosingContext = IMPDecl->getClassInterface();
16869       assert(EnclosingContext && "Implementation has no class interface!");
16870     }
16871     else
16872       EnclosingContext = EnclosingDecl;
16873   } else {
16874     if (ObjCCategoryDecl *CDecl =
16875         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16876       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16877         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16878         return nullptr;
16879       }
16880     }
16881     EnclosingContext = EnclosingDecl;
16882   }
16883 
16884   // Construct the decl.
16885   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16886                                              DeclStart, Loc, II, T,
16887                                              TInfo, ac, (Expr *)BitfieldWidth);
16888 
16889   if (II) {
16890     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16891                                            ForVisibleRedeclaration);
16892     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16893         && !isa<TagDecl>(PrevDecl)) {
16894       Diag(Loc, diag::err_duplicate_member) << II;
16895       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16896       NewID->setInvalidDecl();
16897     }
16898   }
16899 
16900   // Process attributes attached to the ivar.
16901   ProcessDeclAttributes(S, NewID, D);
16902 
16903   if (D.isInvalidType())
16904     NewID->setInvalidDecl();
16905 
16906   // In ARC, infer 'retaining' for ivars of retainable type.
16907   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16908     NewID->setInvalidDecl();
16909 
16910   if (D.getDeclSpec().isModulePrivateSpecified())
16911     NewID->setModulePrivate();
16912 
16913   if (II) {
16914     // FIXME: When interfaces are DeclContexts, we'll need to add
16915     // these to the interface.
16916     S->AddDecl(NewID);
16917     IdResolver.AddDecl(NewID);
16918   }
16919 
16920   if (LangOpts.ObjCRuntime.isNonFragile() &&
16921       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16922     Diag(Loc, diag::warn_ivars_in_interface);
16923 
16924   return NewID;
16925 }
16926 
16927 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16928 /// class and class extensions. For every class \@interface and class
16929 /// extension \@interface, if the last ivar is a bitfield of any type,
16930 /// then add an implicit `char :0` ivar to the end of that interface.
16931 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16932                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16933   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16934     return;
16935 
16936   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16937   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16938 
16939   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16940     return;
16941   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16942   if (!ID) {
16943     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16944       if (!CD->IsClassExtension())
16945         return;
16946     }
16947     // No need to add this to end of @implementation.
16948     else
16949       return;
16950   }
16951   // All conditions are met. Add a new bitfield to the tail end of ivars.
16952   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16953   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16954 
16955   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16956                               DeclLoc, DeclLoc, nullptr,
16957                               Context.CharTy,
16958                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16959                                                                DeclLoc),
16960                               ObjCIvarDecl::Private, BW,
16961                               true);
16962   AllIvarDecls.push_back(Ivar);
16963 }
16964 
16965 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16966                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16967                        SourceLocation RBrac,
16968                        const ParsedAttributesView &Attrs) {
16969   assert(EnclosingDecl && "missing record or interface decl");
16970 
16971   // If this is an Objective-C @implementation or category and we have
16972   // new fields here we should reset the layout of the interface since
16973   // it will now change.
16974   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16975     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16976     switch (DC->getKind()) {
16977     default: break;
16978     case Decl::ObjCCategory:
16979       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16980       break;
16981     case Decl::ObjCImplementation:
16982       Context.
16983         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16984       break;
16985     }
16986   }
16987 
16988   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16989   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16990 
16991   // Start counting up the number of named members; make sure to include
16992   // members of anonymous structs and unions in the total.
16993   unsigned NumNamedMembers = 0;
16994   if (Record) {
16995     for (const auto *I : Record->decls()) {
16996       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16997         if (IFD->getDeclName())
16998           ++NumNamedMembers;
16999     }
17000   }
17001 
17002   // Verify that all the fields are okay.
17003   SmallVector<FieldDecl*, 32> RecFields;
17004 
17005   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17006        i != end; ++i) {
17007     FieldDecl *FD = cast<FieldDecl>(*i);
17008 
17009     // Get the type for the field.
17010     const Type *FDTy = FD->getType().getTypePtr();
17011 
17012     if (!FD->isAnonymousStructOrUnion()) {
17013       // Remember all fields written by the user.
17014       RecFields.push_back(FD);
17015     }
17016 
17017     // If the field is already invalid for some reason, don't emit more
17018     // diagnostics about it.
17019     if (FD->isInvalidDecl()) {
17020       EnclosingDecl->setInvalidDecl();
17021       continue;
17022     }
17023 
17024     // C99 6.7.2.1p2:
17025     //   A structure or union shall not contain a member with
17026     //   incomplete or function type (hence, a structure shall not
17027     //   contain an instance of itself, but may contain a pointer to
17028     //   an instance of itself), except that the last member of a
17029     //   structure with more than one named member may have incomplete
17030     //   array type; such a structure (and any union containing,
17031     //   possibly recursively, a member that is such a structure)
17032     //   shall not be a member of a structure or an element of an
17033     //   array.
17034     bool IsLastField = (i + 1 == Fields.end());
17035     if (FDTy->isFunctionType()) {
17036       // Field declared as a function.
17037       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17038         << FD->getDeclName();
17039       FD->setInvalidDecl();
17040       EnclosingDecl->setInvalidDecl();
17041       continue;
17042     } else if (FDTy->isIncompleteArrayType() &&
17043                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17044       if (Record) {
17045         // Flexible array member.
17046         // Microsoft and g++ is more permissive regarding flexible array.
17047         // It will accept flexible array in union and also
17048         // as the sole element of a struct/class.
17049         unsigned DiagID = 0;
17050         if (!Record->isUnion() && !IsLastField) {
17051           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17052             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17053           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17054           FD->setInvalidDecl();
17055           EnclosingDecl->setInvalidDecl();
17056           continue;
17057         } else if (Record->isUnion())
17058           DiagID = getLangOpts().MicrosoftExt
17059                        ? diag::ext_flexible_array_union_ms
17060                        : getLangOpts().CPlusPlus
17061                              ? diag::ext_flexible_array_union_gnu
17062                              : diag::err_flexible_array_union;
17063         else if (NumNamedMembers < 1)
17064           DiagID = getLangOpts().MicrosoftExt
17065                        ? diag::ext_flexible_array_empty_aggregate_ms
17066                        : getLangOpts().CPlusPlus
17067                              ? diag::ext_flexible_array_empty_aggregate_gnu
17068                              : diag::err_flexible_array_empty_aggregate;
17069 
17070         if (DiagID)
17071           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17072                                           << Record->getTagKind();
17073         // While the layout of types that contain virtual bases is not specified
17074         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17075         // virtual bases after the derived members.  This would make a flexible
17076         // array member declared at the end of an object not adjacent to the end
17077         // of the type.
17078         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17079           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17080               << FD->getDeclName() << Record->getTagKind();
17081         if (!getLangOpts().C99)
17082           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17083             << FD->getDeclName() << Record->getTagKind();
17084 
17085         // If the element type has a non-trivial destructor, we would not
17086         // implicitly destroy the elements, so disallow it for now.
17087         //
17088         // FIXME: GCC allows this. We should probably either implicitly delete
17089         // the destructor of the containing class, or just allow this.
17090         QualType BaseElem = Context.getBaseElementType(FD->getType());
17091         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17092           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17093             << FD->getDeclName() << FD->getType();
17094           FD->setInvalidDecl();
17095           EnclosingDecl->setInvalidDecl();
17096           continue;
17097         }
17098         // Okay, we have a legal flexible array member at the end of the struct.
17099         Record->setHasFlexibleArrayMember(true);
17100       } else {
17101         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17102         // unless they are followed by another ivar. That check is done
17103         // elsewhere, after synthesized ivars are known.
17104       }
17105     } else if (!FDTy->isDependentType() &&
17106                RequireCompleteSizedType(
17107                    FD->getLocation(), FD->getType(),
17108                    diag::err_field_incomplete_or_sizeless)) {
17109       // Incomplete type
17110       FD->setInvalidDecl();
17111       EnclosingDecl->setInvalidDecl();
17112       continue;
17113     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17114       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17115         // A type which contains a flexible array member is considered to be a
17116         // flexible array member.
17117         Record->setHasFlexibleArrayMember(true);
17118         if (!Record->isUnion()) {
17119           // If this is a struct/class and this is not the last element, reject
17120           // it.  Note that GCC supports variable sized arrays in the middle of
17121           // structures.
17122           if (!IsLastField)
17123             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17124               << FD->getDeclName() << FD->getType();
17125           else {
17126             // We support flexible arrays at the end of structs in
17127             // other structs as an extension.
17128             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17129               << FD->getDeclName();
17130           }
17131         }
17132       }
17133       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17134           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17135                                  diag::err_abstract_type_in_decl,
17136                                  AbstractIvarType)) {
17137         // Ivars can not have abstract class types
17138         FD->setInvalidDecl();
17139       }
17140       if (Record && FDTTy->getDecl()->hasObjectMember())
17141         Record->setHasObjectMember(true);
17142       if (Record && FDTTy->getDecl()->hasVolatileMember())
17143         Record->setHasVolatileMember(true);
17144     } else if (FDTy->isObjCObjectType()) {
17145       /// A field cannot be an Objective-c object
17146       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17147         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17148       QualType T = Context.getObjCObjectPointerType(FD->getType());
17149       FD->setType(T);
17150     } else if (Record && Record->isUnion() &&
17151                FD->getType().hasNonTrivialObjCLifetime() &&
17152                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17153                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17154                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17155                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17156       // For backward compatibility, fields of C unions declared in system
17157       // headers that have non-trivial ObjC ownership qualifications are marked
17158       // as unavailable unless the qualifier is explicit and __strong. This can
17159       // break ABI compatibility between programs compiled with ARC and MRR, but
17160       // is a better option than rejecting programs using those unions under
17161       // ARC.
17162       FD->addAttr(UnavailableAttr::CreateImplicit(
17163           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17164           FD->getLocation()));
17165     } else if (getLangOpts().ObjC &&
17166                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17167                !Record->hasObjectMember()) {
17168       if (FD->getType()->isObjCObjectPointerType() ||
17169           FD->getType().isObjCGCStrong())
17170         Record->setHasObjectMember(true);
17171       else if (Context.getAsArrayType(FD->getType())) {
17172         QualType BaseType = Context.getBaseElementType(FD->getType());
17173         if (BaseType->isRecordType() &&
17174             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17175           Record->setHasObjectMember(true);
17176         else if (BaseType->isObjCObjectPointerType() ||
17177                  BaseType.isObjCGCStrong())
17178                Record->setHasObjectMember(true);
17179       }
17180     }
17181 
17182     if (Record && !getLangOpts().CPlusPlus &&
17183         !shouldIgnoreForRecordTriviality(FD)) {
17184       QualType FT = FD->getType();
17185       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17186         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17187         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17188             Record->isUnion())
17189           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17190       }
17191       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17192       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17193         Record->setNonTrivialToPrimitiveCopy(true);
17194         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17195           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17196       }
17197       if (FT.isDestructedType()) {
17198         Record->setNonTrivialToPrimitiveDestroy(true);
17199         Record->setParamDestroyedInCallee(true);
17200         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17201           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17202       }
17203 
17204       if (const auto *RT = FT->getAs<RecordType>()) {
17205         if (RT->getDecl()->getArgPassingRestrictions() ==
17206             RecordDecl::APK_CanNeverPassInRegs)
17207           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17208       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17209         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17210     }
17211 
17212     if (Record && FD->getType().isVolatileQualified())
17213       Record->setHasVolatileMember(true);
17214     // Keep track of the number of named members.
17215     if (FD->getIdentifier())
17216       ++NumNamedMembers;
17217   }
17218 
17219   // Okay, we successfully defined 'Record'.
17220   if (Record) {
17221     bool Completed = false;
17222     if (CXXRecord) {
17223       if (!CXXRecord->isInvalidDecl()) {
17224         // Set access bits correctly on the directly-declared conversions.
17225         for (CXXRecordDecl::conversion_iterator
17226                I = CXXRecord->conversion_begin(),
17227                E = CXXRecord->conversion_end(); I != E; ++I)
17228           I.setAccess((*I)->getAccess());
17229       }
17230 
17231       // Add any implicitly-declared members to this class.
17232       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17233 
17234       if (!CXXRecord->isDependentType()) {
17235         if (!CXXRecord->isInvalidDecl()) {
17236           // If we have virtual base classes, we may end up finding multiple
17237           // final overriders for a given virtual function. Check for this
17238           // problem now.
17239           if (CXXRecord->getNumVBases()) {
17240             CXXFinalOverriderMap FinalOverriders;
17241             CXXRecord->getFinalOverriders(FinalOverriders);
17242 
17243             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17244                                              MEnd = FinalOverriders.end();
17245                  M != MEnd; ++M) {
17246               for (OverridingMethods::iterator SO = M->second.begin(),
17247                                             SOEnd = M->second.end();
17248                    SO != SOEnd; ++SO) {
17249                 assert(SO->second.size() > 0 &&
17250                        "Virtual function without overriding functions?");
17251                 if (SO->second.size() == 1)
17252                   continue;
17253 
17254                 // C++ [class.virtual]p2:
17255                 //   In a derived class, if a virtual member function of a base
17256                 //   class subobject has more than one final overrider the
17257                 //   program is ill-formed.
17258                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17259                   << (const NamedDecl *)M->first << Record;
17260                 Diag(M->first->getLocation(),
17261                      diag::note_overridden_virtual_function);
17262                 for (OverridingMethods::overriding_iterator
17263                           OM = SO->second.begin(),
17264                        OMEnd = SO->second.end();
17265                      OM != OMEnd; ++OM)
17266                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17267                     << (const NamedDecl *)M->first << OM->Method->getParent();
17268 
17269                 Record->setInvalidDecl();
17270               }
17271             }
17272             CXXRecord->completeDefinition(&FinalOverriders);
17273             Completed = true;
17274           }
17275         }
17276       }
17277     }
17278 
17279     if (!Completed)
17280       Record->completeDefinition();
17281 
17282     // Handle attributes before checking the layout.
17283     ProcessDeclAttributeList(S, Record, Attrs);
17284 
17285     // We may have deferred checking for a deleted destructor. Check now.
17286     if (CXXRecord) {
17287       auto *Dtor = CXXRecord->getDestructor();
17288       if (Dtor && Dtor->isImplicit() &&
17289           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17290         CXXRecord->setImplicitDestructorIsDeleted();
17291         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17292       }
17293     }
17294 
17295     if (Record->hasAttrs()) {
17296       CheckAlignasUnderalignment(Record);
17297 
17298       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17299         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17300                                            IA->getRange(), IA->getBestCase(),
17301                                            IA->getInheritanceModel());
17302     }
17303 
17304     // Check if the structure/union declaration is a type that can have zero
17305     // size in C. For C this is a language extension, for C++ it may cause
17306     // compatibility problems.
17307     bool CheckForZeroSize;
17308     if (!getLangOpts().CPlusPlus) {
17309       CheckForZeroSize = true;
17310     } else {
17311       // For C++ filter out types that cannot be referenced in C code.
17312       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17313       CheckForZeroSize =
17314           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17315           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17316           CXXRecord->isCLike();
17317     }
17318     if (CheckForZeroSize) {
17319       bool ZeroSize = true;
17320       bool IsEmpty = true;
17321       unsigned NonBitFields = 0;
17322       for (RecordDecl::field_iterator I = Record->field_begin(),
17323                                       E = Record->field_end();
17324            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17325         IsEmpty = false;
17326         if (I->isUnnamedBitfield()) {
17327           if (!I->isZeroLengthBitField(Context))
17328             ZeroSize = false;
17329         } else {
17330           ++NonBitFields;
17331           QualType FieldType = I->getType();
17332           if (FieldType->isIncompleteType() ||
17333               !Context.getTypeSizeInChars(FieldType).isZero())
17334             ZeroSize = false;
17335         }
17336       }
17337 
17338       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17339       // allowed in C++, but warn if its declaration is inside
17340       // extern "C" block.
17341       if (ZeroSize) {
17342         Diag(RecLoc, getLangOpts().CPlusPlus ?
17343                          diag::warn_zero_size_struct_union_in_extern_c :
17344                          diag::warn_zero_size_struct_union_compat)
17345           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17346       }
17347 
17348       // Structs without named members are extension in C (C99 6.7.2.1p7),
17349       // but are accepted by GCC.
17350       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17351         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17352                                diag::ext_no_named_members_in_struct_union)
17353           << Record->isUnion();
17354       }
17355     }
17356   } else {
17357     ObjCIvarDecl **ClsFields =
17358       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17359     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17360       ID->setEndOfDefinitionLoc(RBrac);
17361       // Add ivar's to class's DeclContext.
17362       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17363         ClsFields[i]->setLexicalDeclContext(ID);
17364         ID->addDecl(ClsFields[i]);
17365       }
17366       // Must enforce the rule that ivars in the base classes may not be
17367       // duplicates.
17368       if (ID->getSuperClass())
17369         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17370     } else if (ObjCImplementationDecl *IMPDecl =
17371                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17372       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17373       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17374         // Ivar declared in @implementation never belongs to the implementation.
17375         // Only it is in implementation's lexical context.
17376         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17377       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17378       IMPDecl->setIvarLBraceLoc(LBrac);
17379       IMPDecl->setIvarRBraceLoc(RBrac);
17380     } else if (ObjCCategoryDecl *CDecl =
17381                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17382       // case of ivars in class extension; all other cases have been
17383       // reported as errors elsewhere.
17384       // FIXME. Class extension does not have a LocEnd field.
17385       // CDecl->setLocEnd(RBrac);
17386       // Add ivar's to class extension's DeclContext.
17387       // Diagnose redeclaration of private ivars.
17388       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17389       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17390         if (IDecl) {
17391           if (const ObjCIvarDecl *ClsIvar =
17392               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17393             Diag(ClsFields[i]->getLocation(),
17394                  diag::err_duplicate_ivar_declaration);
17395             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17396             continue;
17397           }
17398           for (const auto *Ext : IDecl->known_extensions()) {
17399             if (const ObjCIvarDecl *ClsExtIvar
17400                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17401               Diag(ClsFields[i]->getLocation(),
17402                    diag::err_duplicate_ivar_declaration);
17403               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17404               continue;
17405             }
17406           }
17407         }
17408         ClsFields[i]->setLexicalDeclContext(CDecl);
17409         CDecl->addDecl(ClsFields[i]);
17410       }
17411       CDecl->setIvarLBraceLoc(LBrac);
17412       CDecl->setIvarRBraceLoc(RBrac);
17413     }
17414   }
17415 }
17416 
17417 /// Determine whether the given integral value is representable within
17418 /// the given type T.
17419 static bool isRepresentableIntegerValue(ASTContext &Context,
17420                                         llvm::APSInt &Value,
17421                                         QualType T) {
17422   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17423          "Integral type required!");
17424   unsigned BitWidth = Context.getIntWidth(T);
17425 
17426   if (Value.isUnsigned() || Value.isNonNegative()) {
17427     if (T->isSignedIntegerOrEnumerationType())
17428       --BitWidth;
17429     return Value.getActiveBits() <= BitWidth;
17430   }
17431   return Value.getMinSignedBits() <= BitWidth;
17432 }
17433 
17434 // Given an integral type, return the next larger integral type
17435 // (or a NULL type of no such type exists).
17436 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17437   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17438   // enum checking below.
17439   assert((T->isIntegralType(Context) ||
17440          T->isEnumeralType()) && "Integral type required!");
17441   const unsigned NumTypes = 4;
17442   QualType SignedIntegralTypes[NumTypes] = {
17443     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17444   };
17445   QualType UnsignedIntegralTypes[NumTypes] = {
17446     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17447     Context.UnsignedLongLongTy
17448   };
17449 
17450   unsigned BitWidth = Context.getTypeSize(T);
17451   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17452                                                         : UnsignedIntegralTypes;
17453   for (unsigned I = 0; I != NumTypes; ++I)
17454     if (Context.getTypeSize(Types[I]) > BitWidth)
17455       return Types[I];
17456 
17457   return QualType();
17458 }
17459 
17460 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17461                                           EnumConstantDecl *LastEnumConst,
17462                                           SourceLocation IdLoc,
17463                                           IdentifierInfo *Id,
17464                                           Expr *Val) {
17465   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17466   llvm::APSInt EnumVal(IntWidth);
17467   QualType EltTy;
17468 
17469   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17470     Val = nullptr;
17471 
17472   if (Val)
17473     Val = DefaultLvalueConversion(Val).get();
17474 
17475   if (Val) {
17476     if (Enum->isDependentType() || Val->isTypeDependent())
17477       EltTy = Context.DependentTy;
17478     else {
17479       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17480         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17481         // constant-expression in the enumerator-definition shall be a converted
17482         // constant expression of the underlying type.
17483         EltTy = Enum->getIntegerType();
17484         ExprResult Converted =
17485           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17486                                            CCEK_Enumerator);
17487         if (Converted.isInvalid())
17488           Val = nullptr;
17489         else
17490           Val = Converted.get();
17491       } else if (!Val->isValueDependent() &&
17492                  !(Val = VerifyIntegerConstantExpression(Val,
17493                                                          &EnumVal).get())) {
17494         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17495       } else {
17496         if (Enum->isComplete()) {
17497           EltTy = Enum->getIntegerType();
17498 
17499           // In Obj-C and Microsoft mode, require the enumeration value to be
17500           // representable in the underlying type of the enumeration. In C++11,
17501           // we perform a non-narrowing conversion as part of converted constant
17502           // expression checking.
17503           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17504             if (Context.getTargetInfo()
17505                     .getTriple()
17506                     .isWindowsMSVCEnvironment()) {
17507               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17508             } else {
17509               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17510             }
17511           }
17512 
17513           // Cast to the underlying type.
17514           Val = ImpCastExprToType(Val, EltTy,
17515                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17516                                                          : CK_IntegralCast)
17517                     .get();
17518         } else if (getLangOpts().CPlusPlus) {
17519           // C++11 [dcl.enum]p5:
17520           //   If the underlying type is not fixed, the type of each enumerator
17521           //   is the type of its initializing value:
17522           //     - If an initializer is specified for an enumerator, the
17523           //       initializing value has the same type as the expression.
17524           EltTy = Val->getType();
17525         } else {
17526           // C99 6.7.2.2p2:
17527           //   The expression that defines the value of an enumeration constant
17528           //   shall be an integer constant expression that has a value
17529           //   representable as an int.
17530 
17531           // Complain if the value is not representable in an int.
17532           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17533             Diag(IdLoc, diag::ext_enum_value_not_int)
17534               << EnumVal.toString(10) << Val->getSourceRange()
17535               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17536           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17537             // Force the type of the expression to 'int'.
17538             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17539           }
17540           EltTy = Val->getType();
17541         }
17542       }
17543     }
17544   }
17545 
17546   if (!Val) {
17547     if (Enum->isDependentType())
17548       EltTy = Context.DependentTy;
17549     else if (!LastEnumConst) {
17550       // C++0x [dcl.enum]p5:
17551       //   If the underlying type is not fixed, the type of each enumerator
17552       //   is the type of its initializing value:
17553       //     - If no initializer is specified for the first enumerator, the
17554       //       initializing value has an unspecified integral type.
17555       //
17556       // GCC uses 'int' for its unspecified integral type, as does
17557       // C99 6.7.2.2p3.
17558       if (Enum->isFixed()) {
17559         EltTy = Enum->getIntegerType();
17560       }
17561       else {
17562         EltTy = Context.IntTy;
17563       }
17564     } else {
17565       // Assign the last value + 1.
17566       EnumVal = LastEnumConst->getInitVal();
17567       ++EnumVal;
17568       EltTy = LastEnumConst->getType();
17569 
17570       // Check for overflow on increment.
17571       if (EnumVal < LastEnumConst->getInitVal()) {
17572         // C++0x [dcl.enum]p5:
17573         //   If the underlying type is not fixed, the type of each enumerator
17574         //   is the type of its initializing value:
17575         //
17576         //     - Otherwise the type of the initializing value is the same as
17577         //       the type of the initializing value of the preceding enumerator
17578         //       unless the incremented value is not representable in that type,
17579         //       in which case the type is an unspecified integral type
17580         //       sufficient to contain the incremented value. If no such type
17581         //       exists, the program is ill-formed.
17582         QualType T = getNextLargerIntegralType(Context, EltTy);
17583         if (T.isNull() || Enum->isFixed()) {
17584           // There is no integral type larger enough to represent this
17585           // value. Complain, then allow the value to wrap around.
17586           EnumVal = LastEnumConst->getInitVal();
17587           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17588           ++EnumVal;
17589           if (Enum->isFixed())
17590             // When the underlying type is fixed, this is ill-formed.
17591             Diag(IdLoc, diag::err_enumerator_wrapped)
17592               << EnumVal.toString(10)
17593               << EltTy;
17594           else
17595             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17596               << EnumVal.toString(10);
17597         } else {
17598           EltTy = T;
17599         }
17600 
17601         // Retrieve the last enumerator's value, extent that type to the
17602         // type that is supposed to be large enough to represent the incremented
17603         // value, then increment.
17604         EnumVal = LastEnumConst->getInitVal();
17605         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17606         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17607         ++EnumVal;
17608 
17609         // If we're not in C++, diagnose the overflow of enumerator values,
17610         // which in C99 means that the enumerator value is not representable in
17611         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17612         // permits enumerator values that are representable in some larger
17613         // integral type.
17614         if (!getLangOpts().CPlusPlus && !T.isNull())
17615           Diag(IdLoc, diag::warn_enum_value_overflow);
17616       } else if (!getLangOpts().CPlusPlus &&
17617                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17618         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17619         Diag(IdLoc, diag::ext_enum_value_not_int)
17620           << EnumVal.toString(10) << 1;
17621       }
17622     }
17623   }
17624 
17625   if (!EltTy->isDependentType()) {
17626     // Make the enumerator value match the signedness and size of the
17627     // enumerator's type.
17628     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17629     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17630   }
17631 
17632   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17633                                   Val, EnumVal);
17634 }
17635 
17636 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17637                                                 SourceLocation IILoc) {
17638   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17639       !getLangOpts().CPlusPlus)
17640     return SkipBodyInfo();
17641 
17642   // We have an anonymous enum definition. Look up the first enumerator to
17643   // determine if we should merge the definition with an existing one and
17644   // skip the body.
17645   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17646                                          forRedeclarationInCurContext());
17647   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17648   if (!PrevECD)
17649     return SkipBodyInfo();
17650 
17651   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17652   NamedDecl *Hidden;
17653   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17654     SkipBodyInfo Skip;
17655     Skip.Previous = Hidden;
17656     return Skip;
17657   }
17658 
17659   return SkipBodyInfo();
17660 }
17661 
17662 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17663                               SourceLocation IdLoc, IdentifierInfo *Id,
17664                               const ParsedAttributesView &Attrs,
17665                               SourceLocation EqualLoc, Expr *Val) {
17666   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17667   EnumConstantDecl *LastEnumConst =
17668     cast_or_null<EnumConstantDecl>(lastEnumConst);
17669 
17670   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17671   // we find one that is.
17672   S = getNonFieldDeclScope(S);
17673 
17674   // Verify that there isn't already something declared with this name in this
17675   // scope.
17676   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17677   LookupName(R, S);
17678   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17679 
17680   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17681     // Maybe we will complain about the shadowed template parameter.
17682     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17683     // Just pretend that we didn't see the previous declaration.
17684     PrevDecl = nullptr;
17685   }
17686 
17687   // C++ [class.mem]p15:
17688   // If T is the name of a class, then each of the following shall have a name
17689   // different from T:
17690   // - every enumerator of every member of class T that is an unscoped
17691   // enumerated type
17692   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17693     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17694                             DeclarationNameInfo(Id, IdLoc));
17695 
17696   EnumConstantDecl *New =
17697     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17698   if (!New)
17699     return nullptr;
17700 
17701   if (PrevDecl) {
17702     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17703       // Check for other kinds of shadowing not already handled.
17704       CheckShadow(New, PrevDecl, R);
17705     }
17706 
17707     // When in C++, we may get a TagDecl with the same name; in this case the
17708     // enum constant will 'hide' the tag.
17709     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17710            "Received TagDecl when not in C++!");
17711     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17712       if (isa<EnumConstantDecl>(PrevDecl))
17713         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17714       else
17715         Diag(IdLoc, diag::err_redefinition) << Id;
17716       notePreviousDefinition(PrevDecl, IdLoc);
17717       return nullptr;
17718     }
17719   }
17720 
17721   // Process attributes.
17722   ProcessDeclAttributeList(S, New, Attrs);
17723   AddPragmaAttributes(S, New);
17724 
17725   // Register this decl in the current scope stack.
17726   New->setAccess(TheEnumDecl->getAccess());
17727   PushOnScopeChains(New, S);
17728 
17729   ActOnDocumentableDecl(New);
17730 
17731   return New;
17732 }
17733 
17734 // Returns true when the enum initial expression does not trigger the
17735 // duplicate enum warning.  A few common cases are exempted as follows:
17736 // Element2 = Element1
17737 // Element2 = Element1 + 1
17738 // Element2 = Element1 - 1
17739 // Where Element2 and Element1 are from the same enum.
17740 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17741   Expr *InitExpr = ECD->getInitExpr();
17742   if (!InitExpr)
17743     return true;
17744   InitExpr = InitExpr->IgnoreImpCasts();
17745 
17746   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17747     if (!BO->isAdditiveOp())
17748       return true;
17749     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17750     if (!IL)
17751       return true;
17752     if (IL->getValue() != 1)
17753       return true;
17754 
17755     InitExpr = BO->getLHS();
17756   }
17757 
17758   // This checks if the elements are from the same enum.
17759   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17760   if (!DRE)
17761     return true;
17762 
17763   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17764   if (!EnumConstant)
17765     return true;
17766 
17767   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17768       Enum)
17769     return true;
17770 
17771   return false;
17772 }
17773 
17774 // Emits a warning when an element is implicitly set a value that
17775 // a previous element has already been set to.
17776 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17777                                         EnumDecl *Enum, QualType EnumType) {
17778   // Avoid anonymous enums
17779   if (!Enum->getIdentifier())
17780     return;
17781 
17782   // Only check for small enums.
17783   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17784     return;
17785 
17786   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17787     return;
17788 
17789   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17790   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17791 
17792   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17793 
17794   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17795   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17796 
17797   // Use int64_t as a key to avoid needing special handling for map keys.
17798   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17799     llvm::APSInt Val = D->getInitVal();
17800     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17801   };
17802 
17803   DuplicatesVector DupVector;
17804   ValueToVectorMap EnumMap;
17805 
17806   // Populate the EnumMap with all values represented by enum constants without
17807   // an initializer.
17808   for (auto *Element : Elements) {
17809     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17810 
17811     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17812     // this constant.  Skip this enum since it may be ill-formed.
17813     if (!ECD) {
17814       return;
17815     }
17816 
17817     // Constants with initalizers are handled in the next loop.
17818     if (ECD->getInitExpr())
17819       continue;
17820 
17821     // Duplicate values are handled in the next loop.
17822     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17823   }
17824 
17825   if (EnumMap.size() == 0)
17826     return;
17827 
17828   // Create vectors for any values that has duplicates.
17829   for (auto *Element : Elements) {
17830     // The last loop returned if any constant was null.
17831     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17832     if (!ValidDuplicateEnum(ECD, Enum))
17833       continue;
17834 
17835     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17836     if (Iter == EnumMap.end())
17837       continue;
17838 
17839     DeclOrVector& Entry = Iter->second;
17840     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17841       // Ensure constants are different.
17842       if (D == ECD)
17843         continue;
17844 
17845       // Create new vector and push values onto it.
17846       auto Vec = std::make_unique<ECDVector>();
17847       Vec->push_back(D);
17848       Vec->push_back(ECD);
17849 
17850       // Update entry to point to the duplicates vector.
17851       Entry = Vec.get();
17852 
17853       // Store the vector somewhere we can consult later for quick emission of
17854       // diagnostics.
17855       DupVector.emplace_back(std::move(Vec));
17856       continue;
17857     }
17858 
17859     ECDVector *Vec = Entry.get<ECDVector*>();
17860     // Make sure constants are not added more than once.
17861     if (*Vec->begin() == ECD)
17862       continue;
17863 
17864     Vec->push_back(ECD);
17865   }
17866 
17867   // Emit diagnostics.
17868   for (const auto &Vec : DupVector) {
17869     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17870 
17871     // Emit warning for one enum constant.
17872     auto *FirstECD = Vec->front();
17873     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17874       << FirstECD << FirstECD->getInitVal().toString(10)
17875       << FirstECD->getSourceRange();
17876 
17877     // Emit one note for each of the remaining enum constants with
17878     // the same value.
17879     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17880       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17881         << ECD << ECD->getInitVal().toString(10)
17882         << ECD->getSourceRange();
17883   }
17884 }
17885 
17886 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17887                              bool AllowMask) const {
17888   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17889   assert(ED->isCompleteDefinition() && "expected enum definition");
17890 
17891   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17892   llvm::APInt &FlagBits = R.first->second;
17893 
17894   if (R.second) {
17895     for (auto *E : ED->enumerators()) {
17896       const auto &EVal = E->getInitVal();
17897       // Only single-bit enumerators introduce new flag values.
17898       if (EVal.isPowerOf2())
17899         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17900     }
17901   }
17902 
17903   // A value is in a flag enum if either its bits are a subset of the enum's
17904   // flag bits (the first condition) or we are allowing masks and the same is
17905   // true of its complement (the second condition). When masks are allowed, we
17906   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17907   //
17908   // While it's true that any value could be used as a mask, the assumption is
17909   // that a mask will have all of the insignificant bits set. Anything else is
17910   // likely a logic error.
17911   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17912   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17913 }
17914 
17915 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17916                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17917                          const ParsedAttributesView &Attrs) {
17918   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17919   QualType EnumType = Context.getTypeDeclType(Enum);
17920 
17921   ProcessDeclAttributeList(S, Enum, Attrs);
17922 
17923   if (Enum->isDependentType()) {
17924     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17925       EnumConstantDecl *ECD =
17926         cast_or_null<EnumConstantDecl>(Elements[i]);
17927       if (!ECD) continue;
17928 
17929       ECD->setType(EnumType);
17930     }
17931 
17932     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17933     return;
17934   }
17935 
17936   // TODO: If the result value doesn't fit in an int, it must be a long or long
17937   // long value.  ISO C does not support this, but GCC does as an extension,
17938   // emit a warning.
17939   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17940   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17941   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17942 
17943   // Verify that all the values are okay, compute the size of the values, and
17944   // reverse the list.
17945   unsigned NumNegativeBits = 0;
17946   unsigned NumPositiveBits = 0;
17947 
17948   // Keep track of whether all elements have type int.
17949   bool AllElementsInt = true;
17950 
17951   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17952     EnumConstantDecl *ECD =
17953       cast_or_null<EnumConstantDecl>(Elements[i]);
17954     if (!ECD) continue;  // Already issued a diagnostic.
17955 
17956     const llvm::APSInt &InitVal = ECD->getInitVal();
17957 
17958     // Keep track of the size of positive and negative values.
17959     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17960       NumPositiveBits = std::max(NumPositiveBits,
17961                                  (unsigned)InitVal.getActiveBits());
17962     else
17963       NumNegativeBits = std::max(NumNegativeBits,
17964                                  (unsigned)InitVal.getMinSignedBits());
17965 
17966     // Keep track of whether every enum element has type int (very common).
17967     if (AllElementsInt)
17968       AllElementsInt = ECD->getType() == Context.IntTy;
17969   }
17970 
17971   // Figure out the type that should be used for this enum.
17972   QualType BestType;
17973   unsigned BestWidth;
17974 
17975   // C++0x N3000 [conv.prom]p3:
17976   //   An rvalue of an unscoped enumeration type whose underlying
17977   //   type is not fixed can be converted to an rvalue of the first
17978   //   of the following types that can represent all the values of
17979   //   the enumeration: int, unsigned int, long int, unsigned long
17980   //   int, long long int, or unsigned long long int.
17981   // C99 6.4.4.3p2:
17982   //   An identifier declared as an enumeration constant has type int.
17983   // The C99 rule is modified by a gcc extension
17984   QualType BestPromotionType;
17985 
17986   bool Packed = Enum->hasAttr<PackedAttr>();
17987   // -fshort-enums is the equivalent to specifying the packed attribute on all
17988   // enum definitions.
17989   if (LangOpts.ShortEnums)
17990     Packed = true;
17991 
17992   // If the enum already has a type because it is fixed or dictated by the
17993   // target, promote that type instead of analyzing the enumerators.
17994   if (Enum->isComplete()) {
17995     BestType = Enum->getIntegerType();
17996     if (BestType->isPromotableIntegerType())
17997       BestPromotionType = Context.getPromotedIntegerType(BestType);
17998     else
17999       BestPromotionType = BestType;
18000 
18001     BestWidth = Context.getIntWidth(BestType);
18002   }
18003   else if (NumNegativeBits) {
18004     // If there is a negative value, figure out the smallest integer type (of
18005     // int/long/longlong) that fits.
18006     // If it's packed, check also if it fits a char or a short.
18007     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18008       BestType = Context.SignedCharTy;
18009       BestWidth = CharWidth;
18010     } else if (Packed && NumNegativeBits <= ShortWidth &&
18011                NumPositiveBits < ShortWidth) {
18012       BestType = Context.ShortTy;
18013       BestWidth = ShortWidth;
18014     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18015       BestType = Context.IntTy;
18016       BestWidth = IntWidth;
18017     } else {
18018       BestWidth = Context.getTargetInfo().getLongWidth();
18019 
18020       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18021         BestType = Context.LongTy;
18022       } else {
18023         BestWidth = Context.getTargetInfo().getLongLongWidth();
18024 
18025         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18026           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18027         BestType = Context.LongLongTy;
18028       }
18029     }
18030     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18031   } else {
18032     // If there is no negative value, figure out the smallest type that fits
18033     // all of the enumerator values.
18034     // If it's packed, check also if it fits a char or a short.
18035     if (Packed && NumPositiveBits <= CharWidth) {
18036       BestType = Context.UnsignedCharTy;
18037       BestPromotionType = Context.IntTy;
18038       BestWidth = CharWidth;
18039     } else if (Packed && NumPositiveBits <= ShortWidth) {
18040       BestType = Context.UnsignedShortTy;
18041       BestPromotionType = Context.IntTy;
18042       BestWidth = ShortWidth;
18043     } else if (NumPositiveBits <= IntWidth) {
18044       BestType = Context.UnsignedIntTy;
18045       BestWidth = IntWidth;
18046       BestPromotionType
18047         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18048                            ? Context.UnsignedIntTy : Context.IntTy;
18049     } else if (NumPositiveBits <=
18050                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18051       BestType = Context.UnsignedLongTy;
18052       BestPromotionType
18053         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18054                            ? Context.UnsignedLongTy : Context.LongTy;
18055     } else {
18056       BestWidth = Context.getTargetInfo().getLongLongWidth();
18057       assert(NumPositiveBits <= BestWidth &&
18058              "How could an initializer get larger than ULL?");
18059       BestType = Context.UnsignedLongLongTy;
18060       BestPromotionType
18061         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18062                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18063     }
18064   }
18065 
18066   // Loop over all of the enumerator constants, changing their types to match
18067   // the type of the enum if needed.
18068   for (auto *D : Elements) {
18069     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18070     if (!ECD) continue;  // Already issued a diagnostic.
18071 
18072     // Standard C says the enumerators have int type, but we allow, as an
18073     // extension, the enumerators to be larger than int size.  If each
18074     // enumerator value fits in an int, type it as an int, otherwise type it the
18075     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18076     // that X has type 'int', not 'unsigned'.
18077 
18078     // Determine whether the value fits into an int.
18079     llvm::APSInt InitVal = ECD->getInitVal();
18080 
18081     // If it fits into an integer type, force it.  Otherwise force it to match
18082     // the enum decl type.
18083     QualType NewTy;
18084     unsigned NewWidth;
18085     bool NewSign;
18086     if (!getLangOpts().CPlusPlus &&
18087         !Enum->isFixed() &&
18088         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18089       NewTy = Context.IntTy;
18090       NewWidth = IntWidth;
18091       NewSign = true;
18092     } else if (ECD->getType() == BestType) {
18093       // Already the right type!
18094       if (getLangOpts().CPlusPlus)
18095         // C++ [dcl.enum]p4: Following the closing brace of an
18096         // enum-specifier, each enumerator has the type of its
18097         // enumeration.
18098         ECD->setType(EnumType);
18099       continue;
18100     } else {
18101       NewTy = BestType;
18102       NewWidth = BestWidth;
18103       NewSign = BestType->isSignedIntegerOrEnumerationType();
18104     }
18105 
18106     // Adjust the APSInt value.
18107     InitVal = InitVal.extOrTrunc(NewWidth);
18108     InitVal.setIsSigned(NewSign);
18109     ECD->setInitVal(InitVal);
18110 
18111     // Adjust the Expr initializer and type.
18112     if (ECD->getInitExpr() &&
18113         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18114       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
18115                                                 CK_IntegralCast,
18116                                                 ECD->getInitExpr(),
18117                                                 /*base paths*/ nullptr,
18118                                                 VK_RValue));
18119     if (getLangOpts().CPlusPlus)
18120       // C++ [dcl.enum]p4: Following the closing brace of an
18121       // enum-specifier, each enumerator has the type of its
18122       // enumeration.
18123       ECD->setType(EnumType);
18124     else
18125       ECD->setType(NewTy);
18126   }
18127 
18128   Enum->completeDefinition(BestType, BestPromotionType,
18129                            NumPositiveBits, NumNegativeBits);
18130 
18131   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18132 
18133   if (Enum->isClosedFlag()) {
18134     for (Decl *D : Elements) {
18135       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18136       if (!ECD) continue;  // Already issued a diagnostic.
18137 
18138       llvm::APSInt InitVal = ECD->getInitVal();
18139       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18140           !IsValueInFlagEnum(Enum, InitVal, true))
18141         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18142           << ECD << Enum;
18143     }
18144   }
18145 
18146   // Now that the enum type is defined, ensure it's not been underaligned.
18147   if (Enum->hasAttrs())
18148     CheckAlignasUnderalignment(Enum);
18149 }
18150 
18151 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18152                                   SourceLocation StartLoc,
18153                                   SourceLocation EndLoc) {
18154   StringLiteral *AsmString = cast<StringLiteral>(expr);
18155 
18156   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18157                                                    AsmString, StartLoc,
18158                                                    EndLoc);
18159   CurContext->addDecl(New);
18160   return New;
18161 }
18162 
18163 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18164                                       IdentifierInfo* AliasName,
18165                                       SourceLocation PragmaLoc,
18166                                       SourceLocation NameLoc,
18167                                       SourceLocation AliasNameLoc) {
18168   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18169                                          LookupOrdinaryName);
18170   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18171                            AttributeCommonInfo::AS_Pragma);
18172   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18173       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18174 
18175   // If a declaration that:
18176   // 1) declares a function or a variable
18177   // 2) has external linkage
18178   // already exists, add a label attribute to it.
18179   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18180     if (isDeclExternC(PrevDecl))
18181       PrevDecl->addAttr(Attr);
18182     else
18183       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18184           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18185   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18186   } else
18187     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18188 }
18189 
18190 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18191                              SourceLocation PragmaLoc,
18192                              SourceLocation NameLoc) {
18193   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18194 
18195   if (PrevDecl) {
18196     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18197   } else {
18198     (void)WeakUndeclaredIdentifiers.insert(
18199       std::pair<IdentifierInfo*,WeakInfo>
18200         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18201   }
18202 }
18203 
18204 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18205                                 IdentifierInfo* AliasName,
18206                                 SourceLocation PragmaLoc,
18207                                 SourceLocation NameLoc,
18208                                 SourceLocation AliasNameLoc) {
18209   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18210                                     LookupOrdinaryName);
18211   WeakInfo W = WeakInfo(Name, NameLoc);
18212 
18213   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18214     if (!PrevDecl->hasAttr<AliasAttr>())
18215       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18216         DeclApplyPragmaWeak(TUScope, ND, W);
18217   } else {
18218     (void)WeakUndeclaredIdentifiers.insert(
18219       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18220   }
18221 }
18222 
18223 Decl *Sema::getObjCDeclContext() const {
18224   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18225 }
18226 
18227 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18228                                                      bool Final) {
18229   // SYCL functions can be template, so we check if they have appropriate
18230   // attribute prior to checking if it is a template.
18231   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18232     return FunctionEmissionStatus::Emitted;
18233 
18234   // Templates are emitted when they're instantiated.
18235   if (FD->isDependentContext())
18236     return FunctionEmissionStatus::TemplateDiscarded;
18237 
18238   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18239   if (LangOpts.OpenMPIsDevice) {
18240     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18241         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18242     if (DevTy.hasValue()) {
18243       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18244         OMPES = FunctionEmissionStatus::OMPDiscarded;
18245       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18246                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18247         OMPES = FunctionEmissionStatus::Emitted;
18248       }
18249     }
18250   } else if (LangOpts.OpenMP) {
18251     // In OpenMP 4.5 all the functions are host functions.
18252     if (LangOpts.OpenMP <= 45) {
18253       OMPES = FunctionEmissionStatus::Emitted;
18254     } else {
18255       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18256           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18257       // In OpenMP 5.0 or above, DevTy may be changed later by
18258       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18259       // having no value does not imply host. The emission status will be
18260       // checked again at the end of compilation unit.
18261       if (DevTy.hasValue()) {
18262         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18263           OMPES = FunctionEmissionStatus::OMPDiscarded;
18264         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18265                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18266           OMPES = FunctionEmissionStatus::Emitted;
18267       } else if (Final)
18268         OMPES = FunctionEmissionStatus::Emitted;
18269     }
18270   }
18271   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18272       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18273     return OMPES;
18274 
18275   if (LangOpts.CUDA) {
18276     // When compiling for device, host functions are never emitted.  Similarly,
18277     // when compiling for host, device and global functions are never emitted.
18278     // (Technically, we do emit a host-side stub for global functions, but this
18279     // doesn't count for our purposes here.)
18280     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18281     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18282       return FunctionEmissionStatus::CUDADiscarded;
18283     if (!LangOpts.CUDAIsDevice &&
18284         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18285       return FunctionEmissionStatus::CUDADiscarded;
18286 
18287     // Check whether this function is externally visible -- if so, it's
18288     // known-emitted.
18289     //
18290     // We have to check the GVA linkage of the function's *definition* -- if we
18291     // only have a declaration, we don't know whether or not the function will
18292     // be emitted, because (say) the definition could include "inline".
18293     FunctionDecl *Def = FD->getDefinition();
18294 
18295     if (Def &&
18296         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18297         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18298       return FunctionEmissionStatus::Emitted;
18299   }
18300 
18301   // Otherwise, the function is known-emitted if it's in our set of
18302   // known-emitted functions.
18303   return FunctionEmissionStatus::Unknown;
18304 }
18305 
18306 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18307   // Host-side references to a __global__ function refer to the stub, so the
18308   // function itself is never emitted and therefore should not be marked.
18309   // If we have host fn calls kernel fn calls host+device, the HD function
18310   // does not get instantiated on the host. We model this by omitting at the
18311   // call to the kernel from the callgraph. This ensures that, when compiling
18312   // for host, only HD functions actually called from the host get marked as
18313   // known-emitted.
18314   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18315          IdentifyCUDATarget(Callee) == CFT_Global;
18316 }
18317