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   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1767     // For a decomposition declaration, warn if none of the bindings are
1768     // referenced, instead of if the variable itself is referenced (which
1769     // it is, by the bindings' expressions).
1770     for (auto *BD : DD->bindings())
1771       if (BD->isReferenced())
1772         return false;
1773   } else if (!D->getDeclName()) {
1774     return false;
1775   } else if (D->isReferenced() || D->isUsed()) {
1776     return false;
1777   }
1778 
1779   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1780     return false;
1781 
1782   if (isa<LabelDecl>(D))
1783     return true;
1784 
1785   // Except for labels, we only care about unused decls that are local to
1786   // functions.
1787   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1788   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1789     // For dependent types, the diagnostic is deferred.
1790     WithinFunction =
1791         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1792   if (!WithinFunction)
1793     return false;
1794 
1795   if (isa<TypedefNameDecl>(D))
1796     return true;
1797 
1798   // White-list anything that isn't a local variable.
1799   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1800     return false;
1801 
1802   // Types of valid local variables should be complete, so this should succeed.
1803   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1804 
1805     // White-list anything with an __attribute__((unused)) type.
1806     const auto *Ty = VD->getType().getTypePtr();
1807 
1808     // Only look at the outermost level of typedef.
1809     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1810       if (TT->getDecl()->hasAttr<UnusedAttr>())
1811         return false;
1812     }
1813 
1814     // If we failed to complete the type for some reason, or if the type is
1815     // dependent, don't diagnose the variable.
1816     if (Ty->isIncompleteType() || Ty->isDependentType())
1817       return false;
1818 
1819     // Look at the element type to ensure that the warning behaviour is
1820     // consistent for both scalars and arrays.
1821     Ty = Ty->getBaseElementTypeUnsafe();
1822 
1823     if (const TagType *TT = Ty->getAs<TagType>()) {
1824       const TagDecl *Tag = TT->getDecl();
1825       if (Tag->hasAttr<UnusedAttr>())
1826         return false;
1827 
1828       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1829         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1830           return false;
1831 
1832         if (const Expr *Init = VD->getInit()) {
1833           if (const ExprWithCleanups *Cleanups =
1834                   dyn_cast<ExprWithCleanups>(Init))
1835             Init = Cleanups->getSubExpr();
1836           const CXXConstructExpr *Construct =
1837             dyn_cast<CXXConstructExpr>(Init);
1838           if (Construct && !Construct->isElidable()) {
1839             CXXConstructorDecl *CD = Construct->getConstructor();
1840             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1841                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1842               return false;
1843           }
1844 
1845           // Suppress the warning if we don't know how this is constructed, and
1846           // it could possibly be non-trivial constructor.
1847           if (Init->isTypeDependent())
1848             for (const CXXConstructorDecl *Ctor : RD->ctors())
1849               if (!Ctor->isTrivial())
1850                 return false;
1851         }
1852       }
1853     }
1854 
1855     // TODO: __attribute__((unused)) templates?
1856   }
1857 
1858   return true;
1859 }
1860 
1861 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1862                                      FixItHint &Hint) {
1863   if (isa<LabelDecl>(D)) {
1864     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1865         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1866         true);
1867     if (AfterColon.isInvalid())
1868       return;
1869     Hint = FixItHint::CreateRemoval(
1870         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1871   }
1872 }
1873 
1874 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1875   if (D->getTypeForDecl()->isDependentType())
1876     return;
1877 
1878   for (auto *TmpD : D->decls()) {
1879     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1880       DiagnoseUnusedDecl(T);
1881     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1882       DiagnoseUnusedNestedTypedefs(R);
1883   }
1884 }
1885 
1886 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1887 /// unless they are marked attr(unused).
1888 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1889   if (!ShouldDiagnoseUnusedDecl(D))
1890     return;
1891 
1892   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1893     // typedefs can be referenced later on, so the diagnostics are emitted
1894     // at end-of-translation-unit.
1895     UnusedLocalTypedefNameCandidates.insert(TD);
1896     return;
1897   }
1898 
1899   FixItHint Hint;
1900   GenerateFixForUnusedDecl(D, Context, Hint);
1901 
1902   unsigned DiagID;
1903   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1904     DiagID = diag::warn_unused_exception_param;
1905   else if (isa<LabelDecl>(D))
1906     DiagID = diag::warn_unused_label;
1907   else
1908     DiagID = diag::warn_unused_variable;
1909 
1910   Diag(D->getLocation(), DiagID) << D << Hint;
1911 }
1912 
1913 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1914   // Verify that we have no forward references left.  If so, there was a goto
1915   // or address of a label taken, but no definition of it.  Label fwd
1916   // definitions are indicated with a null substmt which is also not a resolved
1917   // MS inline assembly label name.
1918   bool Diagnose = false;
1919   if (L->isMSAsmLabel())
1920     Diagnose = !L->isResolvedMSAsmLabel();
1921   else
1922     Diagnose = L->getStmt() == nullptr;
1923   if (Diagnose)
1924     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1925 }
1926 
1927 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1928   S->mergeNRVOIntoParent();
1929 
1930   if (S->decl_empty()) return;
1931   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1932          "Scope shouldn't contain decls!");
1933 
1934   for (auto *TmpD : S->decls()) {
1935     assert(TmpD && "This decl didn't get pushed??");
1936 
1937     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1938     NamedDecl *D = cast<NamedDecl>(TmpD);
1939 
1940     // Diagnose unused variables in this scope.
1941     if (!S->hasUnrecoverableErrorOccurred()) {
1942       DiagnoseUnusedDecl(D);
1943       if (const auto *RD = dyn_cast<RecordDecl>(D))
1944         DiagnoseUnusedNestedTypedefs(RD);
1945     }
1946 
1947     if (!D->getDeclName()) continue;
1948 
1949     // If this was a forward reference to a label, verify it was defined.
1950     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1951       CheckPoppedLabel(LD, *this);
1952 
1953     // Remove this name from our lexical scope, and warn on it if we haven't
1954     // already.
1955     IdResolver.RemoveDecl(D);
1956     auto ShadowI = ShadowingDecls.find(D);
1957     if (ShadowI != ShadowingDecls.end()) {
1958       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1959         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1960             << D << FD << FD->getParent();
1961         Diag(FD->getLocation(), diag::note_previous_declaration);
1962       }
1963       ShadowingDecls.erase(ShadowI);
1964     }
1965   }
1966 }
1967 
1968 /// Look for an Objective-C class in the translation unit.
1969 ///
1970 /// \param Id The name of the Objective-C class we're looking for. If
1971 /// typo-correction fixes this name, the Id will be updated
1972 /// to the fixed name.
1973 ///
1974 /// \param IdLoc The location of the name in the translation unit.
1975 ///
1976 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1977 /// if there is no class with the given name.
1978 ///
1979 /// \returns The declaration of the named Objective-C class, or NULL if the
1980 /// class could not be found.
1981 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1982                                               SourceLocation IdLoc,
1983                                               bool DoTypoCorrection) {
1984   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1985   // creation from this context.
1986   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1987 
1988   if (!IDecl && DoTypoCorrection) {
1989     // Perform typo correction at the given location, but only if we
1990     // find an Objective-C class name.
1991     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1992     if (TypoCorrection C =
1993             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1994                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1995       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1996       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1997       Id = IDecl->getIdentifier();
1998     }
1999   }
2000   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2001   // This routine must always return a class definition, if any.
2002   if (Def && Def->getDefinition())
2003       Def = Def->getDefinition();
2004   return Def;
2005 }
2006 
2007 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2008 /// from S, where a non-field would be declared. This routine copes
2009 /// with the difference between C and C++ scoping rules in structs and
2010 /// unions. For example, the following code is well-formed in C but
2011 /// ill-formed in C++:
2012 /// @code
2013 /// struct S6 {
2014 ///   enum { BAR } e;
2015 /// };
2016 ///
2017 /// void test_S6() {
2018 ///   struct S6 a;
2019 ///   a.e = BAR;
2020 /// }
2021 /// @endcode
2022 /// For the declaration of BAR, this routine will return a different
2023 /// scope. The scope S will be the scope of the unnamed enumeration
2024 /// within S6. In C++, this routine will return the scope associated
2025 /// with S6, because the enumeration's scope is a transparent
2026 /// context but structures can contain non-field names. In C, this
2027 /// routine will return the translation unit scope, since the
2028 /// enumeration's scope is a transparent context and structures cannot
2029 /// contain non-field names.
2030 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2031   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2032          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2033          (S->isClassScope() && !getLangOpts().CPlusPlus))
2034     S = S->getParent();
2035   return S;
2036 }
2037 
2038 /// Looks up the declaration of "struct objc_super" and
2039 /// saves it for later use in building builtin declaration of
2040 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2041 /// pre-existing declaration exists no action takes place.
2042 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2043                                         IdentifierInfo *II) {
2044   if (!II->isStr("objc_msgSendSuper"))
2045     return;
2046   ASTContext &Context = ThisSema.Context;
2047 
2048   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2049                       SourceLocation(), Sema::LookupTagName);
2050   ThisSema.LookupName(Result, S);
2051   if (Result.getResultKind() == LookupResult::Found)
2052     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2053       Context.setObjCSuperType(Context.getTagDeclType(TD));
2054 }
2055 
2056 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2057                                ASTContext::GetBuiltinTypeError Error) {
2058   switch (Error) {
2059   case ASTContext::GE_None:
2060     return "";
2061   case ASTContext::GE_Missing_type:
2062     return BuiltinInfo.getHeaderName(ID);
2063   case ASTContext::GE_Missing_stdio:
2064     return "stdio.h";
2065   case ASTContext::GE_Missing_setjmp:
2066     return "setjmp.h";
2067   case ASTContext::GE_Missing_ucontext:
2068     return "ucontext.h";
2069   }
2070   llvm_unreachable("unhandled error kind");
2071 }
2072 
2073 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2074                                   unsigned ID, SourceLocation Loc) {
2075   DeclContext *Parent = Context.getTranslationUnitDecl();
2076 
2077   if (getLangOpts().CPlusPlus) {
2078     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2079         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2080     CLinkageDecl->setImplicit();
2081     Parent->addDecl(CLinkageDecl);
2082     Parent = CLinkageDecl;
2083   }
2084 
2085   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2086                                            /*TInfo=*/nullptr, SC_Extern, false,
2087                                            Type->isFunctionProtoType());
2088   New->setImplicit();
2089   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2090 
2091   // Create Decl objects for each parameter, adding them to the
2092   // FunctionDecl.
2093   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2094     SmallVector<ParmVarDecl *, 16> Params;
2095     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2096       ParmVarDecl *parm = ParmVarDecl::Create(
2097           Context, New, SourceLocation(), SourceLocation(), nullptr,
2098           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2099       parm->setScopeInfo(0, i);
2100       Params.push_back(parm);
2101     }
2102     New->setParams(Params);
2103   }
2104 
2105   AddKnownFunctionAttributes(New);
2106   return New;
2107 }
2108 
2109 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2110 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2111 /// if we're creating this built-in in anticipation of redeclaring the
2112 /// built-in.
2113 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2114                                      Scope *S, bool ForRedeclaration,
2115                                      SourceLocation Loc) {
2116   LookupPredefedObjCSuperType(*this, S, II);
2117 
2118   ASTContext::GetBuiltinTypeError Error;
2119   QualType R = Context.GetBuiltinType(ID, Error);
2120   if (Error) {
2121     if (!ForRedeclaration)
2122       return nullptr;
2123 
2124     // If we have a builtin without an associated type we should not emit a
2125     // warning when we were not able to find a type for it.
2126     if (Error == ASTContext::GE_Missing_type)
2127       return nullptr;
2128 
2129     // If we could not find a type for setjmp it is because the jmp_buf type was
2130     // not defined prior to the setjmp declaration.
2131     if (Error == ASTContext::GE_Missing_setjmp) {
2132       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2133           << Context.BuiltinInfo.getName(ID);
2134       return nullptr;
2135     }
2136 
2137     // Generally, we emit a warning that the declaration requires the
2138     // appropriate header.
2139     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2140         << getHeaderName(Context.BuiltinInfo, ID, Error)
2141         << Context.BuiltinInfo.getName(ID);
2142     return nullptr;
2143   }
2144 
2145   if (!ForRedeclaration &&
2146       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2147        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2148     Diag(Loc, diag::ext_implicit_lib_function_decl)
2149         << Context.BuiltinInfo.getName(ID) << R;
2150     if (Context.BuiltinInfo.getHeaderName(ID) &&
2151         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2152       Diag(Loc, diag::note_include_header_or_declare)
2153           << Context.BuiltinInfo.getHeaderName(ID)
2154           << Context.BuiltinInfo.getName(ID);
2155   }
2156 
2157   if (R.isNull())
2158     return nullptr;
2159 
2160   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2161   RegisterLocallyScopedExternCDecl(New, S);
2162 
2163   // TUScope is the translation-unit scope to insert this function into.
2164   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2165   // relate Scopes to DeclContexts, and probably eliminate CurContext
2166   // entirely, but we're not there yet.
2167   DeclContext *SavedContext = CurContext;
2168   CurContext = New->getDeclContext();
2169   PushOnScopeChains(New, TUScope);
2170   CurContext = SavedContext;
2171   return New;
2172 }
2173 
2174 /// Typedef declarations don't have linkage, but they still denote the same
2175 /// entity if their types are the same.
2176 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2177 /// isSameEntity.
2178 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2179                                                      TypedefNameDecl *Decl,
2180                                                      LookupResult &Previous) {
2181   // This is only interesting when modules are enabled.
2182   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2183     return;
2184 
2185   // Empty sets are uninteresting.
2186   if (Previous.empty())
2187     return;
2188 
2189   LookupResult::Filter Filter = Previous.makeFilter();
2190   while (Filter.hasNext()) {
2191     NamedDecl *Old = Filter.next();
2192 
2193     // Non-hidden declarations are never ignored.
2194     if (S.isVisible(Old))
2195       continue;
2196 
2197     // Declarations of the same entity are not ignored, even if they have
2198     // different linkages.
2199     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2200       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2201                                 Decl->getUnderlyingType()))
2202         continue;
2203 
2204       // If both declarations give a tag declaration a typedef name for linkage
2205       // purposes, then they declare the same entity.
2206       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2207           Decl->getAnonDeclWithTypedefName())
2208         continue;
2209     }
2210 
2211     Filter.erase();
2212   }
2213 
2214   Filter.done();
2215 }
2216 
2217 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2218   QualType OldType;
2219   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2220     OldType = OldTypedef->getUnderlyingType();
2221   else
2222     OldType = Context.getTypeDeclType(Old);
2223   QualType NewType = New->getUnderlyingType();
2224 
2225   if (NewType->isVariablyModifiedType()) {
2226     // Must not redefine a typedef with a variably-modified type.
2227     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2228     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2229       << Kind << NewType;
2230     if (Old->getLocation().isValid())
2231       notePreviousDefinition(Old, New->getLocation());
2232     New->setInvalidDecl();
2233     return true;
2234   }
2235 
2236   if (OldType != NewType &&
2237       !OldType->isDependentType() &&
2238       !NewType->isDependentType() &&
2239       !Context.hasSameType(OldType, NewType)) {
2240     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2241     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2242       << Kind << NewType << OldType;
2243     if (Old->getLocation().isValid())
2244       notePreviousDefinition(Old, New->getLocation());
2245     New->setInvalidDecl();
2246     return true;
2247   }
2248   return false;
2249 }
2250 
2251 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2252 /// same name and scope as a previous declaration 'Old'.  Figure out
2253 /// how to resolve this situation, merging decls or emitting
2254 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2255 ///
2256 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2257                                 LookupResult &OldDecls) {
2258   // If the new decl is known invalid already, don't bother doing any
2259   // merging checks.
2260   if (New->isInvalidDecl()) return;
2261 
2262   // Allow multiple definitions for ObjC built-in typedefs.
2263   // FIXME: Verify the underlying types are equivalent!
2264   if (getLangOpts().ObjC) {
2265     const IdentifierInfo *TypeID = New->getIdentifier();
2266     switch (TypeID->getLength()) {
2267     default: break;
2268     case 2:
2269       {
2270         if (!TypeID->isStr("id"))
2271           break;
2272         QualType T = New->getUnderlyingType();
2273         if (!T->isPointerType())
2274           break;
2275         if (!T->isVoidPointerType()) {
2276           QualType PT = T->castAs<PointerType>()->getPointeeType();
2277           if (!PT->isStructureType())
2278             break;
2279         }
2280         Context.setObjCIdRedefinitionType(T);
2281         // Install the built-in type for 'id', ignoring the current definition.
2282         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2283         return;
2284       }
2285     case 5:
2286       if (!TypeID->isStr("Class"))
2287         break;
2288       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2289       // Install the built-in type for 'Class', ignoring the current definition.
2290       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2291       return;
2292     case 3:
2293       if (!TypeID->isStr("SEL"))
2294         break;
2295       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2296       // Install the built-in type for 'SEL', ignoring the current definition.
2297       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2298       return;
2299     }
2300     // Fall through - the typedef name was not a builtin type.
2301   }
2302 
2303   // Verify the old decl was also a type.
2304   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2305   if (!Old) {
2306     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2307       << New->getDeclName();
2308 
2309     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2310     if (OldD->getLocation().isValid())
2311       notePreviousDefinition(OldD, New->getLocation());
2312 
2313     return New->setInvalidDecl();
2314   }
2315 
2316   // If the old declaration is invalid, just give up here.
2317   if (Old->isInvalidDecl())
2318     return New->setInvalidDecl();
2319 
2320   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2321     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2322     auto *NewTag = New->getAnonDeclWithTypedefName();
2323     NamedDecl *Hidden = nullptr;
2324     if (OldTag && NewTag &&
2325         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2326         !hasVisibleDefinition(OldTag, &Hidden)) {
2327       // There is a definition of this tag, but it is not visible. Use it
2328       // instead of our tag.
2329       New->setTypeForDecl(OldTD->getTypeForDecl());
2330       if (OldTD->isModed())
2331         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2332                                     OldTD->getUnderlyingType());
2333       else
2334         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2335 
2336       // Make the old tag definition visible.
2337       makeMergedDefinitionVisible(Hidden);
2338 
2339       // If this was an unscoped enumeration, yank all of its enumerators
2340       // out of the scope.
2341       if (isa<EnumDecl>(NewTag)) {
2342         Scope *EnumScope = getNonFieldDeclScope(S);
2343         for (auto *D : NewTag->decls()) {
2344           auto *ED = cast<EnumConstantDecl>(D);
2345           assert(EnumScope->isDeclScope(ED));
2346           EnumScope->RemoveDecl(ED);
2347           IdResolver.RemoveDecl(ED);
2348           ED->getLexicalDeclContext()->removeDecl(ED);
2349         }
2350       }
2351     }
2352   }
2353 
2354   // If the typedef types are not identical, reject them in all languages and
2355   // with any extensions enabled.
2356   if (isIncompatibleTypedef(Old, New))
2357     return;
2358 
2359   // The types match.  Link up the redeclaration chain and merge attributes if
2360   // the old declaration was a typedef.
2361   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2362     New->setPreviousDecl(Typedef);
2363     mergeDeclAttributes(New, Old);
2364   }
2365 
2366   if (getLangOpts().MicrosoftExt)
2367     return;
2368 
2369   if (getLangOpts().CPlusPlus) {
2370     // C++ [dcl.typedef]p2:
2371     //   In a given non-class scope, a typedef specifier can be used to
2372     //   redefine the name of any type declared in that scope to refer
2373     //   to the type to which it already refers.
2374     if (!isa<CXXRecordDecl>(CurContext))
2375       return;
2376 
2377     // C++0x [dcl.typedef]p4:
2378     //   In a given class scope, a typedef specifier can be used to redefine
2379     //   any class-name declared in that scope that is not also a typedef-name
2380     //   to refer to the type to which it already refers.
2381     //
2382     // This wording came in via DR424, which was a correction to the
2383     // wording in DR56, which accidentally banned code like:
2384     //
2385     //   struct S {
2386     //     typedef struct A { } A;
2387     //   };
2388     //
2389     // in the C++03 standard. We implement the C++0x semantics, which
2390     // allow the above but disallow
2391     //
2392     //   struct S {
2393     //     typedef int I;
2394     //     typedef int I;
2395     //   };
2396     //
2397     // since that was the intent of DR56.
2398     if (!isa<TypedefNameDecl>(Old))
2399       return;
2400 
2401     Diag(New->getLocation(), diag::err_redefinition)
2402       << New->getDeclName();
2403     notePreviousDefinition(Old, New->getLocation());
2404     return New->setInvalidDecl();
2405   }
2406 
2407   // Modules always permit redefinition of typedefs, as does C11.
2408   if (getLangOpts().Modules || getLangOpts().C11)
2409     return;
2410 
2411   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2412   // is normally mapped to an error, but can be controlled with
2413   // -Wtypedef-redefinition.  If either the original or the redefinition is
2414   // in a system header, don't emit this for compatibility with GCC.
2415   if (getDiagnostics().getSuppressSystemWarnings() &&
2416       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2417       (Old->isImplicit() ||
2418        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2419        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2420     return;
2421 
2422   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2423     << New->getDeclName();
2424   notePreviousDefinition(Old, New->getLocation());
2425 }
2426 
2427 /// DeclhasAttr - returns true if decl Declaration already has the target
2428 /// attribute.
2429 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2430   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2431   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2432   for (const auto *i : D->attrs())
2433     if (i->getKind() == A->getKind()) {
2434       if (Ann) {
2435         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2436           return true;
2437         continue;
2438       }
2439       // FIXME: Don't hardcode this check
2440       if (OA && isa<OwnershipAttr>(i))
2441         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2442       return true;
2443     }
2444 
2445   return false;
2446 }
2447 
2448 static bool isAttributeTargetADefinition(Decl *D) {
2449   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2450     return VD->isThisDeclarationADefinition();
2451   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2452     return TD->isCompleteDefinition() || TD->isBeingDefined();
2453   return true;
2454 }
2455 
2456 /// Merge alignment attributes from \p Old to \p New, taking into account the
2457 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2458 ///
2459 /// \return \c true if any attributes were added to \p New.
2460 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2461   // Look for alignas attributes on Old, and pick out whichever attribute
2462   // specifies the strictest alignment requirement.
2463   AlignedAttr *OldAlignasAttr = nullptr;
2464   AlignedAttr *OldStrictestAlignAttr = nullptr;
2465   unsigned OldAlign = 0;
2466   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2467     // FIXME: We have no way of representing inherited dependent alignments
2468     // in a case like:
2469     //   template<int A, int B> struct alignas(A) X;
2470     //   template<int A, int B> struct alignas(B) X {};
2471     // For now, we just ignore any alignas attributes which are not on the
2472     // definition in such a case.
2473     if (I->isAlignmentDependent())
2474       return false;
2475 
2476     if (I->isAlignas())
2477       OldAlignasAttr = I;
2478 
2479     unsigned Align = I->getAlignment(S.Context);
2480     if (Align > OldAlign) {
2481       OldAlign = Align;
2482       OldStrictestAlignAttr = I;
2483     }
2484   }
2485 
2486   // Look for alignas attributes on New.
2487   AlignedAttr *NewAlignasAttr = nullptr;
2488   unsigned NewAlign = 0;
2489   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2490     if (I->isAlignmentDependent())
2491       return false;
2492 
2493     if (I->isAlignas())
2494       NewAlignasAttr = I;
2495 
2496     unsigned Align = I->getAlignment(S.Context);
2497     if (Align > NewAlign)
2498       NewAlign = Align;
2499   }
2500 
2501   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2502     // Both declarations have 'alignas' attributes. We require them to match.
2503     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2504     // fall short. (If two declarations both have alignas, they must both match
2505     // every definition, and so must match each other if there is a definition.)
2506 
2507     // If either declaration only contains 'alignas(0)' specifiers, then it
2508     // specifies the natural alignment for the type.
2509     if (OldAlign == 0 || NewAlign == 0) {
2510       QualType Ty;
2511       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2512         Ty = VD->getType();
2513       else
2514         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2515 
2516       if (OldAlign == 0)
2517         OldAlign = S.Context.getTypeAlign(Ty);
2518       if (NewAlign == 0)
2519         NewAlign = S.Context.getTypeAlign(Ty);
2520     }
2521 
2522     if (OldAlign != NewAlign) {
2523       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2524         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2525         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2526       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2527     }
2528   }
2529 
2530   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2531     // C++11 [dcl.align]p6:
2532     //   if any declaration of an entity has an alignment-specifier,
2533     //   every defining declaration of that entity shall specify an
2534     //   equivalent alignment.
2535     // C11 6.7.5/7:
2536     //   If the definition of an object does not have an alignment
2537     //   specifier, any other declaration of that object shall also
2538     //   have no alignment specifier.
2539     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2540       << OldAlignasAttr;
2541     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2542       << OldAlignasAttr;
2543   }
2544 
2545   bool AnyAdded = false;
2546 
2547   // Ensure we have an attribute representing the strictest alignment.
2548   if (OldAlign > NewAlign) {
2549     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2550     Clone->setInherited(true);
2551     New->addAttr(Clone);
2552     AnyAdded = true;
2553   }
2554 
2555   // Ensure we have an alignas attribute if the old declaration had one.
2556   if (OldAlignasAttr && !NewAlignasAttr &&
2557       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2558     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2559     Clone->setInherited(true);
2560     New->addAttr(Clone);
2561     AnyAdded = true;
2562   }
2563 
2564   return AnyAdded;
2565 }
2566 
2567 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2568                                const InheritableAttr *Attr,
2569                                Sema::AvailabilityMergeKind AMK) {
2570   // This function copies an attribute Attr from a previous declaration to the
2571   // new declaration D if the new declaration doesn't itself have that attribute
2572   // yet or if that attribute allows duplicates.
2573   // If you're adding a new attribute that requires logic different from
2574   // "use explicit attribute on decl if present, else use attribute from
2575   // previous decl", for example if the attribute needs to be consistent
2576   // between redeclarations, you need to call a custom merge function here.
2577   InheritableAttr *NewAttr = nullptr;
2578   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2579     NewAttr = S.mergeAvailabilityAttr(
2580         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2581         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2582         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2583         AA->getPriority());
2584   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2585     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2586   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2587     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2588   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2589     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2590   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2591     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2592   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2593     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2594                                 FA->getFirstArg());
2595   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2596     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2597   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2598     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2599   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2600     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2601                                        IA->getInheritanceModel());
2602   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2603     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2604                                       &S.Context.Idents.get(AA->getSpelling()));
2605   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2606            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2607             isa<CUDAGlobalAttr>(Attr))) {
2608     // CUDA target attributes are part of function signature for
2609     // overloading purposes and must not be merged.
2610     return false;
2611   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2612     NewAttr = S.mergeMinSizeAttr(D, *MA);
2613   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2614     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2615   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2616     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2617   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2618     NewAttr = S.mergeCommonAttr(D, *CommonA);
2619   else if (isa<AlignedAttr>(Attr))
2620     // AlignedAttrs are handled separately, because we need to handle all
2621     // such attributes on a declaration at the same time.
2622     NewAttr = nullptr;
2623   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2624            (AMK == Sema::AMK_Override ||
2625             AMK == Sema::AMK_ProtocolImplementation))
2626     NewAttr = nullptr;
2627   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2628     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2629   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2630     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2631   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2632     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2633   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2634     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2635   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2636     NewAttr = S.mergeImportNameAttr(D, *INA);
2637   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2638     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2639 
2640   if (NewAttr) {
2641     NewAttr->setInherited(true);
2642     D->addAttr(NewAttr);
2643     if (isa<MSInheritanceAttr>(NewAttr))
2644       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2645     return true;
2646   }
2647 
2648   return false;
2649 }
2650 
2651 static const NamedDecl *getDefinition(const Decl *D) {
2652   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2653     return TD->getDefinition();
2654   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2655     const VarDecl *Def = VD->getDefinition();
2656     if (Def)
2657       return Def;
2658     return VD->getActingDefinition();
2659   }
2660   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2661     return FD->getDefinition();
2662   return nullptr;
2663 }
2664 
2665 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2666   for (const auto *Attribute : D->attrs())
2667     if (Attribute->getKind() == Kind)
2668       return true;
2669   return false;
2670 }
2671 
2672 /// checkNewAttributesAfterDef - If we already have a definition, check that
2673 /// there are no new attributes in this declaration.
2674 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2675   if (!New->hasAttrs())
2676     return;
2677 
2678   const NamedDecl *Def = getDefinition(Old);
2679   if (!Def || Def == New)
2680     return;
2681 
2682   AttrVec &NewAttributes = New->getAttrs();
2683   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2684     const Attr *NewAttribute = NewAttributes[I];
2685 
2686     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2687       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2688         Sema::SkipBodyInfo SkipBody;
2689         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2690 
2691         // If we're skipping this definition, drop the "alias" attribute.
2692         if (SkipBody.ShouldSkip) {
2693           NewAttributes.erase(NewAttributes.begin() + I);
2694           --E;
2695           continue;
2696         }
2697       } else {
2698         VarDecl *VD = cast<VarDecl>(New);
2699         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2700                                 VarDecl::TentativeDefinition
2701                             ? diag::err_alias_after_tentative
2702                             : diag::err_redefinition;
2703         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2704         if (Diag == diag::err_redefinition)
2705           S.notePreviousDefinition(Def, VD->getLocation());
2706         else
2707           S.Diag(Def->getLocation(), diag::note_previous_definition);
2708         VD->setInvalidDecl();
2709       }
2710       ++I;
2711       continue;
2712     }
2713 
2714     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2715       // Tentative definitions are only interesting for the alias check above.
2716       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2717         ++I;
2718         continue;
2719       }
2720     }
2721 
2722     if (hasAttribute(Def, NewAttribute->getKind())) {
2723       ++I;
2724       continue; // regular attr merging will take care of validating this.
2725     }
2726 
2727     if (isa<C11NoReturnAttr>(NewAttribute)) {
2728       // C's _Noreturn is allowed to be added to a function after it is defined.
2729       ++I;
2730       continue;
2731     } else if (isa<UuidAttr>(NewAttribute)) {
2732       // msvc will allow a subsequent definition to add an uuid to a class
2733       ++I;
2734       continue;
2735     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2736       if (AA->isAlignas()) {
2737         // C++11 [dcl.align]p6:
2738         //   if any declaration of an entity has an alignment-specifier,
2739         //   every defining declaration of that entity shall specify an
2740         //   equivalent alignment.
2741         // C11 6.7.5/7:
2742         //   If the definition of an object does not have an alignment
2743         //   specifier, any other declaration of that object shall also
2744         //   have no alignment specifier.
2745         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2746           << AA;
2747         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2748           << AA;
2749         NewAttributes.erase(NewAttributes.begin() + I);
2750         --E;
2751         continue;
2752       }
2753     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2754       // If there is a C definition followed by a redeclaration with this
2755       // attribute then there are two different definitions. In C++, prefer the
2756       // standard diagnostics.
2757       if (!S.getLangOpts().CPlusPlus) {
2758         S.Diag(NewAttribute->getLocation(),
2759                diag::err_loader_uninitialized_redeclaration);
2760         S.Diag(Def->getLocation(), diag::note_previous_definition);
2761         NewAttributes.erase(NewAttributes.begin() + I);
2762         --E;
2763         continue;
2764       }
2765     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2766                cast<VarDecl>(New)->isInline() &&
2767                !cast<VarDecl>(New)->isInlineSpecified()) {
2768       // Don't warn about applying selectany to implicitly inline variables.
2769       // Older compilers and language modes would require the use of selectany
2770       // to make such variables inline, and it would have no effect if we
2771       // honored it.
2772       ++I;
2773       continue;
2774     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2775       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2776       // declarations after defintions.
2777       ++I;
2778       continue;
2779     }
2780 
2781     S.Diag(NewAttribute->getLocation(),
2782            diag::warn_attribute_precede_definition);
2783     S.Diag(Def->getLocation(), diag::note_previous_definition);
2784     NewAttributes.erase(NewAttributes.begin() + I);
2785     --E;
2786   }
2787 }
2788 
2789 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2790                                      const ConstInitAttr *CIAttr,
2791                                      bool AttrBeforeInit) {
2792   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2793 
2794   // Figure out a good way to write this specifier on the old declaration.
2795   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2796   // enough of the attribute list spelling information to extract that without
2797   // heroics.
2798   std::string SuitableSpelling;
2799   if (S.getLangOpts().CPlusPlus20)
2800     SuitableSpelling = std::string(
2801         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2802   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2803     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2804         InsertLoc, {tok::l_square, tok::l_square,
2805                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2806                     S.PP.getIdentifierInfo("require_constant_initialization"),
2807                     tok::r_square, tok::r_square}));
2808   if (SuitableSpelling.empty())
2809     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2810         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2811                     S.PP.getIdentifierInfo("require_constant_initialization"),
2812                     tok::r_paren, tok::r_paren}));
2813   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2814     SuitableSpelling = "constinit";
2815   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2816     SuitableSpelling = "[[clang::require_constant_initialization]]";
2817   if (SuitableSpelling.empty())
2818     SuitableSpelling = "__attribute__((require_constant_initialization))";
2819   SuitableSpelling += " ";
2820 
2821   if (AttrBeforeInit) {
2822     // extern constinit int a;
2823     // int a = 0; // error (missing 'constinit'), accepted as extension
2824     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2825     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2826         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2827     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2828   } else {
2829     // int a = 0;
2830     // constinit extern int a; // error (missing 'constinit')
2831     S.Diag(CIAttr->getLocation(),
2832            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2833                                  : diag::warn_require_const_init_added_too_late)
2834         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2835     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2836         << CIAttr->isConstinit()
2837         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2838   }
2839 }
2840 
2841 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2842 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2843                                AvailabilityMergeKind AMK) {
2844   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2845     UsedAttr *NewAttr = OldAttr->clone(Context);
2846     NewAttr->setInherited(true);
2847     New->addAttr(NewAttr);
2848   }
2849 
2850   if (!Old->hasAttrs() && !New->hasAttrs())
2851     return;
2852 
2853   // [dcl.constinit]p1:
2854   //   If the [constinit] specifier is applied to any declaration of a
2855   //   variable, it shall be applied to the initializing declaration.
2856   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2857   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2858   if (bool(OldConstInit) != bool(NewConstInit)) {
2859     const auto *OldVD = cast<VarDecl>(Old);
2860     auto *NewVD = cast<VarDecl>(New);
2861 
2862     // Find the initializing declaration. Note that we might not have linked
2863     // the new declaration into the redeclaration chain yet.
2864     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2865     if (!InitDecl &&
2866         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2867       InitDecl = NewVD;
2868 
2869     if (InitDecl == NewVD) {
2870       // This is the initializing declaration. If it would inherit 'constinit',
2871       // that's ill-formed. (Note that we do not apply this to the attribute
2872       // form).
2873       if (OldConstInit && OldConstInit->isConstinit())
2874         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2875                                  /*AttrBeforeInit=*/true);
2876     } else if (NewConstInit) {
2877       // This is the first time we've been told that this declaration should
2878       // have a constant initializer. If we already saw the initializing
2879       // declaration, this is too late.
2880       if (InitDecl && InitDecl != NewVD) {
2881         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2882                                  /*AttrBeforeInit=*/false);
2883         NewVD->dropAttr<ConstInitAttr>();
2884       }
2885     }
2886   }
2887 
2888   // Attributes declared post-definition are currently ignored.
2889   checkNewAttributesAfterDef(*this, New, Old);
2890 
2891   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2892     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2893       if (!OldA->isEquivalent(NewA)) {
2894         // This redeclaration changes __asm__ label.
2895         Diag(New->getLocation(), diag::err_different_asm_label);
2896         Diag(OldA->getLocation(), diag::note_previous_declaration);
2897       }
2898     } else if (Old->isUsed()) {
2899       // This redeclaration adds an __asm__ label to a declaration that has
2900       // already been ODR-used.
2901       Diag(New->getLocation(), diag::err_late_asm_label_name)
2902         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2903     }
2904   }
2905 
2906   // Re-declaration cannot add abi_tag's.
2907   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2908     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2909       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2910         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2911                       NewTag) == OldAbiTagAttr->tags_end()) {
2912           Diag(NewAbiTagAttr->getLocation(),
2913                diag::err_new_abi_tag_on_redeclaration)
2914               << NewTag;
2915           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2916         }
2917       }
2918     } else {
2919       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2920       Diag(Old->getLocation(), diag::note_previous_declaration);
2921     }
2922   }
2923 
2924   // This redeclaration adds a section attribute.
2925   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2926     if (auto *VD = dyn_cast<VarDecl>(New)) {
2927       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2928         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2929         Diag(Old->getLocation(), diag::note_previous_declaration);
2930       }
2931     }
2932   }
2933 
2934   // Redeclaration adds code-seg attribute.
2935   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2936   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2937       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2938     Diag(New->getLocation(), diag::warn_mismatched_section)
2939          << 0 /*codeseg*/;
2940     Diag(Old->getLocation(), diag::note_previous_declaration);
2941   }
2942 
2943   if (!Old->hasAttrs())
2944     return;
2945 
2946   bool foundAny = New->hasAttrs();
2947 
2948   // Ensure that any moving of objects within the allocated map is done before
2949   // we process them.
2950   if (!foundAny) New->setAttrs(AttrVec());
2951 
2952   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2953     // Ignore deprecated/unavailable/availability attributes if requested.
2954     AvailabilityMergeKind LocalAMK = AMK_None;
2955     if (isa<DeprecatedAttr>(I) ||
2956         isa<UnavailableAttr>(I) ||
2957         isa<AvailabilityAttr>(I)) {
2958       switch (AMK) {
2959       case AMK_None:
2960         continue;
2961 
2962       case AMK_Redeclaration:
2963       case AMK_Override:
2964       case AMK_ProtocolImplementation:
2965         LocalAMK = AMK;
2966         break;
2967       }
2968     }
2969 
2970     // Already handled.
2971     if (isa<UsedAttr>(I))
2972       continue;
2973 
2974     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2975       foundAny = true;
2976   }
2977 
2978   if (mergeAlignedAttrs(*this, New, Old))
2979     foundAny = true;
2980 
2981   if (!foundAny) New->dropAttrs();
2982 }
2983 
2984 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2985 /// to the new one.
2986 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2987                                      const ParmVarDecl *oldDecl,
2988                                      Sema &S) {
2989   // C++11 [dcl.attr.depend]p2:
2990   //   The first declaration of a function shall specify the
2991   //   carries_dependency attribute for its declarator-id if any declaration
2992   //   of the function specifies the carries_dependency attribute.
2993   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2994   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2995     S.Diag(CDA->getLocation(),
2996            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2997     // Find the first declaration of the parameter.
2998     // FIXME: Should we build redeclaration chains for function parameters?
2999     const FunctionDecl *FirstFD =
3000       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3001     const ParmVarDecl *FirstVD =
3002       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3003     S.Diag(FirstVD->getLocation(),
3004            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3005   }
3006 
3007   if (!oldDecl->hasAttrs())
3008     return;
3009 
3010   bool foundAny = newDecl->hasAttrs();
3011 
3012   // Ensure that any moving of objects within the allocated map is
3013   // done before we process them.
3014   if (!foundAny) newDecl->setAttrs(AttrVec());
3015 
3016   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3017     if (!DeclHasAttr(newDecl, I)) {
3018       InheritableAttr *newAttr =
3019         cast<InheritableParamAttr>(I->clone(S.Context));
3020       newAttr->setInherited(true);
3021       newDecl->addAttr(newAttr);
3022       foundAny = true;
3023     }
3024   }
3025 
3026   if (!foundAny) newDecl->dropAttrs();
3027 }
3028 
3029 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3030                                 const ParmVarDecl *OldParam,
3031                                 Sema &S) {
3032   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3033     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3034       if (*Oldnullability != *Newnullability) {
3035         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3036           << DiagNullabilityKind(
3037                *Newnullability,
3038                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3039                 != 0))
3040           << DiagNullabilityKind(
3041                *Oldnullability,
3042                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3043                 != 0));
3044         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3045       }
3046     } else {
3047       QualType NewT = NewParam->getType();
3048       NewT = S.Context.getAttributedType(
3049                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3050                          NewT, NewT);
3051       NewParam->setType(NewT);
3052     }
3053   }
3054 }
3055 
3056 namespace {
3057 
3058 /// Used in MergeFunctionDecl to keep track of function parameters in
3059 /// C.
3060 struct GNUCompatibleParamWarning {
3061   ParmVarDecl *OldParm;
3062   ParmVarDecl *NewParm;
3063   QualType PromotedType;
3064 };
3065 
3066 } // end anonymous namespace
3067 
3068 // Determine whether the previous declaration was a definition, implicit
3069 // declaration, or a declaration.
3070 template <typename T>
3071 static std::pair<diag::kind, SourceLocation>
3072 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3073   diag::kind PrevDiag;
3074   SourceLocation OldLocation = Old->getLocation();
3075   if (Old->isThisDeclarationADefinition())
3076     PrevDiag = diag::note_previous_definition;
3077   else if (Old->isImplicit()) {
3078     PrevDiag = diag::note_previous_implicit_declaration;
3079     if (OldLocation.isInvalid())
3080       OldLocation = New->getLocation();
3081   } else
3082     PrevDiag = diag::note_previous_declaration;
3083   return std::make_pair(PrevDiag, OldLocation);
3084 }
3085 
3086 /// canRedefineFunction - checks if a function can be redefined. Currently,
3087 /// only extern inline functions can be redefined, and even then only in
3088 /// GNU89 mode.
3089 static bool canRedefineFunction(const FunctionDecl *FD,
3090                                 const LangOptions& LangOpts) {
3091   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3092           !LangOpts.CPlusPlus &&
3093           FD->isInlineSpecified() &&
3094           FD->getStorageClass() == SC_Extern);
3095 }
3096 
3097 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3098   const AttributedType *AT = T->getAs<AttributedType>();
3099   while (AT && !AT->isCallingConv())
3100     AT = AT->getModifiedType()->getAs<AttributedType>();
3101   return AT;
3102 }
3103 
3104 template <typename T>
3105 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3106   const DeclContext *DC = Old->getDeclContext();
3107   if (DC->isRecord())
3108     return false;
3109 
3110   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3111   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3112     return true;
3113   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3114     return true;
3115   return false;
3116 }
3117 
3118 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3119 static bool isExternC(VarTemplateDecl *) { return false; }
3120 
3121 /// Check whether a redeclaration of an entity introduced by a
3122 /// using-declaration is valid, given that we know it's not an overload
3123 /// (nor a hidden tag declaration).
3124 template<typename ExpectedDecl>
3125 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3126                                    ExpectedDecl *New) {
3127   // C++11 [basic.scope.declarative]p4:
3128   //   Given a set of declarations in a single declarative region, each of
3129   //   which specifies the same unqualified name,
3130   //   -- they shall all refer to the same entity, or all refer to functions
3131   //      and function templates; or
3132   //   -- exactly one declaration shall declare a class name or enumeration
3133   //      name that is not a typedef name and the other declarations shall all
3134   //      refer to the same variable or enumerator, or all refer to functions
3135   //      and function templates; in this case the class name or enumeration
3136   //      name is hidden (3.3.10).
3137 
3138   // C++11 [namespace.udecl]p14:
3139   //   If a function declaration in namespace scope or block scope has the
3140   //   same name and the same parameter-type-list as a function introduced
3141   //   by a using-declaration, and the declarations do not declare the same
3142   //   function, the program is ill-formed.
3143 
3144   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3145   if (Old &&
3146       !Old->getDeclContext()->getRedeclContext()->Equals(
3147           New->getDeclContext()->getRedeclContext()) &&
3148       !(isExternC(Old) && isExternC(New)))
3149     Old = nullptr;
3150 
3151   if (!Old) {
3152     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3153     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3154     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3155     return true;
3156   }
3157   return false;
3158 }
3159 
3160 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3161                                             const FunctionDecl *B) {
3162   assert(A->getNumParams() == B->getNumParams());
3163 
3164   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3165     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3166     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3167     if (AttrA == AttrB)
3168       return true;
3169     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3170            AttrA->isDynamic() == AttrB->isDynamic();
3171   };
3172 
3173   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3174 }
3175 
3176 /// If necessary, adjust the semantic declaration context for a qualified
3177 /// declaration to name the correct inline namespace within the qualifier.
3178 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3179                                                DeclaratorDecl *OldD) {
3180   // The only case where we need to update the DeclContext is when
3181   // redeclaration lookup for a qualified name finds a declaration
3182   // in an inline namespace within the context named by the qualifier:
3183   //
3184   //   inline namespace N { int f(); }
3185   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3186   //
3187   // For unqualified declarations, the semantic context *can* change
3188   // along the redeclaration chain (for local extern declarations,
3189   // extern "C" declarations, and friend declarations in particular).
3190   if (!NewD->getQualifier())
3191     return;
3192 
3193   // NewD is probably already in the right context.
3194   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3195   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3196   if (NamedDC->Equals(SemaDC))
3197     return;
3198 
3199   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3200           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3201          "unexpected context for redeclaration");
3202 
3203   auto *LexDC = NewD->getLexicalDeclContext();
3204   auto FixSemaDC = [=](NamedDecl *D) {
3205     if (!D)
3206       return;
3207     D->setDeclContext(SemaDC);
3208     D->setLexicalDeclContext(LexDC);
3209   };
3210 
3211   FixSemaDC(NewD);
3212   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3213     FixSemaDC(FD->getDescribedFunctionTemplate());
3214   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3215     FixSemaDC(VD->getDescribedVarTemplate());
3216 }
3217 
3218 /// MergeFunctionDecl - We just parsed a function 'New' from
3219 /// declarator D which has the same name and scope as a previous
3220 /// declaration 'Old'.  Figure out how to resolve this situation,
3221 /// merging decls or emitting diagnostics as appropriate.
3222 ///
3223 /// In C++, New and Old must be declarations that are not
3224 /// overloaded. Use IsOverload to determine whether New and Old are
3225 /// overloaded, and to select the Old declaration that New should be
3226 /// merged with.
3227 ///
3228 /// Returns true if there was an error, false otherwise.
3229 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3230                              Scope *S, bool MergeTypeWithOld) {
3231   // Verify the old decl was also a function.
3232   FunctionDecl *Old = OldD->getAsFunction();
3233   if (!Old) {
3234     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3235       if (New->getFriendObjectKind()) {
3236         Diag(New->getLocation(), diag::err_using_decl_friend);
3237         Diag(Shadow->getTargetDecl()->getLocation(),
3238              diag::note_using_decl_target);
3239         Diag(Shadow->getUsingDecl()->getLocation(),
3240              diag::note_using_decl) << 0;
3241         return true;
3242       }
3243 
3244       // Check whether the two declarations might declare the same function.
3245       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3246         return true;
3247       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3248     } else {
3249       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3250         << New->getDeclName();
3251       notePreviousDefinition(OldD, New->getLocation());
3252       return true;
3253     }
3254   }
3255 
3256   // If the old declaration is invalid, just give up here.
3257   if (Old->isInvalidDecl())
3258     return true;
3259 
3260   // Disallow redeclaration of some builtins.
3261   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3262     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3263     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3264         << Old << Old->getType();
3265     return true;
3266   }
3267 
3268   diag::kind PrevDiag;
3269   SourceLocation OldLocation;
3270   std::tie(PrevDiag, OldLocation) =
3271       getNoteDiagForInvalidRedeclaration(Old, New);
3272 
3273   // Don't complain about this if we're in GNU89 mode and the old function
3274   // is an extern inline function.
3275   // Don't complain about specializations. They are not supposed to have
3276   // storage classes.
3277   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3278       New->getStorageClass() == SC_Static &&
3279       Old->hasExternalFormalLinkage() &&
3280       !New->getTemplateSpecializationInfo() &&
3281       !canRedefineFunction(Old, getLangOpts())) {
3282     if (getLangOpts().MicrosoftExt) {
3283       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3284       Diag(OldLocation, PrevDiag);
3285     } else {
3286       Diag(New->getLocation(), diag::err_static_non_static) << New;
3287       Diag(OldLocation, PrevDiag);
3288       return true;
3289     }
3290   }
3291 
3292   if (New->hasAttr<InternalLinkageAttr>() &&
3293       !Old->hasAttr<InternalLinkageAttr>()) {
3294     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3295         << New->getDeclName();
3296     notePreviousDefinition(Old, New->getLocation());
3297     New->dropAttr<InternalLinkageAttr>();
3298   }
3299 
3300   if (CheckRedeclarationModuleOwnership(New, Old))
3301     return true;
3302 
3303   if (!getLangOpts().CPlusPlus) {
3304     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3305     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3306       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3307         << New << OldOvl;
3308 
3309       // Try our best to find a decl that actually has the overloadable
3310       // attribute for the note. In most cases (e.g. programs with only one
3311       // broken declaration/definition), this won't matter.
3312       //
3313       // FIXME: We could do this if we juggled some extra state in
3314       // OverloadableAttr, rather than just removing it.
3315       const Decl *DiagOld = Old;
3316       if (OldOvl) {
3317         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3318           const auto *A = D->getAttr<OverloadableAttr>();
3319           return A && !A->isImplicit();
3320         });
3321         // If we've implicitly added *all* of the overloadable attrs to this
3322         // chain, emitting a "previous redecl" note is pointless.
3323         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3324       }
3325 
3326       if (DiagOld)
3327         Diag(DiagOld->getLocation(),
3328              diag::note_attribute_overloadable_prev_overload)
3329           << OldOvl;
3330 
3331       if (OldOvl)
3332         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3333       else
3334         New->dropAttr<OverloadableAttr>();
3335     }
3336   }
3337 
3338   // If a function is first declared with a calling convention, but is later
3339   // declared or defined without one, all following decls assume the calling
3340   // convention of the first.
3341   //
3342   // It's OK if a function is first declared without a calling convention,
3343   // but is later declared or defined with the default calling convention.
3344   //
3345   // To test if either decl has an explicit calling convention, we look for
3346   // AttributedType sugar nodes on the type as written.  If they are missing or
3347   // were canonicalized away, we assume the calling convention was implicit.
3348   //
3349   // Note also that we DO NOT return at this point, because we still have
3350   // other tests to run.
3351   QualType OldQType = Context.getCanonicalType(Old->getType());
3352   QualType NewQType = Context.getCanonicalType(New->getType());
3353   const FunctionType *OldType = cast<FunctionType>(OldQType);
3354   const FunctionType *NewType = cast<FunctionType>(NewQType);
3355   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3356   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3357   bool RequiresAdjustment = false;
3358 
3359   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3360     FunctionDecl *First = Old->getFirstDecl();
3361     const FunctionType *FT =
3362         First->getType().getCanonicalType()->castAs<FunctionType>();
3363     FunctionType::ExtInfo FI = FT->getExtInfo();
3364     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3365     if (!NewCCExplicit) {
3366       // Inherit the CC from the previous declaration if it was specified
3367       // there but not here.
3368       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3369       RequiresAdjustment = true;
3370     } else if (Old->getBuiltinID()) {
3371       // Builtin attribute isn't propagated to the new one yet at this point,
3372       // so we check if the old one is a builtin.
3373 
3374       // Calling Conventions on a Builtin aren't really useful and setting a
3375       // default calling convention and cdecl'ing some builtin redeclarations is
3376       // common, so warn and ignore the calling convention on the redeclaration.
3377       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3378           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3379           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3380       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3381       RequiresAdjustment = true;
3382     } else {
3383       // Calling conventions aren't compatible, so complain.
3384       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3385       Diag(New->getLocation(), diag::err_cconv_change)
3386         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3387         << !FirstCCExplicit
3388         << (!FirstCCExplicit ? "" :
3389             FunctionType::getNameForCallConv(FI.getCC()));
3390 
3391       // Put the note on the first decl, since it is the one that matters.
3392       Diag(First->getLocation(), diag::note_previous_declaration);
3393       return true;
3394     }
3395   }
3396 
3397   // FIXME: diagnose the other way around?
3398   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3399     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3400     RequiresAdjustment = true;
3401   }
3402 
3403   // Merge regparm attribute.
3404   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3405       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3406     if (NewTypeInfo.getHasRegParm()) {
3407       Diag(New->getLocation(), diag::err_regparm_mismatch)
3408         << NewType->getRegParmType()
3409         << OldType->getRegParmType();
3410       Diag(OldLocation, diag::note_previous_declaration);
3411       return true;
3412     }
3413 
3414     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3415     RequiresAdjustment = true;
3416   }
3417 
3418   // Merge ns_returns_retained attribute.
3419   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3420     if (NewTypeInfo.getProducesResult()) {
3421       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3422           << "'ns_returns_retained'";
3423       Diag(OldLocation, diag::note_previous_declaration);
3424       return true;
3425     }
3426 
3427     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3428     RequiresAdjustment = true;
3429   }
3430 
3431   if (OldTypeInfo.getNoCallerSavedRegs() !=
3432       NewTypeInfo.getNoCallerSavedRegs()) {
3433     if (NewTypeInfo.getNoCallerSavedRegs()) {
3434       AnyX86NoCallerSavedRegistersAttr *Attr =
3435         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3436       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3437       Diag(OldLocation, diag::note_previous_declaration);
3438       return true;
3439     }
3440 
3441     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3442     RequiresAdjustment = true;
3443   }
3444 
3445   if (RequiresAdjustment) {
3446     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3447     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3448     New->setType(QualType(AdjustedType, 0));
3449     NewQType = Context.getCanonicalType(New->getType());
3450   }
3451 
3452   // If this redeclaration makes the function inline, we may need to add it to
3453   // UndefinedButUsed.
3454   if (!Old->isInlined() && New->isInlined() &&
3455       !New->hasAttr<GNUInlineAttr>() &&
3456       !getLangOpts().GNUInline &&
3457       Old->isUsed(false) &&
3458       !Old->isDefined() && !New->isThisDeclarationADefinition())
3459     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3460                                            SourceLocation()));
3461 
3462   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3463   // about it.
3464   if (New->hasAttr<GNUInlineAttr>() &&
3465       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3466     UndefinedButUsed.erase(Old->getCanonicalDecl());
3467   }
3468 
3469   // If pass_object_size params don't match up perfectly, this isn't a valid
3470   // redeclaration.
3471   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3472       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3473     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3474         << New->getDeclName();
3475     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3476     return true;
3477   }
3478 
3479   if (getLangOpts().CPlusPlus) {
3480     // C++1z [over.load]p2
3481     //   Certain function declarations cannot be overloaded:
3482     //     -- Function declarations that differ only in the return type,
3483     //        the exception specification, or both cannot be overloaded.
3484 
3485     // Check the exception specifications match. This may recompute the type of
3486     // both Old and New if it resolved exception specifications, so grab the
3487     // types again after this. Because this updates the type, we do this before
3488     // any of the other checks below, which may update the "de facto" NewQType
3489     // but do not necessarily update the type of New.
3490     if (CheckEquivalentExceptionSpec(Old, New))
3491       return true;
3492     OldQType = Context.getCanonicalType(Old->getType());
3493     NewQType = Context.getCanonicalType(New->getType());
3494 
3495     // Go back to the type source info to compare the declared return types,
3496     // per C++1y [dcl.type.auto]p13:
3497     //   Redeclarations or specializations of a function or function template
3498     //   with a declared return type that uses a placeholder type shall also
3499     //   use that placeholder, not a deduced type.
3500     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3501     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3502     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3503         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3504                                        OldDeclaredReturnType)) {
3505       QualType ResQT;
3506       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3507           OldDeclaredReturnType->isObjCObjectPointerType())
3508         // FIXME: This does the wrong thing for a deduced return type.
3509         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3510       if (ResQT.isNull()) {
3511         if (New->isCXXClassMember() && New->isOutOfLine())
3512           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3513               << New << New->getReturnTypeSourceRange();
3514         else
3515           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3516               << New->getReturnTypeSourceRange();
3517         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3518                                     << Old->getReturnTypeSourceRange();
3519         return true;
3520       }
3521       else
3522         NewQType = ResQT;
3523     }
3524 
3525     QualType OldReturnType = OldType->getReturnType();
3526     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3527     if (OldReturnType != NewReturnType) {
3528       // If this function has a deduced return type and has already been
3529       // defined, copy the deduced value from the old declaration.
3530       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3531       if (OldAT && OldAT->isDeduced()) {
3532         New->setType(
3533             SubstAutoType(New->getType(),
3534                           OldAT->isDependentType() ? Context.DependentTy
3535                                                    : OldAT->getDeducedType()));
3536         NewQType = Context.getCanonicalType(
3537             SubstAutoType(NewQType,
3538                           OldAT->isDependentType() ? Context.DependentTy
3539                                                    : OldAT->getDeducedType()));
3540       }
3541     }
3542 
3543     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3544     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3545     if (OldMethod && NewMethod) {
3546       // Preserve triviality.
3547       NewMethod->setTrivial(OldMethod->isTrivial());
3548 
3549       // MSVC allows explicit template specialization at class scope:
3550       // 2 CXXMethodDecls referring to the same function will be injected.
3551       // We don't want a redeclaration error.
3552       bool IsClassScopeExplicitSpecialization =
3553                               OldMethod->isFunctionTemplateSpecialization() &&
3554                               NewMethod->isFunctionTemplateSpecialization();
3555       bool isFriend = NewMethod->getFriendObjectKind();
3556 
3557       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3558           !IsClassScopeExplicitSpecialization) {
3559         //    -- Member function declarations with the same name and the
3560         //       same parameter types cannot be overloaded if any of them
3561         //       is a static member function declaration.
3562         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3563           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3564           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3565           return true;
3566         }
3567 
3568         // C++ [class.mem]p1:
3569         //   [...] A member shall not be declared twice in the
3570         //   member-specification, except that a nested class or member
3571         //   class template can be declared and then later defined.
3572         if (!inTemplateInstantiation()) {
3573           unsigned NewDiag;
3574           if (isa<CXXConstructorDecl>(OldMethod))
3575             NewDiag = diag::err_constructor_redeclared;
3576           else if (isa<CXXDestructorDecl>(NewMethod))
3577             NewDiag = diag::err_destructor_redeclared;
3578           else if (isa<CXXConversionDecl>(NewMethod))
3579             NewDiag = diag::err_conv_function_redeclared;
3580           else
3581             NewDiag = diag::err_member_redeclared;
3582 
3583           Diag(New->getLocation(), NewDiag);
3584         } else {
3585           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3586             << New << New->getType();
3587         }
3588         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3589         return true;
3590 
3591       // Complain if this is an explicit declaration of a special
3592       // member that was initially declared implicitly.
3593       //
3594       // As an exception, it's okay to befriend such methods in order
3595       // to permit the implicit constructor/destructor/operator calls.
3596       } else if (OldMethod->isImplicit()) {
3597         if (isFriend) {
3598           NewMethod->setImplicit();
3599         } else {
3600           Diag(NewMethod->getLocation(),
3601                diag::err_definition_of_implicitly_declared_member)
3602             << New << getSpecialMember(OldMethod);
3603           return true;
3604         }
3605       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3606         Diag(NewMethod->getLocation(),
3607              diag::err_definition_of_explicitly_defaulted_member)
3608           << getSpecialMember(OldMethod);
3609         return true;
3610       }
3611     }
3612 
3613     // C++11 [dcl.attr.noreturn]p1:
3614     //   The first declaration of a function shall specify the noreturn
3615     //   attribute if any declaration of that function specifies the noreturn
3616     //   attribute.
3617     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3618     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3619       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3620       Diag(Old->getFirstDecl()->getLocation(),
3621            diag::note_noreturn_missing_first_decl);
3622     }
3623 
3624     // C++11 [dcl.attr.depend]p2:
3625     //   The first declaration of a function shall specify the
3626     //   carries_dependency attribute for its declarator-id if any declaration
3627     //   of the function specifies the carries_dependency attribute.
3628     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3629     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3630       Diag(CDA->getLocation(),
3631            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3632       Diag(Old->getFirstDecl()->getLocation(),
3633            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3634     }
3635 
3636     // (C++98 8.3.5p3):
3637     //   All declarations for a function shall agree exactly in both the
3638     //   return type and the parameter-type-list.
3639     // We also want to respect all the extended bits except noreturn.
3640 
3641     // noreturn should now match unless the old type info didn't have it.
3642     QualType OldQTypeForComparison = OldQType;
3643     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3644       auto *OldType = OldQType->castAs<FunctionProtoType>();
3645       const FunctionType *OldTypeForComparison
3646         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3647       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3648       assert(OldQTypeForComparison.isCanonical());
3649     }
3650 
3651     if (haveIncompatibleLanguageLinkages(Old, New)) {
3652       // As a special case, retain the language linkage from previous
3653       // declarations of a friend function as an extension.
3654       //
3655       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3656       // and is useful because there's otherwise no way to specify language
3657       // linkage within class scope.
3658       //
3659       // Check cautiously as the friend object kind isn't yet complete.
3660       if (New->getFriendObjectKind() != Decl::FOK_None) {
3661         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3662         Diag(OldLocation, PrevDiag);
3663       } else {
3664         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3665         Diag(OldLocation, PrevDiag);
3666         return true;
3667       }
3668     }
3669 
3670     // If the function types are compatible, merge the declarations. Ignore the
3671     // exception specifier because it was already checked above in
3672     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3673     // about incompatible types under -fms-compatibility.
3674     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3675                                                          NewQType))
3676       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3677 
3678     // If the types are imprecise (due to dependent constructs in friends or
3679     // local extern declarations), it's OK if they differ. We'll check again
3680     // during instantiation.
3681     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3682       return false;
3683 
3684     // Fall through for conflicting redeclarations and redefinitions.
3685   }
3686 
3687   // C: Function types need to be compatible, not identical. This handles
3688   // duplicate function decls like "void f(int); void f(enum X);" properly.
3689   if (!getLangOpts().CPlusPlus &&
3690       Context.typesAreCompatible(OldQType, NewQType)) {
3691     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3692     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3693     const FunctionProtoType *OldProto = nullptr;
3694     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3695         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3696       // The old declaration provided a function prototype, but the
3697       // new declaration does not. Merge in the prototype.
3698       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3699       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3700       NewQType =
3701           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3702                                   OldProto->getExtProtoInfo());
3703       New->setType(NewQType);
3704       New->setHasInheritedPrototype();
3705 
3706       // Synthesize parameters with the same types.
3707       SmallVector<ParmVarDecl*, 16> Params;
3708       for (const auto &ParamType : OldProto->param_types()) {
3709         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3710                                                  SourceLocation(), nullptr,
3711                                                  ParamType, /*TInfo=*/nullptr,
3712                                                  SC_None, nullptr);
3713         Param->setScopeInfo(0, Params.size());
3714         Param->setImplicit();
3715         Params.push_back(Param);
3716       }
3717 
3718       New->setParams(Params);
3719     }
3720 
3721     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3722   }
3723 
3724   // Check if the function types are compatible when pointer size address
3725   // spaces are ignored.
3726   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3727     return false;
3728 
3729   // GNU C permits a K&R definition to follow a prototype declaration
3730   // if the declared types of the parameters in the K&R definition
3731   // match the types in the prototype declaration, even when the
3732   // promoted types of the parameters from the K&R definition differ
3733   // from the types in the prototype. GCC then keeps the types from
3734   // the prototype.
3735   //
3736   // If a variadic prototype is followed by a non-variadic K&R definition,
3737   // the K&R definition becomes variadic.  This is sort of an edge case, but
3738   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3739   // C99 6.9.1p8.
3740   if (!getLangOpts().CPlusPlus &&
3741       Old->hasPrototype() && !New->hasPrototype() &&
3742       New->getType()->getAs<FunctionProtoType>() &&
3743       Old->getNumParams() == New->getNumParams()) {
3744     SmallVector<QualType, 16> ArgTypes;
3745     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3746     const FunctionProtoType *OldProto
3747       = Old->getType()->getAs<FunctionProtoType>();
3748     const FunctionProtoType *NewProto
3749       = New->getType()->getAs<FunctionProtoType>();
3750 
3751     // Determine whether this is the GNU C extension.
3752     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3753                                                NewProto->getReturnType());
3754     bool LooseCompatible = !MergedReturn.isNull();
3755     for (unsigned Idx = 0, End = Old->getNumParams();
3756          LooseCompatible && Idx != End; ++Idx) {
3757       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3758       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3759       if (Context.typesAreCompatible(OldParm->getType(),
3760                                      NewProto->getParamType(Idx))) {
3761         ArgTypes.push_back(NewParm->getType());
3762       } else if (Context.typesAreCompatible(OldParm->getType(),
3763                                             NewParm->getType(),
3764                                             /*CompareUnqualified=*/true)) {
3765         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3766                                            NewProto->getParamType(Idx) };
3767         Warnings.push_back(Warn);
3768         ArgTypes.push_back(NewParm->getType());
3769       } else
3770         LooseCompatible = false;
3771     }
3772 
3773     if (LooseCompatible) {
3774       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3775         Diag(Warnings[Warn].NewParm->getLocation(),
3776              diag::ext_param_promoted_not_compatible_with_prototype)
3777           << Warnings[Warn].PromotedType
3778           << Warnings[Warn].OldParm->getType();
3779         if (Warnings[Warn].OldParm->getLocation().isValid())
3780           Diag(Warnings[Warn].OldParm->getLocation(),
3781                diag::note_previous_declaration);
3782       }
3783 
3784       if (MergeTypeWithOld)
3785         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3786                                              OldProto->getExtProtoInfo()));
3787       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3788     }
3789 
3790     // Fall through to diagnose conflicting types.
3791   }
3792 
3793   // A function that has already been declared has been redeclared or
3794   // defined with a different type; show an appropriate diagnostic.
3795 
3796   // If the previous declaration was an implicitly-generated builtin
3797   // declaration, then at the very least we should use a specialized note.
3798   unsigned BuiltinID;
3799   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3800     // If it's actually a library-defined builtin function like 'malloc'
3801     // or 'printf', just warn about the incompatible redeclaration.
3802     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3803       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3804       Diag(OldLocation, diag::note_previous_builtin_declaration)
3805         << Old << Old->getType();
3806       return false;
3807     }
3808 
3809     PrevDiag = diag::note_previous_builtin_declaration;
3810   }
3811 
3812   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3813   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3814   return true;
3815 }
3816 
3817 /// Completes the merge of two function declarations that are
3818 /// known to be compatible.
3819 ///
3820 /// This routine handles the merging of attributes and other
3821 /// properties of function declarations from the old declaration to
3822 /// the new declaration, once we know that New is in fact a
3823 /// redeclaration of Old.
3824 ///
3825 /// \returns false
3826 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3827                                         Scope *S, bool MergeTypeWithOld) {
3828   // Merge the attributes
3829   mergeDeclAttributes(New, Old);
3830 
3831   // Merge "pure" flag.
3832   if (Old->isPure())
3833     New->setPure();
3834 
3835   // Merge "used" flag.
3836   if (Old->getMostRecentDecl()->isUsed(false))
3837     New->setIsUsed();
3838 
3839   // Merge attributes from the parameters.  These can mismatch with K&R
3840   // declarations.
3841   if (New->getNumParams() == Old->getNumParams())
3842       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3843         ParmVarDecl *NewParam = New->getParamDecl(i);
3844         ParmVarDecl *OldParam = Old->getParamDecl(i);
3845         mergeParamDeclAttributes(NewParam, OldParam, *this);
3846         mergeParamDeclTypes(NewParam, OldParam, *this);
3847       }
3848 
3849   if (getLangOpts().CPlusPlus)
3850     return MergeCXXFunctionDecl(New, Old, S);
3851 
3852   // Merge the function types so the we get the composite types for the return
3853   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3854   // was visible.
3855   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3856   if (!Merged.isNull() && MergeTypeWithOld)
3857     New->setType(Merged);
3858 
3859   return false;
3860 }
3861 
3862 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3863                                 ObjCMethodDecl *oldMethod) {
3864   // Merge the attributes, including deprecated/unavailable
3865   AvailabilityMergeKind MergeKind =
3866     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3867       ? AMK_ProtocolImplementation
3868       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3869                                                        : AMK_Override;
3870 
3871   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3872 
3873   // Merge attributes from the parameters.
3874   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3875                                        oe = oldMethod->param_end();
3876   for (ObjCMethodDecl::param_iterator
3877          ni = newMethod->param_begin(), ne = newMethod->param_end();
3878        ni != ne && oi != oe; ++ni, ++oi)
3879     mergeParamDeclAttributes(*ni, *oi, *this);
3880 
3881   CheckObjCMethodOverride(newMethod, oldMethod);
3882 }
3883 
3884 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3885   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3886 
3887   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3888          ? diag::err_redefinition_different_type
3889          : diag::err_redeclaration_different_type)
3890     << New->getDeclName() << New->getType() << Old->getType();
3891 
3892   diag::kind PrevDiag;
3893   SourceLocation OldLocation;
3894   std::tie(PrevDiag, OldLocation)
3895     = getNoteDiagForInvalidRedeclaration(Old, New);
3896   S.Diag(OldLocation, PrevDiag);
3897   New->setInvalidDecl();
3898 }
3899 
3900 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3901 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3902 /// emitting diagnostics as appropriate.
3903 ///
3904 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3905 /// to here in AddInitializerToDecl. We can't check them before the initializer
3906 /// is attached.
3907 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3908                              bool MergeTypeWithOld) {
3909   if (New->isInvalidDecl() || Old->isInvalidDecl())
3910     return;
3911 
3912   QualType MergedT;
3913   if (getLangOpts().CPlusPlus) {
3914     if (New->getType()->isUndeducedType()) {
3915       // We don't know what the new type is until the initializer is attached.
3916       return;
3917     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3918       // These could still be something that needs exception specs checked.
3919       return MergeVarDeclExceptionSpecs(New, Old);
3920     }
3921     // C++ [basic.link]p10:
3922     //   [...] the types specified by all declarations referring to a given
3923     //   object or function shall be identical, except that declarations for an
3924     //   array object can specify array types that differ by the presence or
3925     //   absence of a major array bound (8.3.4).
3926     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3927       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3928       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3929 
3930       // We are merging a variable declaration New into Old. If it has an array
3931       // bound, and that bound differs from Old's bound, we should diagnose the
3932       // mismatch.
3933       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3934         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3935              PrevVD = PrevVD->getPreviousDecl()) {
3936           QualType PrevVDTy = PrevVD->getType();
3937           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3938             continue;
3939 
3940           if (!Context.hasSameType(New->getType(), PrevVDTy))
3941             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3942         }
3943       }
3944 
3945       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3946         if (Context.hasSameType(OldArray->getElementType(),
3947                                 NewArray->getElementType()))
3948           MergedT = New->getType();
3949       }
3950       // FIXME: Check visibility. New is hidden but has a complete type. If New
3951       // has no array bound, it should not inherit one from Old, if Old is not
3952       // visible.
3953       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3954         if (Context.hasSameType(OldArray->getElementType(),
3955                                 NewArray->getElementType()))
3956           MergedT = Old->getType();
3957       }
3958     }
3959     else if (New->getType()->isObjCObjectPointerType() &&
3960                Old->getType()->isObjCObjectPointerType()) {
3961       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3962                                               Old->getType());
3963     }
3964   } else {
3965     // C 6.2.7p2:
3966     //   All declarations that refer to the same object or function shall have
3967     //   compatible type.
3968     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3969   }
3970   if (MergedT.isNull()) {
3971     // It's OK if we couldn't merge types if either type is dependent, for a
3972     // block-scope variable. In other cases (static data members of class
3973     // templates, variable templates, ...), we require the types to be
3974     // equivalent.
3975     // FIXME: The C++ standard doesn't say anything about this.
3976     if ((New->getType()->isDependentType() ||
3977          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3978       // If the old type was dependent, we can't merge with it, so the new type
3979       // becomes dependent for now. We'll reproduce the original type when we
3980       // instantiate the TypeSourceInfo for the variable.
3981       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3982         New->setType(Context.DependentTy);
3983       return;
3984     }
3985     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3986   }
3987 
3988   // Don't actually update the type on the new declaration if the old
3989   // declaration was an extern declaration in a different scope.
3990   if (MergeTypeWithOld)
3991     New->setType(MergedT);
3992 }
3993 
3994 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3995                                   LookupResult &Previous) {
3996   // C11 6.2.7p4:
3997   //   For an identifier with internal or external linkage declared
3998   //   in a scope in which a prior declaration of that identifier is
3999   //   visible, if the prior declaration specifies internal or
4000   //   external linkage, the type of the identifier at the later
4001   //   declaration becomes the composite type.
4002   //
4003   // If the variable isn't visible, we do not merge with its type.
4004   if (Previous.isShadowed())
4005     return false;
4006 
4007   if (S.getLangOpts().CPlusPlus) {
4008     // C++11 [dcl.array]p3:
4009     //   If there is a preceding declaration of the entity in the same
4010     //   scope in which the bound was specified, an omitted array bound
4011     //   is taken to be the same as in that earlier declaration.
4012     return NewVD->isPreviousDeclInSameBlockScope() ||
4013            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4014             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4015   } else {
4016     // If the old declaration was function-local, don't merge with its
4017     // type unless we're in the same function.
4018     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4019            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4020   }
4021 }
4022 
4023 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4024 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4025 /// situation, merging decls or emitting diagnostics as appropriate.
4026 ///
4027 /// Tentative definition rules (C99 6.9.2p2) are checked by
4028 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4029 /// definitions here, since the initializer hasn't been attached.
4030 ///
4031 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4032   // If the new decl is already invalid, don't do any other checking.
4033   if (New->isInvalidDecl())
4034     return;
4035 
4036   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4037     return;
4038 
4039   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4040 
4041   // Verify the old decl was also a variable or variable template.
4042   VarDecl *Old = nullptr;
4043   VarTemplateDecl *OldTemplate = nullptr;
4044   if (Previous.isSingleResult()) {
4045     if (NewTemplate) {
4046       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4047       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4048 
4049       if (auto *Shadow =
4050               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4051         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4052           return New->setInvalidDecl();
4053     } else {
4054       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4055 
4056       if (auto *Shadow =
4057               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4058         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4059           return New->setInvalidDecl();
4060     }
4061   }
4062   if (!Old) {
4063     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4064         << New->getDeclName();
4065     notePreviousDefinition(Previous.getRepresentativeDecl(),
4066                            New->getLocation());
4067     return New->setInvalidDecl();
4068   }
4069 
4070   // Ensure the template parameters are compatible.
4071   if (NewTemplate &&
4072       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4073                                       OldTemplate->getTemplateParameters(),
4074                                       /*Complain=*/true, TPL_TemplateMatch))
4075     return New->setInvalidDecl();
4076 
4077   // C++ [class.mem]p1:
4078   //   A member shall not be declared twice in the member-specification [...]
4079   //
4080   // Here, we need only consider static data members.
4081   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4082     Diag(New->getLocation(), diag::err_duplicate_member)
4083       << New->getIdentifier();
4084     Diag(Old->getLocation(), diag::note_previous_declaration);
4085     New->setInvalidDecl();
4086   }
4087 
4088   mergeDeclAttributes(New, Old);
4089   // Warn if an already-declared variable is made a weak_import in a subsequent
4090   // declaration
4091   if (New->hasAttr<WeakImportAttr>() &&
4092       Old->getStorageClass() == SC_None &&
4093       !Old->hasAttr<WeakImportAttr>()) {
4094     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4095     notePreviousDefinition(Old, New->getLocation());
4096     // Remove weak_import attribute on new declaration.
4097     New->dropAttr<WeakImportAttr>();
4098   }
4099 
4100   if (New->hasAttr<InternalLinkageAttr>() &&
4101       !Old->hasAttr<InternalLinkageAttr>()) {
4102     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4103         << New->getDeclName();
4104     notePreviousDefinition(Old, New->getLocation());
4105     New->dropAttr<InternalLinkageAttr>();
4106   }
4107 
4108   // Merge the types.
4109   VarDecl *MostRecent = Old->getMostRecentDecl();
4110   if (MostRecent != Old) {
4111     MergeVarDeclTypes(New, MostRecent,
4112                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4113     if (New->isInvalidDecl())
4114       return;
4115   }
4116 
4117   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4118   if (New->isInvalidDecl())
4119     return;
4120 
4121   diag::kind PrevDiag;
4122   SourceLocation OldLocation;
4123   std::tie(PrevDiag, OldLocation) =
4124       getNoteDiagForInvalidRedeclaration(Old, New);
4125 
4126   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4127   if (New->getStorageClass() == SC_Static &&
4128       !New->isStaticDataMember() &&
4129       Old->hasExternalFormalLinkage()) {
4130     if (getLangOpts().MicrosoftExt) {
4131       Diag(New->getLocation(), diag::ext_static_non_static)
4132           << New->getDeclName();
4133       Diag(OldLocation, PrevDiag);
4134     } else {
4135       Diag(New->getLocation(), diag::err_static_non_static)
4136           << New->getDeclName();
4137       Diag(OldLocation, PrevDiag);
4138       return New->setInvalidDecl();
4139     }
4140   }
4141   // C99 6.2.2p4:
4142   //   For an identifier declared with the storage-class specifier
4143   //   extern in a scope in which a prior declaration of that
4144   //   identifier is visible,23) if the prior declaration specifies
4145   //   internal or external linkage, the linkage of the identifier at
4146   //   the later declaration is the same as the linkage specified at
4147   //   the prior declaration. If no prior declaration is visible, or
4148   //   if the prior declaration specifies no linkage, then the
4149   //   identifier has external linkage.
4150   if (New->hasExternalStorage() && Old->hasLinkage())
4151     /* Okay */;
4152   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4153            !New->isStaticDataMember() &&
4154            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4155     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4156     Diag(OldLocation, PrevDiag);
4157     return New->setInvalidDecl();
4158   }
4159 
4160   // Check if extern is followed by non-extern and vice-versa.
4161   if (New->hasExternalStorage() &&
4162       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4163     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4164     Diag(OldLocation, PrevDiag);
4165     return New->setInvalidDecl();
4166   }
4167   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4168       !New->hasExternalStorage()) {
4169     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4170     Diag(OldLocation, PrevDiag);
4171     return New->setInvalidDecl();
4172   }
4173 
4174   if (CheckRedeclarationModuleOwnership(New, Old))
4175     return;
4176 
4177   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4178 
4179   // FIXME: The test for external storage here seems wrong? We still
4180   // need to check for mismatches.
4181   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4182       // Don't complain about out-of-line definitions of static members.
4183       !(Old->getLexicalDeclContext()->isRecord() &&
4184         !New->getLexicalDeclContext()->isRecord())) {
4185     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4186     Diag(OldLocation, PrevDiag);
4187     return New->setInvalidDecl();
4188   }
4189 
4190   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4191     if (VarDecl *Def = Old->getDefinition()) {
4192       // C++1z [dcl.fcn.spec]p4:
4193       //   If the definition of a variable appears in a translation unit before
4194       //   its first declaration as inline, the program is ill-formed.
4195       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4196       Diag(Def->getLocation(), diag::note_previous_definition);
4197     }
4198   }
4199 
4200   // If this redeclaration makes the variable inline, we may need to add it to
4201   // UndefinedButUsed.
4202   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4203       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4204     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4205                                            SourceLocation()));
4206 
4207   if (New->getTLSKind() != Old->getTLSKind()) {
4208     if (!Old->getTLSKind()) {
4209       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4210       Diag(OldLocation, PrevDiag);
4211     } else if (!New->getTLSKind()) {
4212       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4213       Diag(OldLocation, PrevDiag);
4214     } else {
4215       // Do not allow redeclaration to change the variable between requiring
4216       // static and dynamic initialization.
4217       // FIXME: GCC allows this, but uses the TLS keyword on the first
4218       // declaration to determine the kind. Do we need to be compatible here?
4219       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4220         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4221       Diag(OldLocation, PrevDiag);
4222     }
4223   }
4224 
4225   // C++ doesn't have tentative definitions, so go right ahead and check here.
4226   if (getLangOpts().CPlusPlus &&
4227       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4228     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4229         Old->getCanonicalDecl()->isConstexpr()) {
4230       // This definition won't be a definition any more once it's been merged.
4231       Diag(New->getLocation(),
4232            diag::warn_deprecated_redundant_constexpr_static_def);
4233     } else if (VarDecl *Def = Old->getDefinition()) {
4234       if (checkVarDeclRedefinition(Def, New))
4235         return;
4236     }
4237   }
4238 
4239   if (haveIncompatibleLanguageLinkages(Old, New)) {
4240     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4241     Diag(OldLocation, PrevDiag);
4242     New->setInvalidDecl();
4243     return;
4244   }
4245 
4246   // Merge "used" flag.
4247   if (Old->getMostRecentDecl()->isUsed(false))
4248     New->setIsUsed();
4249 
4250   // Keep a chain of previous declarations.
4251   New->setPreviousDecl(Old);
4252   if (NewTemplate)
4253     NewTemplate->setPreviousDecl(OldTemplate);
4254   adjustDeclContextForDeclaratorDecl(New, Old);
4255 
4256   // Inherit access appropriately.
4257   New->setAccess(Old->getAccess());
4258   if (NewTemplate)
4259     NewTemplate->setAccess(New->getAccess());
4260 
4261   if (Old->isInline())
4262     New->setImplicitlyInline();
4263 }
4264 
4265 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4266   SourceManager &SrcMgr = getSourceManager();
4267   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4268   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4269   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4270   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4271   auto &HSI = PP.getHeaderSearchInfo();
4272   StringRef HdrFilename =
4273       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4274 
4275   auto noteFromModuleOrInclude = [&](Module *Mod,
4276                                      SourceLocation IncLoc) -> bool {
4277     // Redefinition errors with modules are common with non modular mapped
4278     // headers, example: a non-modular header H in module A that also gets
4279     // included directly in a TU. Pointing twice to the same header/definition
4280     // is confusing, try to get better diagnostics when modules is on.
4281     if (IncLoc.isValid()) {
4282       if (Mod) {
4283         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4284             << HdrFilename.str() << Mod->getFullModuleName();
4285         if (!Mod->DefinitionLoc.isInvalid())
4286           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4287               << Mod->getFullModuleName();
4288       } else {
4289         Diag(IncLoc, diag::note_redefinition_include_same_file)
4290             << HdrFilename.str();
4291       }
4292       return true;
4293     }
4294 
4295     return false;
4296   };
4297 
4298   // Is it the same file and same offset? Provide more information on why
4299   // this leads to a redefinition error.
4300   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4301     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4302     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4303     bool EmittedDiag =
4304         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4305     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4306 
4307     // If the header has no guards, emit a note suggesting one.
4308     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4309       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4310 
4311     if (EmittedDiag)
4312       return;
4313   }
4314 
4315   // Redefinition coming from different files or couldn't do better above.
4316   if (Old->getLocation().isValid())
4317     Diag(Old->getLocation(), diag::note_previous_definition);
4318 }
4319 
4320 /// We've just determined that \p Old and \p New both appear to be definitions
4321 /// of the same variable. Either diagnose or fix the problem.
4322 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4323   if (!hasVisibleDefinition(Old) &&
4324       (New->getFormalLinkage() == InternalLinkage ||
4325        New->isInline() ||
4326        New->getDescribedVarTemplate() ||
4327        New->getNumTemplateParameterLists() ||
4328        New->getDeclContext()->isDependentContext())) {
4329     // The previous definition is hidden, and multiple definitions are
4330     // permitted (in separate TUs). Demote this to a declaration.
4331     New->demoteThisDefinitionToDeclaration();
4332 
4333     // Make the canonical definition visible.
4334     if (auto *OldTD = Old->getDescribedVarTemplate())
4335       makeMergedDefinitionVisible(OldTD);
4336     makeMergedDefinitionVisible(Old);
4337     return false;
4338   } else {
4339     Diag(New->getLocation(), diag::err_redefinition) << New;
4340     notePreviousDefinition(Old, New->getLocation());
4341     New->setInvalidDecl();
4342     return true;
4343   }
4344 }
4345 
4346 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4347 /// no declarator (e.g. "struct foo;") is parsed.
4348 Decl *
4349 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4350                                  RecordDecl *&AnonRecord) {
4351   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4352                                     AnonRecord);
4353 }
4354 
4355 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4356 // disambiguate entities defined in different scopes.
4357 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4358 // compatibility.
4359 // We will pick our mangling number depending on which version of MSVC is being
4360 // targeted.
4361 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4362   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4363              ? S->getMSCurManglingNumber()
4364              : S->getMSLastManglingNumber();
4365 }
4366 
4367 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4368   if (!Context.getLangOpts().CPlusPlus)
4369     return;
4370 
4371   if (isa<CXXRecordDecl>(Tag->getParent())) {
4372     // If this tag is the direct child of a class, number it if
4373     // it is anonymous.
4374     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4375       return;
4376     MangleNumberingContext &MCtx =
4377         Context.getManglingNumberContext(Tag->getParent());
4378     Context.setManglingNumber(
4379         Tag, MCtx.getManglingNumber(
4380                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4381     return;
4382   }
4383 
4384   // If this tag isn't a direct child of a class, number it if it is local.
4385   MangleNumberingContext *MCtx;
4386   Decl *ManglingContextDecl;
4387   std::tie(MCtx, ManglingContextDecl) =
4388       getCurrentMangleNumberContext(Tag->getDeclContext());
4389   if (MCtx) {
4390     Context.setManglingNumber(
4391         Tag, MCtx->getManglingNumber(
4392                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4393   }
4394 }
4395 
4396 namespace {
4397 struct NonCLikeKind {
4398   enum {
4399     None,
4400     BaseClass,
4401     DefaultMemberInit,
4402     Lambda,
4403     Friend,
4404     OtherMember,
4405     Invalid,
4406   } Kind = None;
4407   SourceRange Range;
4408 
4409   explicit operator bool() { return Kind != None; }
4410 };
4411 }
4412 
4413 /// Determine whether a class is C-like, according to the rules of C++
4414 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4415 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4416   if (RD->isInvalidDecl())
4417     return {NonCLikeKind::Invalid, {}};
4418 
4419   // C++ [dcl.typedef]p9: [P1766R1]
4420   //   An unnamed class with a typedef name for linkage purposes shall not
4421   //
4422   //    -- have any base classes
4423   if (RD->getNumBases())
4424     return {NonCLikeKind::BaseClass,
4425             SourceRange(RD->bases_begin()->getBeginLoc(),
4426                         RD->bases_end()[-1].getEndLoc())};
4427   bool Invalid = false;
4428   for (Decl *D : RD->decls()) {
4429     // Don't complain about things we already diagnosed.
4430     if (D->isInvalidDecl()) {
4431       Invalid = true;
4432       continue;
4433     }
4434 
4435     //  -- have any [...] default member initializers
4436     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4437       if (FD->hasInClassInitializer()) {
4438         auto *Init = FD->getInClassInitializer();
4439         return {NonCLikeKind::DefaultMemberInit,
4440                 Init ? Init->getSourceRange() : D->getSourceRange()};
4441       }
4442       continue;
4443     }
4444 
4445     // FIXME: We don't allow friend declarations. This violates the wording of
4446     // P1766, but not the intent.
4447     if (isa<FriendDecl>(D))
4448       return {NonCLikeKind::Friend, D->getSourceRange()};
4449 
4450     //  -- declare any members other than non-static data members, member
4451     //     enumerations, or member classes,
4452     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4453         isa<EnumDecl>(D))
4454       continue;
4455     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4456     if (!MemberRD) {
4457       if (D->isImplicit())
4458         continue;
4459       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4460     }
4461 
4462     //  -- contain a lambda-expression,
4463     if (MemberRD->isLambda())
4464       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4465 
4466     //  and all member classes shall also satisfy these requirements
4467     //  (recursively).
4468     if (MemberRD->isThisDeclarationADefinition()) {
4469       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4470         return Kind;
4471     }
4472   }
4473 
4474   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4475 }
4476 
4477 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4478                                         TypedefNameDecl *NewTD) {
4479   if (TagFromDeclSpec->isInvalidDecl())
4480     return;
4481 
4482   // Do nothing if the tag already has a name for linkage purposes.
4483   if (TagFromDeclSpec->hasNameForLinkage())
4484     return;
4485 
4486   // A well-formed anonymous tag must always be a TUK_Definition.
4487   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4488 
4489   // The type must match the tag exactly;  no qualifiers allowed.
4490   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4491                            Context.getTagDeclType(TagFromDeclSpec))) {
4492     if (getLangOpts().CPlusPlus)
4493       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4494     return;
4495   }
4496 
4497   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4498   //   An unnamed class with a typedef name for linkage purposes shall [be
4499   //   C-like].
4500   //
4501   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4502   // shouldn't happen, but there are constructs that the language rule doesn't
4503   // disallow for which we can't reasonably avoid computing linkage early.
4504   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4505   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4506                              : NonCLikeKind();
4507   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4508   if (NonCLike || ChangesLinkage) {
4509     if (NonCLike.Kind == NonCLikeKind::Invalid)
4510       return;
4511 
4512     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4513     if (ChangesLinkage) {
4514       // If the linkage changes, we can't accept this as an extension.
4515       if (NonCLike.Kind == NonCLikeKind::None)
4516         DiagID = diag::err_typedef_changes_linkage;
4517       else
4518         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4519     }
4520 
4521     SourceLocation FixitLoc =
4522         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4523     llvm::SmallString<40> TextToInsert;
4524     TextToInsert += ' ';
4525     TextToInsert += NewTD->getIdentifier()->getName();
4526 
4527     Diag(FixitLoc, DiagID)
4528       << isa<TypeAliasDecl>(NewTD)
4529       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4530     if (NonCLike.Kind != NonCLikeKind::None) {
4531       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4532         << NonCLike.Kind - 1 << NonCLike.Range;
4533     }
4534     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4535       << NewTD << isa<TypeAliasDecl>(NewTD);
4536 
4537     if (ChangesLinkage)
4538       return;
4539   }
4540 
4541   // Otherwise, set this as the anon-decl typedef for the tag.
4542   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4543 }
4544 
4545 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4546   switch (T) {
4547   case DeclSpec::TST_class:
4548     return 0;
4549   case DeclSpec::TST_struct:
4550     return 1;
4551   case DeclSpec::TST_interface:
4552     return 2;
4553   case DeclSpec::TST_union:
4554     return 3;
4555   case DeclSpec::TST_enum:
4556     return 4;
4557   default:
4558     llvm_unreachable("unexpected type specifier");
4559   }
4560 }
4561 
4562 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4563 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4564 /// parameters to cope with template friend declarations.
4565 Decl *
4566 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4567                                  MultiTemplateParamsArg TemplateParams,
4568                                  bool IsExplicitInstantiation,
4569                                  RecordDecl *&AnonRecord) {
4570   Decl *TagD = nullptr;
4571   TagDecl *Tag = nullptr;
4572   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4573       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4574       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4575       DS.getTypeSpecType() == DeclSpec::TST_union ||
4576       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4577     TagD = DS.getRepAsDecl();
4578 
4579     if (!TagD) // We probably had an error
4580       return nullptr;
4581 
4582     // Note that the above type specs guarantee that the
4583     // type rep is a Decl, whereas in many of the others
4584     // it's a Type.
4585     if (isa<TagDecl>(TagD))
4586       Tag = cast<TagDecl>(TagD);
4587     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4588       Tag = CTD->getTemplatedDecl();
4589   }
4590 
4591   if (Tag) {
4592     handleTagNumbering(Tag, S);
4593     Tag->setFreeStanding();
4594     if (Tag->isInvalidDecl())
4595       return Tag;
4596   }
4597 
4598   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4599     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4600     // or incomplete types shall not be restrict-qualified."
4601     if (TypeQuals & DeclSpec::TQ_restrict)
4602       Diag(DS.getRestrictSpecLoc(),
4603            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4604            << DS.getSourceRange();
4605   }
4606 
4607   if (DS.isInlineSpecified())
4608     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4609         << getLangOpts().CPlusPlus17;
4610 
4611   if (DS.hasConstexprSpecifier()) {
4612     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4613     // and definitions of functions and variables.
4614     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4615     // the declaration of a function or function template
4616     if (Tag)
4617       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4618           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4619           << DS.getConstexprSpecifier();
4620     else
4621       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4622           << DS.getConstexprSpecifier();
4623     // Don't emit warnings after this error.
4624     return TagD;
4625   }
4626 
4627   DiagnoseFunctionSpecifiers(DS);
4628 
4629   if (DS.isFriendSpecified()) {
4630     // If we're dealing with a decl but not a TagDecl, assume that
4631     // whatever routines created it handled the friendship aspect.
4632     if (TagD && !Tag)
4633       return nullptr;
4634     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4635   }
4636 
4637   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4638   bool IsExplicitSpecialization =
4639     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4640   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4641       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4642       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4643     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4644     // nested-name-specifier unless it is an explicit instantiation
4645     // or an explicit specialization.
4646     //
4647     // FIXME: We allow class template partial specializations here too, per the
4648     // obvious intent of DR1819.
4649     //
4650     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4651     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4652         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4653     return nullptr;
4654   }
4655 
4656   // Track whether this decl-specifier declares anything.
4657   bool DeclaresAnything = true;
4658 
4659   // Handle anonymous struct definitions.
4660   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4661     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4662         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4663       if (getLangOpts().CPlusPlus ||
4664           Record->getDeclContext()->isRecord()) {
4665         // If CurContext is a DeclContext that can contain statements,
4666         // RecursiveASTVisitor won't visit the decls that
4667         // BuildAnonymousStructOrUnion() will put into CurContext.
4668         // Also store them here so that they can be part of the
4669         // DeclStmt that gets created in this case.
4670         // FIXME: Also return the IndirectFieldDecls created by
4671         // BuildAnonymousStructOr union, for the same reason?
4672         if (CurContext->isFunctionOrMethod())
4673           AnonRecord = Record;
4674         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4675                                            Context.getPrintingPolicy());
4676       }
4677 
4678       DeclaresAnything = false;
4679     }
4680   }
4681 
4682   // C11 6.7.2.1p2:
4683   //   A struct-declaration that does not declare an anonymous structure or
4684   //   anonymous union shall contain a struct-declarator-list.
4685   //
4686   // This rule also existed in C89 and C99; the grammar for struct-declaration
4687   // did not permit a struct-declaration without a struct-declarator-list.
4688   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4689       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4690     // Check for Microsoft C extension: anonymous struct/union member.
4691     // Handle 2 kinds of anonymous struct/union:
4692     //   struct STRUCT;
4693     //   union UNION;
4694     // and
4695     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4696     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4697     if ((Tag && Tag->getDeclName()) ||
4698         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4699       RecordDecl *Record = nullptr;
4700       if (Tag)
4701         Record = dyn_cast<RecordDecl>(Tag);
4702       else if (const RecordType *RT =
4703                    DS.getRepAsType().get()->getAsStructureType())
4704         Record = RT->getDecl();
4705       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4706         Record = UT->getDecl();
4707 
4708       if (Record && getLangOpts().MicrosoftExt) {
4709         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4710             << Record->isUnion() << DS.getSourceRange();
4711         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4712       }
4713 
4714       DeclaresAnything = false;
4715     }
4716   }
4717 
4718   // Skip all the checks below if we have a type error.
4719   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4720       (TagD && TagD->isInvalidDecl()))
4721     return TagD;
4722 
4723   if (getLangOpts().CPlusPlus &&
4724       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4725     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4726       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4727           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4728         DeclaresAnything = false;
4729 
4730   if (!DS.isMissingDeclaratorOk()) {
4731     // Customize diagnostic for a typedef missing a name.
4732     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4733       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4734           << DS.getSourceRange();
4735     else
4736       DeclaresAnything = false;
4737   }
4738 
4739   if (DS.isModulePrivateSpecified() &&
4740       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4741     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4742       << Tag->getTagKind()
4743       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4744 
4745   ActOnDocumentableDecl(TagD);
4746 
4747   // C 6.7/2:
4748   //   A declaration [...] shall declare at least a declarator [...], a tag,
4749   //   or the members of an enumeration.
4750   // C++ [dcl.dcl]p3:
4751   //   [If there are no declarators], and except for the declaration of an
4752   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4753   //   names into the program, or shall redeclare a name introduced by a
4754   //   previous declaration.
4755   if (!DeclaresAnything) {
4756     // In C, we allow this as a (popular) extension / bug. Don't bother
4757     // producing further diagnostics for redundant qualifiers after this.
4758     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4759                                ? diag::err_no_declarators
4760                                : diag::ext_no_declarators)
4761         << DS.getSourceRange();
4762     return TagD;
4763   }
4764 
4765   // C++ [dcl.stc]p1:
4766   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4767   //   init-declarator-list of the declaration shall not be empty.
4768   // C++ [dcl.fct.spec]p1:
4769   //   If a cv-qualifier appears in a decl-specifier-seq, the
4770   //   init-declarator-list of the declaration shall not be empty.
4771   //
4772   // Spurious qualifiers here appear to be valid in C.
4773   unsigned DiagID = diag::warn_standalone_specifier;
4774   if (getLangOpts().CPlusPlus)
4775     DiagID = diag::ext_standalone_specifier;
4776 
4777   // Note that a linkage-specification sets a storage class, but
4778   // 'extern "C" struct foo;' is actually valid and not theoretically
4779   // useless.
4780   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4781     if (SCS == DeclSpec::SCS_mutable)
4782       // Since mutable is not a viable storage class specifier in C, there is
4783       // no reason to treat it as an extension. Instead, diagnose as an error.
4784       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4785     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4786       Diag(DS.getStorageClassSpecLoc(), DiagID)
4787         << DeclSpec::getSpecifierName(SCS);
4788   }
4789 
4790   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4791     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4792       << DeclSpec::getSpecifierName(TSCS);
4793   if (DS.getTypeQualifiers()) {
4794     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4795       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4796     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4797       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4798     // Restrict is covered above.
4799     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4800       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4801     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4802       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4803   }
4804 
4805   // Warn about ignored type attributes, for example:
4806   // __attribute__((aligned)) struct A;
4807   // Attributes should be placed after tag to apply to type declaration.
4808   if (!DS.getAttributes().empty()) {
4809     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4810     if (TypeSpecType == DeclSpec::TST_class ||
4811         TypeSpecType == DeclSpec::TST_struct ||
4812         TypeSpecType == DeclSpec::TST_interface ||
4813         TypeSpecType == DeclSpec::TST_union ||
4814         TypeSpecType == DeclSpec::TST_enum) {
4815       for (const ParsedAttr &AL : DS.getAttributes())
4816         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4817             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4818     }
4819   }
4820 
4821   return TagD;
4822 }
4823 
4824 /// We are trying to inject an anonymous member into the given scope;
4825 /// check if there's an existing declaration that can't be overloaded.
4826 ///
4827 /// \return true if this is a forbidden redeclaration
4828 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4829                                          Scope *S,
4830                                          DeclContext *Owner,
4831                                          DeclarationName Name,
4832                                          SourceLocation NameLoc,
4833                                          bool IsUnion) {
4834   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4835                  Sema::ForVisibleRedeclaration);
4836   if (!SemaRef.LookupName(R, S)) return false;
4837 
4838   // Pick a representative declaration.
4839   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4840   assert(PrevDecl && "Expected a non-null Decl");
4841 
4842   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4843     return false;
4844 
4845   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4846     << IsUnion << Name;
4847   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4848 
4849   return true;
4850 }
4851 
4852 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4853 /// anonymous struct or union AnonRecord into the owning context Owner
4854 /// and scope S. This routine will be invoked just after we realize
4855 /// that an unnamed union or struct is actually an anonymous union or
4856 /// struct, e.g.,
4857 ///
4858 /// @code
4859 /// union {
4860 ///   int i;
4861 ///   float f;
4862 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4863 ///    // f into the surrounding scope.x
4864 /// @endcode
4865 ///
4866 /// This routine is recursive, injecting the names of nested anonymous
4867 /// structs/unions into the owning context and scope as well.
4868 static bool
4869 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4870                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4871                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4872   bool Invalid = false;
4873 
4874   // Look every FieldDecl and IndirectFieldDecl with a name.
4875   for (auto *D : AnonRecord->decls()) {
4876     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4877         cast<NamedDecl>(D)->getDeclName()) {
4878       ValueDecl *VD = cast<ValueDecl>(D);
4879       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4880                                        VD->getLocation(),
4881                                        AnonRecord->isUnion())) {
4882         // C++ [class.union]p2:
4883         //   The names of the members of an anonymous union shall be
4884         //   distinct from the names of any other entity in the
4885         //   scope in which the anonymous union is declared.
4886         Invalid = true;
4887       } else {
4888         // C++ [class.union]p2:
4889         //   For the purpose of name lookup, after the anonymous union
4890         //   definition, the members of the anonymous union are
4891         //   considered to have been defined in the scope in which the
4892         //   anonymous union is declared.
4893         unsigned OldChainingSize = Chaining.size();
4894         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4895           Chaining.append(IF->chain_begin(), IF->chain_end());
4896         else
4897           Chaining.push_back(VD);
4898 
4899         assert(Chaining.size() >= 2);
4900         NamedDecl **NamedChain =
4901           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4902         for (unsigned i = 0; i < Chaining.size(); i++)
4903           NamedChain[i] = Chaining[i];
4904 
4905         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4906             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4907             VD->getType(), {NamedChain, Chaining.size()});
4908 
4909         for (const auto *Attr : VD->attrs())
4910           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4911 
4912         IndirectField->setAccess(AS);
4913         IndirectField->setImplicit();
4914         SemaRef.PushOnScopeChains(IndirectField, S);
4915 
4916         // That includes picking up the appropriate access specifier.
4917         if (AS != AS_none) IndirectField->setAccess(AS);
4918 
4919         Chaining.resize(OldChainingSize);
4920       }
4921     }
4922   }
4923 
4924   return Invalid;
4925 }
4926 
4927 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4928 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4929 /// illegal input values are mapped to SC_None.
4930 static StorageClass
4931 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4932   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4933   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4934          "Parser allowed 'typedef' as storage class VarDecl.");
4935   switch (StorageClassSpec) {
4936   case DeclSpec::SCS_unspecified:    return SC_None;
4937   case DeclSpec::SCS_extern:
4938     if (DS.isExternInLinkageSpec())
4939       return SC_None;
4940     return SC_Extern;
4941   case DeclSpec::SCS_static:         return SC_Static;
4942   case DeclSpec::SCS_auto:           return SC_Auto;
4943   case DeclSpec::SCS_register:       return SC_Register;
4944   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4945     // Illegal SCSs map to None: error reporting is up to the caller.
4946   case DeclSpec::SCS_mutable:        // Fall through.
4947   case DeclSpec::SCS_typedef:        return SC_None;
4948   }
4949   llvm_unreachable("unknown storage class specifier");
4950 }
4951 
4952 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4953   assert(Record->hasInClassInitializer());
4954 
4955   for (const auto *I : Record->decls()) {
4956     const auto *FD = dyn_cast<FieldDecl>(I);
4957     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4958       FD = IFD->getAnonField();
4959     if (FD && FD->hasInClassInitializer())
4960       return FD->getLocation();
4961   }
4962 
4963   llvm_unreachable("couldn't find in-class initializer");
4964 }
4965 
4966 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4967                                       SourceLocation DefaultInitLoc) {
4968   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4969     return;
4970 
4971   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4972   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4973 }
4974 
4975 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4976                                       CXXRecordDecl *AnonUnion) {
4977   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4978     return;
4979 
4980   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4981 }
4982 
4983 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4984 /// anonymous structure or union. Anonymous unions are a C++ feature
4985 /// (C++ [class.union]) and a C11 feature; anonymous structures
4986 /// are a C11 feature and GNU C++ extension.
4987 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4988                                         AccessSpecifier AS,
4989                                         RecordDecl *Record,
4990                                         const PrintingPolicy &Policy) {
4991   DeclContext *Owner = Record->getDeclContext();
4992 
4993   // Diagnose whether this anonymous struct/union is an extension.
4994   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4995     Diag(Record->getLocation(), diag::ext_anonymous_union);
4996   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4997     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4998   else if (!Record->isUnion() && !getLangOpts().C11)
4999     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5000 
5001   // C and C++ require different kinds of checks for anonymous
5002   // structs/unions.
5003   bool Invalid = false;
5004   if (getLangOpts().CPlusPlus) {
5005     const char *PrevSpec = nullptr;
5006     if (Record->isUnion()) {
5007       // C++ [class.union]p6:
5008       // C++17 [class.union.anon]p2:
5009       //   Anonymous unions declared in a named namespace or in the
5010       //   global namespace shall be declared static.
5011       unsigned DiagID;
5012       DeclContext *OwnerScope = Owner->getRedeclContext();
5013       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5014           (OwnerScope->isTranslationUnit() ||
5015            (OwnerScope->isNamespace() &&
5016             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5017         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5018           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5019 
5020         // Recover by adding 'static'.
5021         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5022                                PrevSpec, DiagID, Policy);
5023       }
5024       // C++ [class.union]p6:
5025       //   A storage class is not allowed in a declaration of an
5026       //   anonymous union in a class scope.
5027       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5028                isa<RecordDecl>(Owner)) {
5029         Diag(DS.getStorageClassSpecLoc(),
5030              diag::err_anonymous_union_with_storage_spec)
5031           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5032 
5033         // Recover by removing the storage specifier.
5034         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5035                                SourceLocation(),
5036                                PrevSpec, DiagID, Context.getPrintingPolicy());
5037       }
5038     }
5039 
5040     // Ignore const/volatile/restrict qualifiers.
5041     if (DS.getTypeQualifiers()) {
5042       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5043         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5044           << Record->isUnion() << "const"
5045           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5046       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5047         Diag(DS.getVolatileSpecLoc(),
5048              diag::ext_anonymous_struct_union_qualified)
5049           << Record->isUnion() << "volatile"
5050           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5051       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5052         Diag(DS.getRestrictSpecLoc(),
5053              diag::ext_anonymous_struct_union_qualified)
5054           << Record->isUnion() << "restrict"
5055           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5056       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5057         Diag(DS.getAtomicSpecLoc(),
5058              diag::ext_anonymous_struct_union_qualified)
5059           << Record->isUnion() << "_Atomic"
5060           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5061       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5062         Diag(DS.getUnalignedSpecLoc(),
5063              diag::ext_anonymous_struct_union_qualified)
5064           << Record->isUnion() << "__unaligned"
5065           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5066 
5067       DS.ClearTypeQualifiers();
5068     }
5069 
5070     // C++ [class.union]p2:
5071     //   The member-specification of an anonymous union shall only
5072     //   define non-static data members. [Note: nested types and
5073     //   functions cannot be declared within an anonymous union. ]
5074     for (auto *Mem : Record->decls()) {
5075       // Ignore invalid declarations; we already diagnosed them.
5076       if (Mem->isInvalidDecl())
5077         continue;
5078 
5079       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5080         // C++ [class.union]p3:
5081         //   An anonymous union shall not have private or protected
5082         //   members (clause 11).
5083         assert(FD->getAccess() != AS_none);
5084         if (FD->getAccess() != AS_public) {
5085           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5086             << Record->isUnion() << (FD->getAccess() == AS_protected);
5087           Invalid = true;
5088         }
5089 
5090         // C++ [class.union]p1
5091         //   An object of a class with a non-trivial constructor, a non-trivial
5092         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5093         //   assignment operator cannot be a member of a union, nor can an
5094         //   array of such objects.
5095         if (CheckNontrivialField(FD))
5096           Invalid = true;
5097       } else if (Mem->isImplicit()) {
5098         // Any implicit members are fine.
5099       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5100         // This is a type that showed up in an
5101         // elaborated-type-specifier inside the anonymous struct or
5102         // union, but which actually declares a type outside of the
5103         // anonymous struct or union. It's okay.
5104       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5105         if (!MemRecord->isAnonymousStructOrUnion() &&
5106             MemRecord->getDeclName()) {
5107           // Visual C++ allows type definition in anonymous struct or union.
5108           if (getLangOpts().MicrosoftExt)
5109             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5110               << Record->isUnion();
5111           else {
5112             // This is a nested type declaration.
5113             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5114               << Record->isUnion();
5115             Invalid = true;
5116           }
5117         } else {
5118           // This is an anonymous type definition within another anonymous type.
5119           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5120           // not part of standard C++.
5121           Diag(MemRecord->getLocation(),
5122                diag::ext_anonymous_record_with_anonymous_type)
5123             << Record->isUnion();
5124         }
5125       } else if (isa<AccessSpecDecl>(Mem)) {
5126         // Any access specifier is fine.
5127       } else if (isa<StaticAssertDecl>(Mem)) {
5128         // In C++1z, static_assert declarations are also fine.
5129       } else {
5130         // We have something that isn't a non-static data
5131         // member. Complain about it.
5132         unsigned DK = diag::err_anonymous_record_bad_member;
5133         if (isa<TypeDecl>(Mem))
5134           DK = diag::err_anonymous_record_with_type;
5135         else if (isa<FunctionDecl>(Mem))
5136           DK = diag::err_anonymous_record_with_function;
5137         else if (isa<VarDecl>(Mem))
5138           DK = diag::err_anonymous_record_with_static;
5139 
5140         // Visual C++ allows type definition in anonymous struct or union.
5141         if (getLangOpts().MicrosoftExt &&
5142             DK == diag::err_anonymous_record_with_type)
5143           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5144             << Record->isUnion();
5145         else {
5146           Diag(Mem->getLocation(), DK) << Record->isUnion();
5147           Invalid = true;
5148         }
5149       }
5150     }
5151 
5152     // C++11 [class.union]p8 (DR1460):
5153     //   At most one variant member of a union may have a
5154     //   brace-or-equal-initializer.
5155     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5156         Owner->isRecord())
5157       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5158                                 cast<CXXRecordDecl>(Record));
5159   }
5160 
5161   if (!Record->isUnion() && !Owner->isRecord()) {
5162     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5163       << getLangOpts().CPlusPlus;
5164     Invalid = true;
5165   }
5166 
5167   // C++ [dcl.dcl]p3:
5168   //   [If there are no declarators], and except for the declaration of an
5169   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5170   //   names into the program
5171   // C++ [class.mem]p2:
5172   //   each such member-declaration shall either declare at least one member
5173   //   name of the class or declare at least one unnamed bit-field
5174   //
5175   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5176   if (getLangOpts().CPlusPlus && Record->field_empty())
5177     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5178 
5179   // Mock up a declarator.
5180   Declarator Dc(DS, DeclaratorContext::MemberContext);
5181   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5182   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5183 
5184   // Create a declaration for this anonymous struct/union.
5185   NamedDecl *Anon = nullptr;
5186   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5187     Anon = FieldDecl::Create(
5188         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5189         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5190         /*BitWidth=*/nullptr, /*Mutable=*/false,
5191         /*InitStyle=*/ICIS_NoInit);
5192     Anon->setAccess(AS);
5193     ProcessDeclAttributes(S, Anon, Dc);
5194 
5195     if (getLangOpts().CPlusPlus)
5196       FieldCollector->Add(cast<FieldDecl>(Anon));
5197   } else {
5198     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5199     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5200     if (SCSpec == DeclSpec::SCS_mutable) {
5201       // mutable can only appear on non-static class members, so it's always
5202       // an error here
5203       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5204       Invalid = true;
5205       SC = SC_None;
5206     }
5207 
5208     assert(DS.getAttributes().empty() && "No attribute expected");
5209     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5210                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5211                            Context.getTypeDeclType(Record), TInfo, SC);
5212 
5213     // Default-initialize the implicit variable. This initialization will be
5214     // trivial in almost all cases, except if a union member has an in-class
5215     // initializer:
5216     //   union { int n = 0; };
5217     ActOnUninitializedDecl(Anon);
5218   }
5219   Anon->setImplicit();
5220 
5221   // Mark this as an anonymous struct/union type.
5222   Record->setAnonymousStructOrUnion(true);
5223 
5224   // Add the anonymous struct/union object to the current
5225   // context. We'll be referencing this object when we refer to one of
5226   // its members.
5227   Owner->addDecl(Anon);
5228 
5229   // Inject the members of the anonymous struct/union into the owning
5230   // context and into the identifier resolver chain for name lookup
5231   // purposes.
5232   SmallVector<NamedDecl*, 2> Chain;
5233   Chain.push_back(Anon);
5234 
5235   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5236     Invalid = true;
5237 
5238   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5239     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5240       MangleNumberingContext *MCtx;
5241       Decl *ManglingContextDecl;
5242       std::tie(MCtx, ManglingContextDecl) =
5243           getCurrentMangleNumberContext(NewVD->getDeclContext());
5244       if (MCtx) {
5245         Context.setManglingNumber(
5246             NewVD, MCtx->getManglingNumber(
5247                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5248         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5249       }
5250     }
5251   }
5252 
5253   if (Invalid)
5254     Anon->setInvalidDecl();
5255 
5256   return Anon;
5257 }
5258 
5259 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5260 /// Microsoft C anonymous structure.
5261 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5262 /// Example:
5263 ///
5264 /// struct A { int a; };
5265 /// struct B { struct A; int b; };
5266 ///
5267 /// void foo() {
5268 ///   B var;
5269 ///   var.a = 3;
5270 /// }
5271 ///
5272 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5273                                            RecordDecl *Record) {
5274   assert(Record && "expected a record!");
5275 
5276   // Mock up a declarator.
5277   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5278   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5279   assert(TInfo && "couldn't build declarator info for anonymous struct");
5280 
5281   auto *ParentDecl = cast<RecordDecl>(CurContext);
5282   QualType RecTy = Context.getTypeDeclType(Record);
5283 
5284   // Create a declaration for this anonymous struct.
5285   NamedDecl *Anon =
5286       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5287                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5288                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5289                         /*InitStyle=*/ICIS_NoInit);
5290   Anon->setImplicit();
5291 
5292   // Add the anonymous struct object to the current context.
5293   CurContext->addDecl(Anon);
5294 
5295   // Inject the members of the anonymous struct into the current
5296   // context and into the identifier resolver chain for name lookup
5297   // purposes.
5298   SmallVector<NamedDecl*, 2> Chain;
5299   Chain.push_back(Anon);
5300 
5301   RecordDecl *RecordDef = Record->getDefinition();
5302   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5303                                diag::err_field_incomplete_or_sizeless) ||
5304       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5305                                           AS_none, Chain)) {
5306     Anon->setInvalidDecl();
5307     ParentDecl->setInvalidDecl();
5308   }
5309 
5310   return Anon;
5311 }
5312 
5313 /// GetNameForDeclarator - Determine the full declaration name for the
5314 /// given Declarator.
5315 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5316   return GetNameFromUnqualifiedId(D.getName());
5317 }
5318 
5319 /// Retrieves the declaration name from a parsed unqualified-id.
5320 DeclarationNameInfo
5321 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5322   DeclarationNameInfo NameInfo;
5323   NameInfo.setLoc(Name.StartLocation);
5324 
5325   switch (Name.getKind()) {
5326 
5327   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5328   case UnqualifiedIdKind::IK_Identifier:
5329     NameInfo.setName(Name.Identifier);
5330     return NameInfo;
5331 
5332   case UnqualifiedIdKind::IK_DeductionGuideName: {
5333     // C++ [temp.deduct.guide]p3:
5334     //   The simple-template-id shall name a class template specialization.
5335     //   The template-name shall be the same identifier as the template-name
5336     //   of the simple-template-id.
5337     // These together intend to imply that the template-name shall name a
5338     // class template.
5339     // FIXME: template<typename T> struct X {};
5340     //        template<typename T> using Y = X<T>;
5341     //        Y(int) -> Y<int>;
5342     //   satisfies these rules but does not name a class template.
5343     TemplateName TN = Name.TemplateName.get().get();
5344     auto *Template = TN.getAsTemplateDecl();
5345     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5346       Diag(Name.StartLocation,
5347            diag::err_deduction_guide_name_not_class_template)
5348         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5349       if (Template)
5350         Diag(Template->getLocation(), diag::note_template_decl_here);
5351       return DeclarationNameInfo();
5352     }
5353 
5354     NameInfo.setName(
5355         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5356     return NameInfo;
5357   }
5358 
5359   case UnqualifiedIdKind::IK_OperatorFunctionId:
5360     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5361                                            Name.OperatorFunctionId.Operator));
5362     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5363       = Name.OperatorFunctionId.SymbolLocations[0];
5364     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5365       = Name.EndLocation.getRawEncoding();
5366     return NameInfo;
5367 
5368   case UnqualifiedIdKind::IK_LiteralOperatorId:
5369     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5370                                                            Name.Identifier));
5371     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5372     return NameInfo;
5373 
5374   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5375     TypeSourceInfo *TInfo;
5376     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5377     if (Ty.isNull())
5378       return DeclarationNameInfo();
5379     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5380                                                Context.getCanonicalType(Ty)));
5381     NameInfo.setNamedTypeInfo(TInfo);
5382     return NameInfo;
5383   }
5384 
5385   case UnqualifiedIdKind::IK_ConstructorName: {
5386     TypeSourceInfo *TInfo;
5387     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5388     if (Ty.isNull())
5389       return DeclarationNameInfo();
5390     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5391                                               Context.getCanonicalType(Ty)));
5392     NameInfo.setNamedTypeInfo(TInfo);
5393     return NameInfo;
5394   }
5395 
5396   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5397     // In well-formed code, we can only have a constructor
5398     // template-id that refers to the current context, so go there
5399     // to find the actual type being constructed.
5400     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5401     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5402       return DeclarationNameInfo();
5403 
5404     // Determine the type of the class being constructed.
5405     QualType CurClassType = Context.getTypeDeclType(CurClass);
5406 
5407     // FIXME: Check two things: that the template-id names the same type as
5408     // CurClassType, and that the template-id does not occur when the name
5409     // was qualified.
5410 
5411     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5412                                     Context.getCanonicalType(CurClassType)));
5413     // FIXME: should we retrieve TypeSourceInfo?
5414     NameInfo.setNamedTypeInfo(nullptr);
5415     return NameInfo;
5416   }
5417 
5418   case UnqualifiedIdKind::IK_DestructorName: {
5419     TypeSourceInfo *TInfo;
5420     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5421     if (Ty.isNull())
5422       return DeclarationNameInfo();
5423     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5424                                               Context.getCanonicalType(Ty)));
5425     NameInfo.setNamedTypeInfo(TInfo);
5426     return NameInfo;
5427   }
5428 
5429   case UnqualifiedIdKind::IK_TemplateId: {
5430     TemplateName TName = Name.TemplateId->Template.get();
5431     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5432     return Context.getNameForTemplate(TName, TNameLoc);
5433   }
5434 
5435   } // switch (Name.getKind())
5436 
5437   llvm_unreachable("Unknown name kind");
5438 }
5439 
5440 static QualType getCoreType(QualType Ty) {
5441   do {
5442     if (Ty->isPointerType() || Ty->isReferenceType())
5443       Ty = Ty->getPointeeType();
5444     else if (Ty->isArrayType())
5445       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5446     else
5447       return Ty.withoutLocalFastQualifiers();
5448   } while (true);
5449 }
5450 
5451 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5452 /// and Definition have "nearly" matching parameters. This heuristic is
5453 /// used to improve diagnostics in the case where an out-of-line function
5454 /// definition doesn't match any declaration within the class or namespace.
5455 /// Also sets Params to the list of indices to the parameters that differ
5456 /// between the declaration and the definition. If hasSimilarParameters
5457 /// returns true and Params is empty, then all of the parameters match.
5458 static bool hasSimilarParameters(ASTContext &Context,
5459                                      FunctionDecl *Declaration,
5460                                      FunctionDecl *Definition,
5461                                      SmallVectorImpl<unsigned> &Params) {
5462   Params.clear();
5463   if (Declaration->param_size() != Definition->param_size())
5464     return false;
5465   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5466     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5467     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5468 
5469     // The parameter types are identical
5470     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5471       continue;
5472 
5473     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5474     QualType DefParamBaseTy = getCoreType(DefParamTy);
5475     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5476     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5477 
5478     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5479         (DeclTyName && DeclTyName == DefTyName))
5480       Params.push_back(Idx);
5481     else  // The two parameters aren't even close
5482       return false;
5483   }
5484 
5485   return true;
5486 }
5487 
5488 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5489 /// declarator needs to be rebuilt in the current instantiation.
5490 /// Any bits of declarator which appear before the name are valid for
5491 /// consideration here.  That's specifically the type in the decl spec
5492 /// and the base type in any member-pointer chunks.
5493 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5494                                                     DeclarationName Name) {
5495   // The types we specifically need to rebuild are:
5496   //   - typenames, typeofs, and decltypes
5497   //   - types which will become injected class names
5498   // Of course, we also need to rebuild any type referencing such a
5499   // type.  It's safest to just say "dependent", but we call out a
5500   // few cases here.
5501 
5502   DeclSpec &DS = D.getMutableDeclSpec();
5503   switch (DS.getTypeSpecType()) {
5504   case DeclSpec::TST_typename:
5505   case DeclSpec::TST_typeofType:
5506   case DeclSpec::TST_underlyingType:
5507   case DeclSpec::TST_atomic: {
5508     // Grab the type from the parser.
5509     TypeSourceInfo *TSI = nullptr;
5510     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5511     if (T.isNull() || !T->isDependentType()) break;
5512 
5513     // Make sure there's a type source info.  This isn't really much
5514     // of a waste; most dependent types should have type source info
5515     // attached already.
5516     if (!TSI)
5517       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5518 
5519     // Rebuild the type in the current instantiation.
5520     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5521     if (!TSI) return true;
5522 
5523     // Store the new type back in the decl spec.
5524     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5525     DS.UpdateTypeRep(LocType);
5526     break;
5527   }
5528 
5529   case DeclSpec::TST_decltype:
5530   case DeclSpec::TST_typeofExpr: {
5531     Expr *E = DS.getRepAsExpr();
5532     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5533     if (Result.isInvalid()) return true;
5534     DS.UpdateExprRep(Result.get());
5535     break;
5536   }
5537 
5538   default:
5539     // Nothing to do for these decl specs.
5540     break;
5541   }
5542 
5543   // It doesn't matter what order we do this in.
5544   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5545     DeclaratorChunk &Chunk = D.getTypeObject(I);
5546 
5547     // The only type information in the declarator which can come
5548     // before the declaration name is the base type of a member
5549     // pointer.
5550     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5551       continue;
5552 
5553     // Rebuild the scope specifier in-place.
5554     CXXScopeSpec &SS = Chunk.Mem.Scope();
5555     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5556       return true;
5557   }
5558 
5559   return false;
5560 }
5561 
5562 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5563   D.setFunctionDefinitionKind(FDK_Declaration);
5564   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5565 
5566   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5567       Dcl && Dcl->getDeclContext()->isFileContext())
5568     Dcl->setTopLevelDeclInObjCContainer();
5569 
5570   if (getLangOpts().OpenCL)
5571     setCurrentOpenCLExtensionForDecl(Dcl);
5572 
5573   return Dcl;
5574 }
5575 
5576 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5577 ///   If T is the name of a class, then each of the following shall have a
5578 ///   name different from T:
5579 ///     - every static data member of class T;
5580 ///     - every member function of class T
5581 ///     - every member of class T that is itself a type;
5582 /// \returns true if the declaration name violates these rules.
5583 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5584                                    DeclarationNameInfo NameInfo) {
5585   DeclarationName Name = NameInfo.getName();
5586 
5587   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5588   while (Record && Record->isAnonymousStructOrUnion())
5589     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5590   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5591     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5592     return true;
5593   }
5594 
5595   return false;
5596 }
5597 
5598 /// Diagnose a declaration whose declarator-id has the given
5599 /// nested-name-specifier.
5600 ///
5601 /// \param SS The nested-name-specifier of the declarator-id.
5602 ///
5603 /// \param DC The declaration context to which the nested-name-specifier
5604 /// resolves.
5605 ///
5606 /// \param Name The name of the entity being declared.
5607 ///
5608 /// \param Loc The location of the name of the entity being declared.
5609 ///
5610 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5611 /// we're declaring an explicit / partial specialization / instantiation.
5612 ///
5613 /// \returns true if we cannot safely recover from this error, false otherwise.
5614 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5615                                         DeclarationName Name,
5616                                         SourceLocation Loc, bool IsTemplateId) {
5617   DeclContext *Cur = CurContext;
5618   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5619     Cur = Cur->getParent();
5620 
5621   // If the user provided a superfluous scope specifier that refers back to the
5622   // class in which the entity is already declared, diagnose and ignore it.
5623   //
5624   // class X {
5625   //   void X::f();
5626   // };
5627   //
5628   // Note, it was once ill-formed to give redundant qualification in all
5629   // contexts, but that rule was removed by DR482.
5630   if (Cur->Equals(DC)) {
5631     if (Cur->isRecord()) {
5632       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5633                                       : diag::err_member_extra_qualification)
5634         << Name << FixItHint::CreateRemoval(SS.getRange());
5635       SS.clear();
5636     } else {
5637       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5638     }
5639     return false;
5640   }
5641 
5642   // Check whether the qualifying scope encloses the scope of the original
5643   // declaration. For a template-id, we perform the checks in
5644   // CheckTemplateSpecializationScope.
5645   if (!Cur->Encloses(DC) && !IsTemplateId) {
5646     if (Cur->isRecord())
5647       Diag(Loc, diag::err_member_qualification)
5648         << Name << SS.getRange();
5649     else if (isa<TranslationUnitDecl>(DC))
5650       Diag(Loc, diag::err_invalid_declarator_global_scope)
5651         << Name << SS.getRange();
5652     else if (isa<FunctionDecl>(Cur))
5653       Diag(Loc, diag::err_invalid_declarator_in_function)
5654         << Name << SS.getRange();
5655     else if (isa<BlockDecl>(Cur))
5656       Diag(Loc, diag::err_invalid_declarator_in_block)
5657         << Name << SS.getRange();
5658     else
5659       Diag(Loc, diag::err_invalid_declarator_scope)
5660       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5661 
5662     return true;
5663   }
5664 
5665   if (Cur->isRecord()) {
5666     // Cannot qualify members within a class.
5667     Diag(Loc, diag::err_member_qualification)
5668       << Name << SS.getRange();
5669     SS.clear();
5670 
5671     // C++ constructors and destructors with incorrect scopes can break
5672     // our AST invariants by having the wrong underlying types. If
5673     // that's the case, then drop this declaration entirely.
5674     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5675          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5676         !Context.hasSameType(Name.getCXXNameType(),
5677                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5678       return true;
5679 
5680     return false;
5681   }
5682 
5683   // C++11 [dcl.meaning]p1:
5684   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5685   //   not begin with a decltype-specifer"
5686   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5687   while (SpecLoc.getPrefix())
5688     SpecLoc = SpecLoc.getPrefix();
5689   if (dyn_cast_or_null<DecltypeType>(
5690         SpecLoc.getNestedNameSpecifier()->getAsType()))
5691     Diag(Loc, diag::err_decltype_in_declarator)
5692       << SpecLoc.getTypeLoc().getSourceRange();
5693 
5694   return false;
5695 }
5696 
5697 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5698                                   MultiTemplateParamsArg TemplateParamLists) {
5699   // TODO: consider using NameInfo for diagnostic.
5700   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5701   DeclarationName Name = NameInfo.getName();
5702 
5703   // All of these full declarators require an identifier.  If it doesn't have
5704   // one, the ParsedFreeStandingDeclSpec action should be used.
5705   if (D.isDecompositionDeclarator()) {
5706     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5707   } else if (!Name) {
5708     if (!D.isInvalidType())  // Reject this if we think it is valid.
5709       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5710           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5711     return nullptr;
5712   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5713     return nullptr;
5714 
5715   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5716   // we find one that is.
5717   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5718          (S->getFlags() & Scope::TemplateParamScope) != 0)
5719     S = S->getParent();
5720 
5721   DeclContext *DC = CurContext;
5722   if (D.getCXXScopeSpec().isInvalid())
5723     D.setInvalidType();
5724   else if (D.getCXXScopeSpec().isSet()) {
5725     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5726                                         UPPC_DeclarationQualifier))
5727       return nullptr;
5728 
5729     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5730     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5731     if (!DC || isa<EnumDecl>(DC)) {
5732       // If we could not compute the declaration context, it's because the
5733       // declaration context is dependent but does not refer to a class,
5734       // class template, or class template partial specialization. Complain
5735       // and return early, to avoid the coming semantic disaster.
5736       Diag(D.getIdentifierLoc(),
5737            diag::err_template_qualified_declarator_no_match)
5738         << D.getCXXScopeSpec().getScopeRep()
5739         << D.getCXXScopeSpec().getRange();
5740       return nullptr;
5741     }
5742     bool IsDependentContext = DC->isDependentContext();
5743 
5744     if (!IsDependentContext &&
5745         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5746       return nullptr;
5747 
5748     // If a class is incomplete, do not parse entities inside it.
5749     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5750       Diag(D.getIdentifierLoc(),
5751            diag::err_member_def_undefined_record)
5752         << Name << DC << D.getCXXScopeSpec().getRange();
5753       return nullptr;
5754     }
5755     if (!D.getDeclSpec().isFriendSpecified()) {
5756       if (diagnoseQualifiedDeclaration(
5757               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5758               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5759         if (DC->isRecord())
5760           return nullptr;
5761 
5762         D.setInvalidType();
5763       }
5764     }
5765 
5766     // Check whether we need to rebuild the type of the given
5767     // declaration in the current instantiation.
5768     if (EnteringContext && IsDependentContext &&
5769         TemplateParamLists.size() != 0) {
5770       ContextRAII SavedContext(*this, DC);
5771       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5772         D.setInvalidType();
5773     }
5774   }
5775 
5776   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5777   QualType R = TInfo->getType();
5778 
5779   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5780                                       UPPC_DeclarationType))
5781     D.setInvalidType();
5782 
5783   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5784                         forRedeclarationInCurContext());
5785 
5786   // See if this is a redefinition of a variable in the same scope.
5787   if (!D.getCXXScopeSpec().isSet()) {
5788     bool IsLinkageLookup = false;
5789     bool CreateBuiltins = false;
5790 
5791     // If the declaration we're planning to build will be a function
5792     // or object with linkage, then look for another declaration with
5793     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5794     //
5795     // If the declaration we're planning to build will be declared with
5796     // external linkage in the translation unit, create any builtin with
5797     // the same name.
5798     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5799       /* Do nothing*/;
5800     else if (CurContext->isFunctionOrMethod() &&
5801              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5802               R->isFunctionType())) {
5803       IsLinkageLookup = true;
5804       CreateBuiltins =
5805           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5806     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5807                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5808       CreateBuiltins = true;
5809 
5810     if (IsLinkageLookup) {
5811       Previous.clear(LookupRedeclarationWithLinkage);
5812       Previous.setRedeclarationKind(ForExternalRedeclaration);
5813     }
5814 
5815     LookupName(Previous, S, CreateBuiltins);
5816   } else { // Something like "int foo::x;"
5817     LookupQualifiedName(Previous, DC);
5818 
5819     // C++ [dcl.meaning]p1:
5820     //   When the declarator-id is qualified, the declaration shall refer to a
5821     //  previously declared member of the class or namespace to which the
5822     //  qualifier refers (or, in the case of a namespace, of an element of the
5823     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5824     //  thereof; [...]
5825     //
5826     // Note that we already checked the context above, and that we do not have
5827     // enough information to make sure that Previous contains the declaration
5828     // we want to match. For example, given:
5829     //
5830     //   class X {
5831     //     void f();
5832     //     void f(float);
5833     //   };
5834     //
5835     //   void X::f(int) { } // ill-formed
5836     //
5837     // In this case, Previous will point to the overload set
5838     // containing the two f's declared in X, but neither of them
5839     // matches.
5840 
5841     // C++ [dcl.meaning]p1:
5842     //   [...] the member shall not merely have been introduced by a
5843     //   using-declaration in the scope of the class or namespace nominated by
5844     //   the nested-name-specifier of the declarator-id.
5845     RemoveUsingDecls(Previous);
5846   }
5847 
5848   if (Previous.isSingleResult() &&
5849       Previous.getFoundDecl()->isTemplateParameter()) {
5850     // Maybe we will complain about the shadowed template parameter.
5851     if (!D.isInvalidType())
5852       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5853                                       Previous.getFoundDecl());
5854 
5855     // Just pretend that we didn't see the previous declaration.
5856     Previous.clear();
5857   }
5858 
5859   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5860     // Forget that the previous declaration is the injected-class-name.
5861     Previous.clear();
5862 
5863   // In C++, the previous declaration we find might be a tag type
5864   // (class or enum). In this case, the new declaration will hide the
5865   // tag type. Note that this applies to functions, function templates, and
5866   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5867   if (Previous.isSingleTagDecl() &&
5868       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5869       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5870     Previous.clear();
5871 
5872   // Check that there are no default arguments other than in the parameters
5873   // of a function declaration (C++ only).
5874   if (getLangOpts().CPlusPlus)
5875     CheckExtraCXXDefaultArguments(D);
5876 
5877   NamedDecl *New;
5878 
5879   bool AddToScope = true;
5880   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5881     if (TemplateParamLists.size()) {
5882       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5883       return nullptr;
5884     }
5885 
5886     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5887   } else if (R->isFunctionType()) {
5888     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5889                                   TemplateParamLists,
5890                                   AddToScope);
5891   } else {
5892     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5893                                   AddToScope);
5894   }
5895 
5896   if (!New)
5897     return nullptr;
5898 
5899   // If this has an identifier and is not a function template specialization,
5900   // add it to the scope stack.
5901   if (New->getDeclName() && AddToScope)
5902     PushOnScopeChains(New, S);
5903 
5904   if (isInOpenMPDeclareTargetContext())
5905     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5906 
5907   return New;
5908 }
5909 
5910 /// Helper method to turn variable array types into constant array
5911 /// types in certain situations which would otherwise be errors (for
5912 /// GCC compatibility).
5913 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5914                                                     ASTContext &Context,
5915                                                     bool &SizeIsNegative,
5916                                                     llvm::APSInt &Oversized) {
5917   // This method tries to turn a variable array into a constant
5918   // array even when the size isn't an ICE.  This is necessary
5919   // for compatibility with code that depends on gcc's buggy
5920   // constant expression folding, like struct {char x[(int)(char*)2];}
5921   SizeIsNegative = false;
5922   Oversized = 0;
5923 
5924   if (T->isDependentType())
5925     return QualType();
5926 
5927   QualifierCollector Qs;
5928   const Type *Ty = Qs.strip(T);
5929 
5930   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5931     QualType Pointee = PTy->getPointeeType();
5932     QualType FixedType =
5933         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5934                                             Oversized);
5935     if (FixedType.isNull()) return FixedType;
5936     FixedType = Context.getPointerType(FixedType);
5937     return Qs.apply(Context, FixedType);
5938   }
5939   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5940     QualType Inner = PTy->getInnerType();
5941     QualType FixedType =
5942         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5943                                             Oversized);
5944     if (FixedType.isNull()) return FixedType;
5945     FixedType = Context.getParenType(FixedType);
5946     return Qs.apply(Context, FixedType);
5947   }
5948 
5949   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5950   if (!VLATy)
5951     return QualType();
5952   // FIXME: We should probably handle this case
5953   if (VLATy->getElementType()->isVariablyModifiedType())
5954     return QualType();
5955 
5956   Expr::EvalResult Result;
5957   if (!VLATy->getSizeExpr() ||
5958       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5959     return QualType();
5960 
5961   llvm::APSInt Res = Result.Val.getInt();
5962 
5963   // Check whether the array size is negative.
5964   if (Res.isSigned() && Res.isNegative()) {
5965     SizeIsNegative = true;
5966     return QualType();
5967   }
5968 
5969   // Check whether the array is too large to be addressed.
5970   unsigned ActiveSizeBits
5971     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5972                                               Res);
5973   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5974     Oversized = Res;
5975     return QualType();
5976   }
5977 
5978   return Context.getConstantArrayType(
5979       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5980 }
5981 
5982 static void
5983 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5984   SrcTL = SrcTL.getUnqualifiedLoc();
5985   DstTL = DstTL.getUnqualifiedLoc();
5986   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5987     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5988     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5989                                       DstPTL.getPointeeLoc());
5990     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5991     return;
5992   }
5993   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5994     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5995     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5996                                       DstPTL.getInnerLoc());
5997     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5998     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5999     return;
6000   }
6001   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6002   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6003   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6004   TypeLoc DstElemTL = DstATL.getElementLoc();
6005   DstElemTL.initializeFullCopy(SrcElemTL);
6006   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6007   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6008   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6009 }
6010 
6011 /// Helper method to turn variable array types into constant array
6012 /// types in certain situations which would otherwise be errors (for
6013 /// GCC compatibility).
6014 static TypeSourceInfo*
6015 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6016                                               ASTContext &Context,
6017                                               bool &SizeIsNegative,
6018                                               llvm::APSInt &Oversized) {
6019   QualType FixedTy
6020     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6021                                           SizeIsNegative, Oversized);
6022   if (FixedTy.isNull())
6023     return nullptr;
6024   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6025   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6026                                     FixedTInfo->getTypeLoc());
6027   return FixedTInfo;
6028 }
6029 
6030 /// Register the given locally-scoped extern "C" declaration so
6031 /// that it can be found later for redeclarations. We include any extern "C"
6032 /// declaration that is not visible in the translation unit here, not just
6033 /// function-scope declarations.
6034 void
6035 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6036   if (!getLangOpts().CPlusPlus &&
6037       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6038     // Don't need to track declarations in the TU in C.
6039     return;
6040 
6041   // Note that we have a locally-scoped external with this name.
6042   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6043 }
6044 
6045 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6046   // FIXME: We can have multiple results via __attribute__((overloadable)).
6047   auto Result = Context.getExternCContextDecl()->lookup(Name);
6048   return Result.empty() ? nullptr : *Result.begin();
6049 }
6050 
6051 /// Diagnose function specifiers on a declaration of an identifier that
6052 /// does not identify a function.
6053 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6054   // FIXME: We should probably indicate the identifier in question to avoid
6055   // confusion for constructs like "virtual int a(), b;"
6056   if (DS.isVirtualSpecified())
6057     Diag(DS.getVirtualSpecLoc(),
6058          diag::err_virtual_non_function);
6059 
6060   if (DS.hasExplicitSpecifier())
6061     Diag(DS.getExplicitSpecLoc(),
6062          diag::err_explicit_non_function);
6063 
6064   if (DS.isNoreturnSpecified())
6065     Diag(DS.getNoreturnSpecLoc(),
6066          diag::err_noreturn_non_function);
6067 }
6068 
6069 NamedDecl*
6070 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6071                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6072   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6073   if (D.getCXXScopeSpec().isSet()) {
6074     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6075       << D.getCXXScopeSpec().getRange();
6076     D.setInvalidType();
6077     // Pretend we didn't see the scope specifier.
6078     DC = CurContext;
6079     Previous.clear();
6080   }
6081 
6082   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6083 
6084   if (D.getDeclSpec().isInlineSpecified())
6085     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6086         << getLangOpts().CPlusPlus17;
6087   if (D.getDeclSpec().hasConstexprSpecifier())
6088     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6089         << 1 << D.getDeclSpec().getConstexprSpecifier();
6090 
6091   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6092     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6093       Diag(D.getName().StartLocation,
6094            diag::err_deduction_guide_invalid_specifier)
6095           << "typedef";
6096     else
6097       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6098           << D.getName().getSourceRange();
6099     return nullptr;
6100   }
6101 
6102   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6103   if (!NewTD) return nullptr;
6104 
6105   // Handle attributes prior to checking for duplicates in MergeVarDecl
6106   ProcessDeclAttributes(S, NewTD, D);
6107 
6108   CheckTypedefForVariablyModifiedType(S, NewTD);
6109 
6110   bool Redeclaration = D.isRedeclaration();
6111   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6112   D.setRedeclaration(Redeclaration);
6113   return ND;
6114 }
6115 
6116 void
6117 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6118   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6119   // then it shall have block scope.
6120   // Note that variably modified types must be fixed before merging the decl so
6121   // that redeclarations will match.
6122   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6123   QualType T = TInfo->getType();
6124   if (T->isVariablyModifiedType()) {
6125     setFunctionHasBranchProtectedScope();
6126 
6127     if (S->getFnParent() == nullptr) {
6128       bool SizeIsNegative;
6129       llvm::APSInt Oversized;
6130       TypeSourceInfo *FixedTInfo =
6131         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6132                                                       SizeIsNegative,
6133                                                       Oversized);
6134       if (FixedTInfo) {
6135         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6136         NewTD->setTypeSourceInfo(FixedTInfo);
6137       } else {
6138         if (SizeIsNegative)
6139           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6140         else if (T->isVariableArrayType())
6141           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6142         else if (Oversized.getBoolValue())
6143           Diag(NewTD->getLocation(), diag::err_array_too_large)
6144             << Oversized.toString(10);
6145         else
6146           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6147         NewTD->setInvalidDecl();
6148       }
6149     }
6150   }
6151 }
6152 
6153 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6154 /// declares a typedef-name, either using the 'typedef' type specifier or via
6155 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6156 NamedDecl*
6157 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6158                            LookupResult &Previous, bool &Redeclaration) {
6159 
6160   // Find the shadowed declaration before filtering for scope.
6161   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6162 
6163   // Merge the decl with the existing one if appropriate. If the decl is
6164   // in an outer scope, it isn't the same thing.
6165   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6166                        /*AllowInlineNamespace*/false);
6167   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6168   if (!Previous.empty()) {
6169     Redeclaration = true;
6170     MergeTypedefNameDecl(S, NewTD, Previous);
6171   } else {
6172     inferGslPointerAttribute(NewTD);
6173   }
6174 
6175   if (ShadowedDecl && !Redeclaration)
6176     CheckShadow(NewTD, ShadowedDecl, Previous);
6177 
6178   // If this is the C FILE type, notify the AST context.
6179   if (IdentifierInfo *II = NewTD->getIdentifier())
6180     if (!NewTD->isInvalidDecl() &&
6181         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6182       if (II->isStr("FILE"))
6183         Context.setFILEDecl(NewTD);
6184       else if (II->isStr("jmp_buf"))
6185         Context.setjmp_bufDecl(NewTD);
6186       else if (II->isStr("sigjmp_buf"))
6187         Context.setsigjmp_bufDecl(NewTD);
6188       else if (II->isStr("ucontext_t"))
6189         Context.setucontext_tDecl(NewTD);
6190     }
6191 
6192   return NewTD;
6193 }
6194 
6195 /// Determines whether the given declaration is an out-of-scope
6196 /// previous declaration.
6197 ///
6198 /// This routine should be invoked when name lookup has found a
6199 /// previous declaration (PrevDecl) that is not in the scope where a
6200 /// new declaration by the same name is being introduced. If the new
6201 /// declaration occurs in a local scope, previous declarations with
6202 /// linkage may still be considered previous declarations (C99
6203 /// 6.2.2p4-5, C++ [basic.link]p6).
6204 ///
6205 /// \param PrevDecl the previous declaration found by name
6206 /// lookup
6207 ///
6208 /// \param DC the context in which the new declaration is being
6209 /// declared.
6210 ///
6211 /// \returns true if PrevDecl is an out-of-scope previous declaration
6212 /// for a new delcaration with the same name.
6213 static bool
6214 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6215                                 ASTContext &Context) {
6216   if (!PrevDecl)
6217     return false;
6218 
6219   if (!PrevDecl->hasLinkage())
6220     return false;
6221 
6222   if (Context.getLangOpts().CPlusPlus) {
6223     // C++ [basic.link]p6:
6224     //   If there is a visible declaration of an entity with linkage
6225     //   having the same name and type, ignoring entities declared
6226     //   outside the innermost enclosing namespace scope, the block
6227     //   scope declaration declares that same entity and receives the
6228     //   linkage of the previous declaration.
6229     DeclContext *OuterContext = DC->getRedeclContext();
6230     if (!OuterContext->isFunctionOrMethod())
6231       // This rule only applies to block-scope declarations.
6232       return false;
6233 
6234     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6235     if (PrevOuterContext->isRecord())
6236       // We found a member function: ignore it.
6237       return false;
6238 
6239     // Find the innermost enclosing namespace for the new and
6240     // previous declarations.
6241     OuterContext = OuterContext->getEnclosingNamespaceContext();
6242     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6243 
6244     // The previous declaration is in a different namespace, so it
6245     // isn't the same function.
6246     if (!OuterContext->Equals(PrevOuterContext))
6247       return false;
6248   }
6249 
6250   return true;
6251 }
6252 
6253 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6254   CXXScopeSpec &SS = D.getCXXScopeSpec();
6255   if (!SS.isSet()) return;
6256   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6257 }
6258 
6259 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6260   QualType type = decl->getType();
6261   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6262   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6263     // Various kinds of declaration aren't allowed to be __autoreleasing.
6264     unsigned kind = -1U;
6265     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6266       if (var->hasAttr<BlocksAttr>())
6267         kind = 0; // __block
6268       else if (!var->hasLocalStorage())
6269         kind = 1; // global
6270     } else if (isa<ObjCIvarDecl>(decl)) {
6271       kind = 3; // ivar
6272     } else if (isa<FieldDecl>(decl)) {
6273       kind = 2; // field
6274     }
6275 
6276     if (kind != -1U) {
6277       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6278         << kind;
6279     }
6280   } else if (lifetime == Qualifiers::OCL_None) {
6281     // Try to infer lifetime.
6282     if (!type->isObjCLifetimeType())
6283       return false;
6284 
6285     lifetime = type->getObjCARCImplicitLifetime();
6286     type = Context.getLifetimeQualifiedType(type, lifetime);
6287     decl->setType(type);
6288   }
6289 
6290   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6291     // Thread-local variables cannot have lifetime.
6292     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6293         var->getTLSKind()) {
6294       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6295         << var->getType();
6296       return true;
6297     }
6298   }
6299 
6300   return false;
6301 }
6302 
6303 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6304   if (Decl->getType().hasAddressSpace())
6305     return;
6306   if (Decl->getType()->isDependentType())
6307     return;
6308   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6309     QualType Type = Var->getType();
6310     if (Type->isSamplerT() || Type->isVoidType())
6311       return;
6312     LangAS ImplAS = LangAS::opencl_private;
6313     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6314         Var->hasGlobalStorage())
6315       ImplAS = LangAS::opencl_global;
6316     // If the original type from a decayed type is an array type and that array
6317     // type has no address space yet, deduce it now.
6318     if (auto DT = dyn_cast<DecayedType>(Type)) {
6319       auto OrigTy = DT->getOriginalType();
6320       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6321         // Add the address space to the original array type and then propagate
6322         // that to the element type through `getAsArrayType`.
6323         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6324         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6325         // Re-generate the decayed type.
6326         Type = Context.getDecayedType(OrigTy);
6327       }
6328     }
6329     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6330     // Apply any qualifiers (including address space) from the array type to
6331     // the element type. This implements C99 6.7.3p8: "If the specification of
6332     // an array type includes any type qualifiers, the element type is so
6333     // qualified, not the array type."
6334     if (Type->isArrayType())
6335       Type = QualType(Context.getAsArrayType(Type), 0);
6336     Decl->setType(Type);
6337   }
6338 }
6339 
6340 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6341   // Ensure that an auto decl is deduced otherwise the checks below might cache
6342   // the wrong linkage.
6343   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6344 
6345   // 'weak' only applies to declarations with external linkage.
6346   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6347     if (!ND.isExternallyVisible()) {
6348       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6349       ND.dropAttr<WeakAttr>();
6350     }
6351   }
6352   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6353     if (ND.isExternallyVisible()) {
6354       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6355       ND.dropAttr<WeakRefAttr>();
6356       ND.dropAttr<AliasAttr>();
6357     }
6358   }
6359 
6360   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6361     if (VD->hasInit()) {
6362       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6363         assert(VD->isThisDeclarationADefinition() &&
6364                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6365         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6366         VD->dropAttr<AliasAttr>();
6367       }
6368     }
6369   }
6370 
6371   // 'selectany' only applies to externally visible variable declarations.
6372   // It does not apply to functions.
6373   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6374     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6375       S.Diag(Attr->getLocation(),
6376              diag::err_attribute_selectany_non_extern_data);
6377       ND.dropAttr<SelectAnyAttr>();
6378     }
6379   }
6380 
6381   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6382     auto *VD = dyn_cast<VarDecl>(&ND);
6383     bool IsAnonymousNS = false;
6384     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6385     if (VD) {
6386       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6387       while (NS && !IsAnonymousNS) {
6388         IsAnonymousNS = NS->isAnonymousNamespace();
6389         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6390       }
6391     }
6392     // dll attributes require external linkage. Static locals may have external
6393     // linkage but still cannot be explicitly imported or exported.
6394     // In Microsoft mode, a variable defined in anonymous namespace must have
6395     // external linkage in order to be exported.
6396     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6397     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6398         (!AnonNSInMicrosoftMode &&
6399          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6400       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6401         << &ND << Attr;
6402       ND.setInvalidDecl();
6403     }
6404   }
6405 
6406   // Virtual functions cannot be marked as 'notail'.
6407   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6408     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6409       if (MD->isVirtual()) {
6410         S.Diag(ND.getLocation(),
6411                diag::err_invalid_attribute_on_virtual_function)
6412             << Attr;
6413         ND.dropAttr<NotTailCalledAttr>();
6414       }
6415 
6416   // Check the attributes on the function type, if any.
6417   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6418     // Don't declare this variable in the second operand of the for-statement;
6419     // GCC miscompiles that by ending its lifetime before evaluating the
6420     // third operand. See gcc.gnu.org/PR86769.
6421     AttributedTypeLoc ATL;
6422     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6423          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6424          TL = ATL.getModifiedLoc()) {
6425       // The [[lifetimebound]] attribute can be applied to the implicit object
6426       // parameter of a non-static member function (other than a ctor or dtor)
6427       // by applying it to the function type.
6428       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6429         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6430         if (!MD || MD->isStatic()) {
6431           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6432               << !MD << A->getRange();
6433         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6434           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6435               << isa<CXXDestructorDecl>(MD) << A->getRange();
6436         }
6437       }
6438     }
6439   }
6440 }
6441 
6442 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6443                                            NamedDecl *NewDecl,
6444                                            bool IsSpecialization,
6445                                            bool IsDefinition) {
6446   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6447     return;
6448 
6449   bool IsTemplate = false;
6450   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6451     OldDecl = OldTD->getTemplatedDecl();
6452     IsTemplate = true;
6453     if (!IsSpecialization)
6454       IsDefinition = false;
6455   }
6456   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6457     NewDecl = NewTD->getTemplatedDecl();
6458     IsTemplate = true;
6459   }
6460 
6461   if (!OldDecl || !NewDecl)
6462     return;
6463 
6464   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6465   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6466   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6467   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6468 
6469   // dllimport and dllexport are inheritable attributes so we have to exclude
6470   // inherited attribute instances.
6471   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6472                     (NewExportAttr && !NewExportAttr->isInherited());
6473 
6474   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6475   // the only exception being explicit specializations.
6476   // Implicitly generated declarations are also excluded for now because there
6477   // is no other way to switch these to use dllimport or dllexport.
6478   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6479 
6480   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6481     // Allow with a warning for free functions and global variables.
6482     bool JustWarn = false;
6483     if (!OldDecl->isCXXClassMember()) {
6484       auto *VD = dyn_cast<VarDecl>(OldDecl);
6485       if (VD && !VD->getDescribedVarTemplate())
6486         JustWarn = true;
6487       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6488       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6489         JustWarn = true;
6490     }
6491 
6492     // We cannot change a declaration that's been used because IR has already
6493     // been emitted. Dllimported functions will still work though (modulo
6494     // address equality) as they can use the thunk.
6495     if (OldDecl->isUsed())
6496       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6497         JustWarn = false;
6498 
6499     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6500                                : diag::err_attribute_dll_redeclaration;
6501     S.Diag(NewDecl->getLocation(), DiagID)
6502         << NewDecl
6503         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6504     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6505     if (!JustWarn) {
6506       NewDecl->setInvalidDecl();
6507       return;
6508     }
6509   }
6510 
6511   // A redeclaration is not allowed to drop a dllimport attribute, the only
6512   // exceptions being inline function definitions (except for function
6513   // templates), local extern declarations, qualified friend declarations or
6514   // special MSVC extension: in the last case, the declaration is treated as if
6515   // it were marked dllexport.
6516   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6517   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6518   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6519     // Ignore static data because out-of-line definitions are diagnosed
6520     // separately.
6521     IsStaticDataMember = VD->isStaticDataMember();
6522     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6523                    VarDecl::DeclarationOnly;
6524   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6525     IsInline = FD->isInlined();
6526     IsQualifiedFriend = FD->getQualifier() &&
6527                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6528   }
6529 
6530   if (OldImportAttr && !HasNewAttr &&
6531       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6532       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6533     if (IsMicrosoft && IsDefinition) {
6534       S.Diag(NewDecl->getLocation(),
6535              diag::warn_redeclaration_without_import_attribute)
6536           << NewDecl;
6537       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6538       NewDecl->dropAttr<DLLImportAttr>();
6539       NewDecl->addAttr(
6540           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6541     } else {
6542       S.Diag(NewDecl->getLocation(),
6543              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6544           << NewDecl << OldImportAttr;
6545       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6546       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6547       OldDecl->dropAttr<DLLImportAttr>();
6548       NewDecl->dropAttr<DLLImportAttr>();
6549     }
6550   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6551     // In MinGW, seeing a function declared inline drops the dllimport
6552     // attribute.
6553     OldDecl->dropAttr<DLLImportAttr>();
6554     NewDecl->dropAttr<DLLImportAttr>();
6555     S.Diag(NewDecl->getLocation(),
6556            diag::warn_dllimport_dropped_from_inline_function)
6557         << NewDecl << OldImportAttr;
6558   }
6559 
6560   // A specialization of a class template member function is processed here
6561   // since it's a redeclaration. If the parent class is dllexport, the
6562   // specialization inherits that attribute. This doesn't happen automatically
6563   // since the parent class isn't instantiated until later.
6564   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6565     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6566         !NewImportAttr && !NewExportAttr) {
6567       if (const DLLExportAttr *ParentExportAttr =
6568               MD->getParent()->getAttr<DLLExportAttr>()) {
6569         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6570         NewAttr->setInherited(true);
6571         NewDecl->addAttr(NewAttr);
6572       }
6573     }
6574   }
6575 }
6576 
6577 /// Given that we are within the definition of the given function,
6578 /// will that definition behave like C99's 'inline', where the
6579 /// definition is discarded except for optimization purposes?
6580 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6581   // Try to avoid calling GetGVALinkageForFunction.
6582 
6583   // All cases of this require the 'inline' keyword.
6584   if (!FD->isInlined()) return false;
6585 
6586   // This is only possible in C++ with the gnu_inline attribute.
6587   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6588     return false;
6589 
6590   // Okay, go ahead and call the relatively-more-expensive function.
6591   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6592 }
6593 
6594 /// Determine whether a variable is extern "C" prior to attaching
6595 /// an initializer. We can't just call isExternC() here, because that
6596 /// will also compute and cache whether the declaration is externally
6597 /// visible, which might change when we attach the initializer.
6598 ///
6599 /// This can only be used if the declaration is known to not be a
6600 /// redeclaration of an internal linkage declaration.
6601 ///
6602 /// For instance:
6603 ///
6604 ///   auto x = []{};
6605 ///
6606 /// Attaching the initializer here makes this declaration not externally
6607 /// visible, because its type has internal linkage.
6608 ///
6609 /// FIXME: This is a hack.
6610 template<typename T>
6611 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6612   if (S.getLangOpts().CPlusPlus) {
6613     // In C++, the overloadable attribute negates the effects of extern "C".
6614     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6615       return false;
6616 
6617     // So do CUDA's host/device attributes.
6618     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6619                                  D->template hasAttr<CUDAHostAttr>()))
6620       return false;
6621   }
6622   return D->isExternC();
6623 }
6624 
6625 static bool shouldConsiderLinkage(const VarDecl *VD) {
6626   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6627   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6628       isa<OMPDeclareMapperDecl>(DC))
6629     return VD->hasExternalStorage();
6630   if (DC->isFileContext())
6631     return true;
6632   if (DC->isRecord())
6633     return false;
6634   if (isa<RequiresExprBodyDecl>(DC))
6635     return false;
6636   llvm_unreachable("Unexpected context");
6637 }
6638 
6639 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6640   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6641   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6642       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6643     return true;
6644   if (DC->isRecord())
6645     return false;
6646   llvm_unreachable("Unexpected context");
6647 }
6648 
6649 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6650                           ParsedAttr::Kind Kind) {
6651   // Check decl attributes on the DeclSpec.
6652   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6653     return true;
6654 
6655   // Walk the declarator structure, checking decl attributes that were in a type
6656   // position to the decl itself.
6657   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6658     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6659       return true;
6660   }
6661 
6662   // Finally, check attributes on the decl itself.
6663   return PD.getAttributes().hasAttribute(Kind);
6664 }
6665 
6666 /// Adjust the \c DeclContext for a function or variable that might be a
6667 /// function-local external declaration.
6668 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6669   if (!DC->isFunctionOrMethod())
6670     return false;
6671 
6672   // If this is a local extern function or variable declared within a function
6673   // template, don't add it into the enclosing namespace scope until it is
6674   // instantiated; it might have a dependent type right now.
6675   if (DC->isDependentContext())
6676     return true;
6677 
6678   // C++11 [basic.link]p7:
6679   //   When a block scope declaration of an entity with linkage is not found to
6680   //   refer to some other declaration, then that entity is a member of the
6681   //   innermost enclosing namespace.
6682   //
6683   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6684   // semantically-enclosing namespace, not a lexically-enclosing one.
6685   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6686     DC = DC->getParent();
6687   return true;
6688 }
6689 
6690 /// Returns true if given declaration has external C language linkage.
6691 static bool isDeclExternC(const Decl *D) {
6692   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6693     return FD->isExternC();
6694   if (const auto *VD = dyn_cast<VarDecl>(D))
6695     return VD->isExternC();
6696 
6697   llvm_unreachable("Unknown type of decl!");
6698 }
6699 /// Returns true if there hasn't been any invalid type diagnosed.
6700 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6701                                 DeclContext *DC, QualType R) {
6702   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6703   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6704   // argument.
6705   if (R->isImageType() || R->isPipeType()) {
6706     Se.Diag(D.getIdentifierLoc(),
6707             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6708         << R;
6709     D.setInvalidType();
6710     return false;
6711   }
6712 
6713   // OpenCL v1.2 s6.9.r:
6714   // The event type cannot be used to declare a program scope variable.
6715   // OpenCL v2.0 s6.9.q:
6716   // The clk_event_t and reserve_id_t types cannot be declared in program
6717   // scope.
6718   if (NULL == S->getParent()) {
6719     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6720       Se.Diag(D.getIdentifierLoc(),
6721               diag::err_invalid_type_for_program_scope_var)
6722           << R;
6723       D.setInvalidType();
6724       return false;
6725     }
6726   }
6727 
6728   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6729   QualType NR = R;
6730   while (NR->isPointerType()) {
6731     if (NR->isFunctionPointerType()) {
6732       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6733       D.setInvalidType();
6734       return false;
6735     }
6736     NR = NR->getPointeeType();
6737   }
6738 
6739   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6740     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6741     // half array type (unless the cl_khr_fp16 extension is enabled).
6742     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6743       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6744       D.setInvalidType();
6745       return false;
6746     }
6747   }
6748 
6749   // OpenCL v1.2 s6.9.r:
6750   // The event type cannot be used with the __local, __constant and __global
6751   // address space qualifiers.
6752   if (R->isEventT()) {
6753     if (R.getAddressSpace() != LangAS::opencl_private) {
6754       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6755       D.setInvalidType();
6756       return false;
6757     }
6758   }
6759 
6760   // C++ for OpenCL does not allow the thread_local storage qualifier.
6761   // OpenCL C does not support thread_local either, and
6762   // also reject all other thread storage class specifiers.
6763   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6764   if (TSC != TSCS_unspecified) {
6765     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6766     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6767             diag::err_opencl_unknown_type_specifier)
6768         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6769         << DeclSpec::getSpecifierName(TSC) << 1;
6770     D.setInvalidType();
6771     return false;
6772   }
6773 
6774   if (R->isSamplerT()) {
6775     // OpenCL v1.2 s6.9.b p4:
6776     // The sampler type cannot be used with the __local and __global address
6777     // space qualifiers.
6778     if (R.getAddressSpace() == LangAS::opencl_local ||
6779         R.getAddressSpace() == LangAS::opencl_global) {
6780       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6781       D.setInvalidType();
6782     }
6783 
6784     // OpenCL v1.2 s6.12.14.1:
6785     // A global sampler must be declared with either the constant address
6786     // space qualifier or with the const qualifier.
6787     if (DC->isTranslationUnit() &&
6788         !(R.getAddressSpace() == LangAS::opencl_constant ||
6789           R.isConstQualified())) {
6790       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6791       D.setInvalidType();
6792     }
6793     if (D.isInvalidType())
6794       return false;
6795   }
6796   return true;
6797 }
6798 
6799 NamedDecl *Sema::ActOnVariableDeclarator(
6800     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6801     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6802     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6803   QualType R = TInfo->getType();
6804   DeclarationName Name = GetNameForDeclarator(D).getName();
6805 
6806   IdentifierInfo *II = Name.getAsIdentifierInfo();
6807 
6808   if (D.isDecompositionDeclarator()) {
6809     // Take the name of the first declarator as our name for diagnostic
6810     // purposes.
6811     auto &Decomp = D.getDecompositionDeclarator();
6812     if (!Decomp.bindings().empty()) {
6813       II = Decomp.bindings()[0].Name;
6814       Name = II;
6815     }
6816   } else if (!II) {
6817     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6818     return nullptr;
6819   }
6820 
6821 
6822   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6823   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6824 
6825   // dllimport globals without explicit storage class are treated as extern. We
6826   // have to change the storage class this early to get the right DeclContext.
6827   if (SC == SC_None && !DC->isRecord() &&
6828       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6829       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6830     SC = SC_Extern;
6831 
6832   DeclContext *OriginalDC = DC;
6833   bool IsLocalExternDecl = SC == SC_Extern &&
6834                            adjustContextForLocalExternDecl(DC);
6835 
6836   if (SCSpec == DeclSpec::SCS_mutable) {
6837     // mutable can only appear on non-static class members, so it's always
6838     // an error here
6839     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6840     D.setInvalidType();
6841     SC = SC_None;
6842   }
6843 
6844   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6845       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6846                               D.getDeclSpec().getStorageClassSpecLoc())) {
6847     // In C++11, the 'register' storage class specifier is deprecated.
6848     // Suppress the warning in system macros, it's used in macros in some
6849     // popular C system headers, such as in glibc's htonl() macro.
6850     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6851          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6852                                    : diag::warn_deprecated_register)
6853       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6854   }
6855 
6856   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6857 
6858   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6859     // C99 6.9p2: The storage-class specifiers auto and register shall not
6860     // appear in the declaration specifiers in an external declaration.
6861     // Global Register+Asm is a GNU extension we support.
6862     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6863       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6864       D.setInvalidType();
6865     }
6866   }
6867 
6868   bool IsMemberSpecialization = false;
6869   bool IsVariableTemplateSpecialization = false;
6870   bool IsPartialSpecialization = false;
6871   bool IsVariableTemplate = false;
6872   VarDecl *NewVD = nullptr;
6873   VarTemplateDecl *NewTemplate = nullptr;
6874   TemplateParameterList *TemplateParams = nullptr;
6875   if (!getLangOpts().CPlusPlus) {
6876     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6877                             II, R, TInfo, SC);
6878 
6879     if (R->getContainedDeducedType())
6880       ParsingInitForAutoVars.insert(NewVD);
6881 
6882     if (D.isInvalidType())
6883       NewVD->setInvalidDecl();
6884 
6885     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6886         NewVD->hasLocalStorage())
6887       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6888                             NTCUC_AutoVar, NTCUK_Destruct);
6889   } else {
6890     bool Invalid = false;
6891 
6892     if (DC->isRecord() && !CurContext->isRecord()) {
6893       // This is an out-of-line definition of a static data member.
6894       switch (SC) {
6895       case SC_None:
6896         break;
6897       case SC_Static:
6898         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6899              diag::err_static_out_of_line)
6900           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6901         break;
6902       case SC_Auto:
6903       case SC_Register:
6904       case SC_Extern:
6905         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6906         // to names of variables declared in a block or to function parameters.
6907         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6908         // of class members
6909 
6910         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6911              diag::err_storage_class_for_static_member)
6912           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6913         break;
6914       case SC_PrivateExtern:
6915         llvm_unreachable("C storage class in c++!");
6916       }
6917     }
6918 
6919     if (SC == SC_Static && CurContext->isRecord()) {
6920       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6921         // Walk up the enclosing DeclContexts to check for any that are
6922         // incompatible with static data members.
6923         const DeclContext *FunctionOrMethod = nullptr;
6924         const CXXRecordDecl *AnonStruct = nullptr;
6925         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6926           if (Ctxt->isFunctionOrMethod()) {
6927             FunctionOrMethod = Ctxt;
6928             break;
6929           }
6930           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6931           if (ParentDecl && !ParentDecl->getDeclName()) {
6932             AnonStruct = ParentDecl;
6933             break;
6934           }
6935         }
6936         if (FunctionOrMethod) {
6937           // C++ [class.static.data]p5: A local class shall not have static data
6938           // members.
6939           Diag(D.getIdentifierLoc(),
6940                diag::err_static_data_member_not_allowed_in_local_class)
6941             << Name << RD->getDeclName() << RD->getTagKind();
6942         } else if (AnonStruct) {
6943           // C++ [class.static.data]p4: Unnamed classes and classes contained
6944           // directly or indirectly within unnamed classes shall not contain
6945           // static data members.
6946           Diag(D.getIdentifierLoc(),
6947                diag::err_static_data_member_not_allowed_in_anon_struct)
6948             << Name << AnonStruct->getTagKind();
6949           Invalid = true;
6950         } else if (RD->isUnion()) {
6951           // C++98 [class.union]p1: If a union contains a static data member,
6952           // the program is ill-formed. C++11 drops this restriction.
6953           Diag(D.getIdentifierLoc(),
6954                getLangOpts().CPlusPlus11
6955                  ? diag::warn_cxx98_compat_static_data_member_in_union
6956                  : diag::ext_static_data_member_in_union) << Name;
6957         }
6958       }
6959     }
6960 
6961     // Match up the template parameter lists with the scope specifier, then
6962     // determine whether we have a template or a template specialization.
6963     bool InvalidScope = false;
6964     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6965         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6966         D.getCXXScopeSpec(),
6967         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6968             ? D.getName().TemplateId
6969             : nullptr,
6970         TemplateParamLists,
6971         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6972     Invalid |= InvalidScope;
6973 
6974     if (TemplateParams) {
6975       if (!TemplateParams->size() &&
6976           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6977         // There is an extraneous 'template<>' for this variable. Complain
6978         // about it, but allow the declaration of the variable.
6979         Diag(TemplateParams->getTemplateLoc(),
6980              diag::err_template_variable_noparams)
6981           << II
6982           << SourceRange(TemplateParams->getTemplateLoc(),
6983                          TemplateParams->getRAngleLoc());
6984         TemplateParams = nullptr;
6985       } else {
6986         // Check that we can declare a template here.
6987         if (CheckTemplateDeclScope(S, TemplateParams))
6988           return nullptr;
6989 
6990         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6991           // This is an explicit specialization or a partial specialization.
6992           IsVariableTemplateSpecialization = true;
6993           IsPartialSpecialization = TemplateParams->size() > 0;
6994         } else { // if (TemplateParams->size() > 0)
6995           // This is a template declaration.
6996           IsVariableTemplate = true;
6997 
6998           // Only C++1y supports variable templates (N3651).
6999           Diag(D.getIdentifierLoc(),
7000                getLangOpts().CPlusPlus14
7001                    ? diag::warn_cxx11_compat_variable_template
7002                    : diag::ext_variable_template);
7003         }
7004       }
7005     } else {
7006       // Check that we can declare a member specialization here.
7007       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7008           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7009         return nullptr;
7010       assert((Invalid ||
7011               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7012              "should have a 'template<>' for this decl");
7013     }
7014 
7015     if (IsVariableTemplateSpecialization) {
7016       SourceLocation TemplateKWLoc =
7017           TemplateParamLists.size() > 0
7018               ? TemplateParamLists[0]->getTemplateLoc()
7019               : SourceLocation();
7020       DeclResult Res = ActOnVarTemplateSpecialization(
7021           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7022           IsPartialSpecialization);
7023       if (Res.isInvalid())
7024         return nullptr;
7025       NewVD = cast<VarDecl>(Res.get());
7026       AddToScope = false;
7027     } else if (D.isDecompositionDeclarator()) {
7028       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7029                                         D.getIdentifierLoc(), R, TInfo, SC,
7030                                         Bindings);
7031     } else
7032       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7033                               D.getIdentifierLoc(), II, R, TInfo, SC);
7034 
7035     // If this is supposed to be a variable template, create it as such.
7036     if (IsVariableTemplate) {
7037       NewTemplate =
7038           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7039                                   TemplateParams, NewVD);
7040       NewVD->setDescribedVarTemplate(NewTemplate);
7041     }
7042 
7043     // If this decl has an auto type in need of deduction, make a note of the
7044     // Decl so we can diagnose uses of it in its own initializer.
7045     if (R->getContainedDeducedType())
7046       ParsingInitForAutoVars.insert(NewVD);
7047 
7048     if (D.isInvalidType() || Invalid) {
7049       NewVD->setInvalidDecl();
7050       if (NewTemplate)
7051         NewTemplate->setInvalidDecl();
7052     }
7053 
7054     SetNestedNameSpecifier(*this, NewVD, D);
7055 
7056     // If we have any template parameter lists that don't directly belong to
7057     // the variable (matching the scope specifier), store them.
7058     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7059     if (TemplateParamLists.size() > VDTemplateParamLists)
7060       NewVD->setTemplateParameterListsInfo(
7061           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7062   }
7063 
7064   if (D.getDeclSpec().isInlineSpecified()) {
7065     if (!getLangOpts().CPlusPlus) {
7066       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7067           << 0;
7068     } else if (CurContext->isFunctionOrMethod()) {
7069       // 'inline' is not allowed on block scope variable declaration.
7070       Diag(D.getDeclSpec().getInlineSpecLoc(),
7071            diag::err_inline_declaration_block_scope) << Name
7072         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7073     } else {
7074       Diag(D.getDeclSpec().getInlineSpecLoc(),
7075            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7076                                      : diag::ext_inline_variable);
7077       NewVD->setInlineSpecified();
7078     }
7079   }
7080 
7081   // Set the lexical context. If the declarator has a C++ scope specifier, the
7082   // lexical context will be different from the semantic context.
7083   NewVD->setLexicalDeclContext(CurContext);
7084   if (NewTemplate)
7085     NewTemplate->setLexicalDeclContext(CurContext);
7086 
7087   if (IsLocalExternDecl) {
7088     if (D.isDecompositionDeclarator())
7089       for (auto *B : Bindings)
7090         B->setLocalExternDecl();
7091     else
7092       NewVD->setLocalExternDecl();
7093   }
7094 
7095   bool EmitTLSUnsupportedError = false;
7096   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7097     // C++11 [dcl.stc]p4:
7098     //   When thread_local is applied to a variable of block scope the
7099     //   storage-class-specifier static is implied if it does not appear
7100     //   explicitly.
7101     // Core issue: 'static' is not implied if the variable is declared
7102     //   'extern'.
7103     if (NewVD->hasLocalStorage() &&
7104         (SCSpec != DeclSpec::SCS_unspecified ||
7105          TSCS != DeclSpec::TSCS_thread_local ||
7106          !DC->isFunctionOrMethod()))
7107       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7108            diag::err_thread_non_global)
7109         << DeclSpec::getSpecifierName(TSCS);
7110     else if (!Context.getTargetInfo().isTLSSupported()) {
7111       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7112           getLangOpts().SYCLIsDevice) {
7113         // Postpone error emission until we've collected attributes required to
7114         // figure out whether it's a host or device variable and whether the
7115         // error should be ignored.
7116         EmitTLSUnsupportedError = true;
7117         // We still need to mark the variable as TLS so it shows up in AST with
7118         // proper storage class for other tools to use even if we're not going
7119         // to emit any code for it.
7120         NewVD->setTSCSpec(TSCS);
7121       } else
7122         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7123              diag::err_thread_unsupported);
7124     } else
7125       NewVD->setTSCSpec(TSCS);
7126   }
7127 
7128   switch (D.getDeclSpec().getConstexprSpecifier()) {
7129   case CSK_unspecified:
7130     break;
7131 
7132   case CSK_consteval:
7133     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7134         diag::err_constexpr_wrong_decl_kind)
7135       << D.getDeclSpec().getConstexprSpecifier();
7136     LLVM_FALLTHROUGH;
7137 
7138   case CSK_constexpr:
7139     NewVD->setConstexpr(true);
7140     MaybeAddCUDAConstantAttr(NewVD);
7141     // C++1z [dcl.spec.constexpr]p1:
7142     //   A static data member declared with the constexpr specifier is
7143     //   implicitly an inline variable.
7144     if (NewVD->isStaticDataMember() &&
7145         (getLangOpts().CPlusPlus17 ||
7146          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7147       NewVD->setImplicitlyInline();
7148     break;
7149 
7150   case CSK_constinit:
7151     if (!NewVD->hasGlobalStorage())
7152       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7153            diag::err_constinit_local_variable);
7154     else
7155       NewVD->addAttr(ConstInitAttr::Create(
7156           Context, D.getDeclSpec().getConstexprSpecLoc(),
7157           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7158     break;
7159   }
7160 
7161   // C99 6.7.4p3
7162   //   An inline definition of a function with external linkage shall
7163   //   not contain a definition of a modifiable object with static or
7164   //   thread storage duration...
7165   // We only apply this when the function is required to be defined
7166   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7167   // that a local variable with thread storage duration still has to
7168   // be marked 'static'.  Also note that it's possible to get these
7169   // semantics in C++ using __attribute__((gnu_inline)).
7170   if (SC == SC_Static && S->getFnParent() != nullptr &&
7171       !NewVD->getType().isConstQualified()) {
7172     FunctionDecl *CurFD = getCurFunctionDecl();
7173     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7174       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7175            diag::warn_static_local_in_extern_inline);
7176       MaybeSuggestAddingStaticToDecl(CurFD);
7177     }
7178   }
7179 
7180   if (D.getDeclSpec().isModulePrivateSpecified()) {
7181     if (IsVariableTemplateSpecialization)
7182       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7183           << (IsPartialSpecialization ? 1 : 0)
7184           << FixItHint::CreateRemoval(
7185                  D.getDeclSpec().getModulePrivateSpecLoc());
7186     else if (IsMemberSpecialization)
7187       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7188         << 2
7189         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7190     else if (NewVD->hasLocalStorage())
7191       Diag(NewVD->getLocation(), diag::err_module_private_local)
7192           << 0 << NewVD
7193           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7194           << FixItHint::CreateRemoval(
7195                  D.getDeclSpec().getModulePrivateSpecLoc());
7196     else {
7197       NewVD->setModulePrivate();
7198       if (NewTemplate)
7199         NewTemplate->setModulePrivate();
7200       for (auto *B : Bindings)
7201         B->setModulePrivate();
7202     }
7203   }
7204 
7205   if (getLangOpts().OpenCL) {
7206 
7207     deduceOpenCLAddressSpace(NewVD);
7208 
7209     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7210   }
7211 
7212   // Handle attributes prior to checking for duplicates in MergeVarDecl
7213   ProcessDeclAttributes(S, NewVD, D);
7214 
7215   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7216       getLangOpts().SYCLIsDevice) {
7217     if (EmitTLSUnsupportedError &&
7218         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7219          (getLangOpts().OpenMPIsDevice &&
7220           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7221       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7222            diag::err_thread_unsupported);
7223 
7224     if (EmitTLSUnsupportedError &&
7225         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7226       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7227     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7228     // storage [duration]."
7229     if (SC == SC_None && S->getFnParent() != nullptr &&
7230         (NewVD->hasAttr<CUDASharedAttr>() ||
7231          NewVD->hasAttr<CUDAConstantAttr>())) {
7232       NewVD->setStorageClass(SC_Static);
7233     }
7234   }
7235 
7236   // Ensure that dllimport globals without explicit storage class are treated as
7237   // extern. The storage class is set above using parsed attributes. Now we can
7238   // check the VarDecl itself.
7239   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7240          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7241          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7242 
7243   // In auto-retain/release, infer strong retension for variables of
7244   // retainable type.
7245   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7246     NewVD->setInvalidDecl();
7247 
7248   // Handle GNU asm-label extension (encoded as an attribute).
7249   if (Expr *E = (Expr*)D.getAsmLabel()) {
7250     // The parser guarantees this is a string.
7251     StringLiteral *SE = cast<StringLiteral>(E);
7252     StringRef Label = SE->getString();
7253     if (S->getFnParent() != nullptr) {
7254       switch (SC) {
7255       case SC_None:
7256       case SC_Auto:
7257         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7258         break;
7259       case SC_Register:
7260         // Local Named register
7261         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7262             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7263           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7264         break;
7265       case SC_Static:
7266       case SC_Extern:
7267       case SC_PrivateExtern:
7268         break;
7269       }
7270     } else if (SC == SC_Register) {
7271       // Global Named register
7272       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7273         const auto &TI = Context.getTargetInfo();
7274         bool HasSizeMismatch;
7275 
7276         if (!TI.isValidGCCRegisterName(Label))
7277           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7278         else if (!TI.validateGlobalRegisterVariable(Label,
7279                                                     Context.getTypeSize(R),
7280                                                     HasSizeMismatch))
7281           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7282         else if (HasSizeMismatch)
7283           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7284       }
7285 
7286       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7287         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7288         NewVD->setInvalidDecl(true);
7289       }
7290     }
7291 
7292     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7293                                         /*IsLiteralLabel=*/true,
7294                                         SE->getStrTokenLoc(0)));
7295   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7296     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7297       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7298     if (I != ExtnameUndeclaredIdentifiers.end()) {
7299       if (isDeclExternC(NewVD)) {
7300         NewVD->addAttr(I->second);
7301         ExtnameUndeclaredIdentifiers.erase(I);
7302       } else
7303         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7304             << /*Variable*/1 << NewVD;
7305     }
7306   }
7307 
7308   // Find the shadowed declaration before filtering for scope.
7309   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7310                                 ? getShadowedDeclaration(NewVD, Previous)
7311                                 : nullptr;
7312 
7313   // Don't consider existing declarations that are in a different
7314   // scope and are out-of-semantic-context declarations (if the new
7315   // declaration has linkage).
7316   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7317                        D.getCXXScopeSpec().isNotEmpty() ||
7318                        IsMemberSpecialization ||
7319                        IsVariableTemplateSpecialization);
7320 
7321   // Check whether the previous declaration is in the same block scope. This
7322   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7323   if (getLangOpts().CPlusPlus &&
7324       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7325     NewVD->setPreviousDeclInSameBlockScope(
7326         Previous.isSingleResult() && !Previous.isShadowed() &&
7327         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7328 
7329   if (!getLangOpts().CPlusPlus) {
7330     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7331   } else {
7332     // If this is an explicit specialization of a static data member, check it.
7333     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7334         CheckMemberSpecialization(NewVD, Previous))
7335       NewVD->setInvalidDecl();
7336 
7337     // Merge the decl with the existing one if appropriate.
7338     if (!Previous.empty()) {
7339       if (Previous.isSingleResult() &&
7340           isa<FieldDecl>(Previous.getFoundDecl()) &&
7341           D.getCXXScopeSpec().isSet()) {
7342         // The user tried to define a non-static data member
7343         // out-of-line (C++ [dcl.meaning]p1).
7344         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7345           << D.getCXXScopeSpec().getRange();
7346         Previous.clear();
7347         NewVD->setInvalidDecl();
7348       }
7349     } else if (D.getCXXScopeSpec().isSet()) {
7350       // No previous declaration in the qualifying scope.
7351       Diag(D.getIdentifierLoc(), diag::err_no_member)
7352         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7353         << D.getCXXScopeSpec().getRange();
7354       NewVD->setInvalidDecl();
7355     }
7356 
7357     if (!IsVariableTemplateSpecialization)
7358       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7359 
7360     if (NewTemplate) {
7361       VarTemplateDecl *PrevVarTemplate =
7362           NewVD->getPreviousDecl()
7363               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7364               : nullptr;
7365 
7366       // Check the template parameter list of this declaration, possibly
7367       // merging in the template parameter list from the previous variable
7368       // template declaration.
7369       if (CheckTemplateParameterList(
7370               TemplateParams,
7371               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7372                               : nullptr,
7373               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7374                DC->isDependentContext())
7375                   ? TPC_ClassTemplateMember
7376                   : TPC_VarTemplate))
7377         NewVD->setInvalidDecl();
7378 
7379       // If we are providing an explicit specialization of a static variable
7380       // template, make a note of that.
7381       if (PrevVarTemplate &&
7382           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7383         PrevVarTemplate->setMemberSpecialization();
7384     }
7385   }
7386 
7387   // Diagnose shadowed variables iff this isn't a redeclaration.
7388   if (ShadowedDecl && !D.isRedeclaration())
7389     CheckShadow(NewVD, ShadowedDecl, Previous);
7390 
7391   ProcessPragmaWeak(S, NewVD);
7392 
7393   // If this is the first declaration of an extern C variable, update
7394   // the map of such variables.
7395   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7396       isIncompleteDeclExternC(*this, NewVD))
7397     RegisterLocallyScopedExternCDecl(NewVD, S);
7398 
7399   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7400     MangleNumberingContext *MCtx;
7401     Decl *ManglingContextDecl;
7402     std::tie(MCtx, ManglingContextDecl) =
7403         getCurrentMangleNumberContext(NewVD->getDeclContext());
7404     if (MCtx) {
7405       Context.setManglingNumber(
7406           NewVD, MCtx->getManglingNumber(
7407                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7408       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7409     }
7410   }
7411 
7412   // Special handling of variable named 'main'.
7413   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7414       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7415       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7416 
7417     // C++ [basic.start.main]p3
7418     // A program that declares a variable main at global scope is ill-formed.
7419     if (getLangOpts().CPlusPlus)
7420       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7421 
7422     // In C, and external-linkage variable named main results in undefined
7423     // behavior.
7424     else if (NewVD->hasExternalFormalLinkage())
7425       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7426   }
7427 
7428   if (D.isRedeclaration() && !Previous.empty()) {
7429     NamedDecl *Prev = Previous.getRepresentativeDecl();
7430     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7431                                    D.isFunctionDefinition());
7432   }
7433 
7434   if (NewTemplate) {
7435     if (NewVD->isInvalidDecl())
7436       NewTemplate->setInvalidDecl();
7437     ActOnDocumentableDecl(NewTemplate);
7438     return NewTemplate;
7439   }
7440 
7441   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7442     CompleteMemberSpecialization(NewVD, Previous);
7443 
7444   return NewVD;
7445 }
7446 
7447 /// Enum describing the %select options in diag::warn_decl_shadow.
7448 enum ShadowedDeclKind {
7449   SDK_Local,
7450   SDK_Global,
7451   SDK_StaticMember,
7452   SDK_Field,
7453   SDK_Typedef,
7454   SDK_Using
7455 };
7456 
7457 /// Determine what kind of declaration we're shadowing.
7458 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7459                                                 const DeclContext *OldDC) {
7460   if (isa<TypeAliasDecl>(ShadowedDecl))
7461     return SDK_Using;
7462   else if (isa<TypedefDecl>(ShadowedDecl))
7463     return SDK_Typedef;
7464   else if (isa<RecordDecl>(OldDC))
7465     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7466 
7467   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7468 }
7469 
7470 /// Return the location of the capture if the given lambda captures the given
7471 /// variable \p VD, or an invalid source location otherwise.
7472 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7473                                          const VarDecl *VD) {
7474   for (const Capture &Capture : LSI->Captures) {
7475     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7476       return Capture.getLocation();
7477   }
7478   return SourceLocation();
7479 }
7480 
7481 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7482                                      const LookupResult &R) {
7483   // Only diagnose if we're shadowing an unambiguous field or variable.
7484   if (R.getResultKind() != LookupResult::Found)
7485     return false;
7486 
7487   // Return false if warning is ignored.
7488   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7489 }
7490 
7491 /// Return the declaration shadowed by the given variable \p D, or null
7492 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7493 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7494                                         const LookupResult &R) {
7495   if (!shouldWarnIfShadowedDecl(Diags, R))
7496     return nullptr;
7497 
7498   // Don't diagnose declarations at file scope.
7499   if (D->hasGlobalStorage())
7500     return nullptr;
7501 
7502   NamedDecl *ShadowedDecl = R.getFoundDecl();
7503   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7504              ? ShadowedDecl
7505              : nullptr;
7506 }
7507 
7508 /// Return the declaration shadowed by the given typedef \p D, or null
7509 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7510 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7511                                         const LookupResult &R) {
7512   // Don't warn if typedef declaration is part of a class
7513   if (D->getDeclContext()->isRecord())
7514     return nullptr;
7515 
7516   if (!shouldWarnIfShadowedDecl(Diags, R))
7517     return nullptr;
7518 
7519   NamedDecl *ShadowedDecl = R.getFoundDecl();
7520   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7521 }
7522 
7523 /// Diagnose variable or built-in function shadowing.  Implements
7524 /// -Wshadow.
7525 ///
7526 /// This method is called whenever a VarDecl is added to a "useful"
7527 /// scope.
7528 ///
7529 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7530 /// \param R the lookup of the name
7531 ///
7532 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7533                        const LookupResult &R) {
7534   DeclContext *NewDC = D->getDeclContext();
7535 
7536   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7537     // Fields are not shadowed by variables in C++ static methods.
7538     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7539       if (MD->isStatic())
7540         return;
7541 
7542     // Fields shadowed by constructor parameters are a special case. Usually
7543     // the constructor initializes the field with the parameter.
7544     if (isa<CXXConstructorDecl>(NewDC))
7545       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7546         // Remember that this was shadowed so we can either warn about its
7547         // modification or its existence depending on warning settings.
7548         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7549         return;
7550       }
7551   }
7552 
7553   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7554     if (shadowedVar->isExternC()) {
7555       // For shadowing external vars, make sure that we point to the global
7556       // declaration, not a locally scoped extern declaration.
7557       for (auto I : shadowedVar->redecls())
7558         if (I->isFileVarDecl()) {
7559           ShadowedDecl = I;
7560           break;
7561         }
7562     }
7563 
7564   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7565 
7566   unsigned WarningDiag = diag::warn_decl_shadow;
7567   SourceLocation CaptureLoc;
7568   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7569       isa<CXXMethodDecl>(NewDC)) {
7570     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7571       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7572         if (RD->getLambdaCaptureDefault() == LCD_None) {
7573           // Try to avoid warnings for lambdas with an explicit capture list.
7574           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7575           // Warn only when the lambda captures the shadowed decl explicitly.
7576           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7577           if (CaptureLoc.isInvalid())
7578             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7579         } else {
7580           // Remember that this was shadowed so we can avoid the warning if the
7581           // shadowed decl isn't captured and the warning settings allow it.
7582           cast<LambdaScopeInfo>(getCurFunction())
7583               ->ShadowingDecls.push_back(
7584                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7585           return;
7586         }
7587       }
7588 
7589       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7590         // A variable can't shadow a local variable in an enclosing scope, if
7591         // they are separated by a non-capturing declaration context.
7592         for (DeclContext *ParentDC = NewDC;
7593              ParentDC && !ParentDC->Equals(OldDC);
7594              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7595           // Only block literals, captured statements, and lambda expressions
7596           // can capture; other scopes don't.
7597           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7598               !isLambdaCallOperator(ParentDC)) {
7599             return;
7600           }
7601         }
7602       }
7603     }
7604   }
7605 
7606   // Only warn about certain kinds of shadowing for class members.
7607   if (NewDC && NewDC->isRecord()) {
7608     // In particular, don't warn about shadowing non-class members.
7609     if (!OldDC->isRecord())
7610       return;
7611 
7612     // TODO: should we warn about static data members shadowing
7613     // static data members from base classes?
7614 
7615     // TODO: don't diagnose for inaccessible shadowed members.
7616     // This is hard to do perfectly because we might friend the
7617     // shadowing context, but that's just a false negative.
7618   }
7619 
7620 
7621   DeclarationName Name = R.getLookupName();
7622 
7623   // Emit warning and note.
7624   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7625     return;
7626   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7627   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7628   if (!CaptureLoc.isInvalid())
7629     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7630         << Name << /*explicitly*/ 1;
7631   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7632 }
7633 
7634 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7635 /// when these variables are captured by the lambda.
7636 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7637   for (const auto &Shadow : LSI->ShadowingDecls) {
7638     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7639     // Try to avoid the warning when the shadowed decl isn't captured.
7640     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7641     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7642     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7643                                        ? diag::warn_decl_shadow_uncaptured_local
7644                                        : diag::warn_decl_shadow)
7645         << Shadow.VD->getDeclName()
7646         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7647     if (!CaptureLoc.isInvalid())
7648       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7649           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7650     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7651   }
7652 }
7653 
7654 /// Check -Wshadow without the advantage of a previous lookup.
7655 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7656   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7657     return;
7658 
7659   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7660                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7661   LookupName(R, S);
7662   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7663     CheckShadow(D, ShadowedDecl, R);
7664 }
7665 
7666 /// Check if 'E', which is an expression that is about to be modified, refers
7667 /// to a constructor parameter that shadows a field.
7668 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7669   // Quickly ignore expressions that can't be shadowing ctor parameters.
7670   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7671     return;
7672   E = E->IgnoreParenImpCasts();
7673   auto *DRE = dyn_cast<DeclRefExpr>(E);
7674   if (!DRE)
7675     return;
7676   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7677   auto I = ShadowingDecls.find(D);
7678   if (I == ShadowingDecls.end())
7679     return;
7680   const NamedDecl *ShadowedDecl = I->second;
7681   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7682   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7683   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7684   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7685 
7686   // Avoid issuing multiple warnings about the same decl.
7687   ShadowingDecls.erase(I);
7688 }
7689 
7690 /// Check for conflict between this global or extern "C" declaration and
7691 /// previous global or extern "C" declarations. This is only used in C++.
7692 template<typename T>
7693 static bool checkGlobalOrExternCConflict(
7694     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7695   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7696   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7697 
7698   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7699     // The common case: this global doesn't conflict with any extern "C"
7700     // declaration.
7701     return false;
7702   }
7703 
7704   if (Prev) {
7705     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7706       // Both the old and new declarations have C language linkage. This is a
7707       // redeclaration.
7708       Previous.clear();
7709       Previous.addDecl(Prev);
7710       return true;
7711     }
7712 
7713     // This is a global, non-extern "C" declaration, and there is a previous
7714     // non-global extern "C" declaration. Diagnose if this is a variable
7715     // declaration.
7716     if (!isa<VarDecl>(ND))
7717       return false;
7718   } else {
7719     // The declaration is extern "C". Check for any declaration in the
7720     // translation unit which might conflict.
7721     if (IsGlobal) {
7722       // We have already performed the lookup into the translation unit.
7723       IsGlobal = false;
7724       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7725            I != E; ++I) {
7726         if (isa<VarDecl>(*I)) {
7727           Prev = *I;
7728           break;
7729         }
7730       }
7731     } else {
7732       DeclContext::lookup_result R =
7733           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7734       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7735            I != E; ++I) {
7736         if (isa<VarDecl>(*I)) {
7737           Prev = *I;
7738           break;
7739         }
7740         // FIXME: If we have any other entity with this name in global scope,
7741         // the declaration is ill-formed, but that is a defect: it breaks the
7742         // 'stat' hack, for instance. Only variables can have mangled name
7743         // clashes with extern "C" declarations, so only they deserve a
7744         // diagnostic.
7745       }
7746     }
7747 
7748     if (!Prev)
7749       return false;
7750   }
7751 
7752   // Use the first declaration's location to ensure we point at something which
7753   // is lexically inside an extern "C" linkage-spec.
7754   assert(Prev && "should have found a previous declaration to diagnose");
7755   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7756     Prev = FD->getFirstDecl();
7757   else
7758     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7759 
7760   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7761     << IsGlobal << ND;
7762   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7763     << IsGlobal;
7764   return false;
7765 }
7766 
7767 /// Apply special rules for handling extern "C" declarations. Returns \c true
7768 /// if we have found that this is a redeclaration of some prior entity.
7769 ///
7770 /// Per C++ [dcl.link]p6:
7771 ///   Two declarations [for a function or variable] with C language linkage
7772 ///   with the same name that appear in different scopes refer to the same
7773 ///   [entity]. An entity with C language linkage shall not be declared with
7774 ///   the same name as an entity in global scope.
7775 template<typename T>
7776 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7777                                                   LookupResult &Previous) {
7778   if (!S.getLangOpts().CPlusPlus) {
7779     // In C, when declaring a global variable, look for a corresponding 'extern'
7780     // variable declared in function scope. We don't need this in C++, because
7781     // we find local extern decls in the surrounding file-scope DeclContext.
7782     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7783       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7784         Previous.clear();
7785         Previous.addDecl(Prev);
7786         return true;
7787       }
7788     }
7789     return false;
7790   }
7791 
7792   // A declaration in the translation unit can conflict with an extern "C"
7793   // declaration.
7794   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7795     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7796 
7797   // An extern "C" declaration can conflict with a declaration in the
7798   // translation unit or can be a redeclaration of an extern "C" declaration
7799   // in another scope.
7800   if (isIncompleteDeclExternC(S,ND))
7801     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7802 
7803   // Neither global nor extern "C": nothing to do.
7804   return false;
7805 }
7806 
7807 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7808   // If the decl is already known invalid, don't check it.
7809   if (NewVD->isInvalidDecl())
7810     return;
7811 
7812   QualType T = NewVD->getType();
7813 
7814   // Defer checking an 'auto' type until its initializer is attached.
7815   if (T->isUndeducedType())
7816     return;
7817 
7818   if (NewVD->hasAttrs())
7819     CheckAlignasUnderalignment(NewVD);
7820 
7821   if (T->isObjCObjectType()) {
7822     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7823       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7824     T = Context.getObjCObjectPointerType(T);
7825     NewVD->setType(T);
7826   }
7827 
7828   // Emit an error if an address space was applied to decl with local storage.
7829   // This includes arrays of objects with address space qualifiers, but not
7830   // automatic variables that point to other address spaces.
7831   // ISO/IEC TR 18037 S5.1.2
7832   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7833       T.getAddressSpace() != LangAS::Default) {
7834     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7835     NewVD->setInvalidDecl();
7836     return;
7837   }
7838 
7839   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7840   // scope.
7841   if (getLangOpts().OpenCLVersion == 120 &&
7842       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7843       NewVD->isStaticLocal()) {
7844     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7845     NewVD->setInvalidDecl();
7846     return;
7847   }
7848 
7849   if (getLangOpts().OpenCL) {
7850     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7851     if (NewVD->hasAttr<BlocksAttr>()) {
7852       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7853       return;
7854     }
7855 
7856     if (T->isBlockPointerType()) {
7857       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7858       // can't use 'extern' storage class.
7859       if (!T.isConstQualified()) {
7860         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7861             << 0 /*const*/;
7862         NewVD->setInvalidDecl();
7863         return;
7864       }
7865       if (NewVD->hasExternalStorage()) {
7866         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7867         NewVD->setInvalidDecl();
7868         return;
7869       }
7870     }
7871     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7872     // __constant address space.
7873     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7874     // variables inside a function can also be declared in the global
7875     // address space.
7876     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7877     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7878     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7879         NewVD->hasExternalStorage()) {
7880       if (!T->isSamplerT() &&
7881           !T->isDependentType() &&
7882           !(T.getAddressSpace() == LangAS::opencl_constant ||
7883             (T.getAddressSpace() == LangAS::opencl_global &&
7884              (getLangOpts().OpenCLVersion == 200 ||
7885               getLangOpts().OpenCLCPlusPlus)))) {
7886         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7887         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7888           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7889               << Scope << "global or constant";
7890         else
7891           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7892               << Scope << "constant";
7893         NewVD->setInvalidDecl();
7894         return;
7895       }
7896     } else {
7897       if (T.getAddressSpace() == LangAS::opencl_global) {
7898         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7899             << 1 /*is any function*/ << "global";
7900         NewVD->setInvalidDecl();
7901         return;
7902       }
7903       if (T.getAddressSpace() == LangAS::opencl_constant ||
7904           T.getAddressSpace() == LangAS::opencl_local) {
7905         FunctionDecl *FD = getCurFunctionDecl();
7906         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7907         // in functions.
7908         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7909           if (T.getAddressSpace() == LangAS::opencl_constant)
7910             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7911                 << 0 /*non-kernel only*/ << "constant";
7912           else
7913             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7914                 << 0 /*non-kernel only*/ << "local";
7915           NewVD->setInvalidDecl();
7916           return;
7917         }
7918         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7919         // in the outermost scope of a kernel function.
7920         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7921           if (!getCurScope()->isFunctionScope()) {
7922             if (T.getAddressSpace() == LangAS::opencl_constant)
7923               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7924                   << "constant";
7925             else
7926               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7927                   << "local";
7928             NewVD->setInvalidDecl();
7929             return;
7930           }
7931         }
7932       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7933                  // If we are parsing a template we didn't deduce an addr
7934                  // space yet.
7935                  T.getAddressSpace() != LangAS::Default) {
7936         // Do not allow other address spaces on automatic variable.
7937         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7938         NewVD->setInvalidDecl();
7939         return;
7940       }
7941     }
7942   }
7943 
7944   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7945       && !NewVD->hasAttr<BlocksAttr>()) {
7946     if (getLangOpts().getGC() != LangOptions::NonGC)
7947       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7948     else {
7949       assert(!getLangOpts().ObjCAutoRefCount);
7950       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7951     }
7952   }
7953 
7954   bool isVM = T->isVariablyModifiedType();
7955   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7956       NewVD->hasAttr<BlocksAttr>())
7957     setFunctionHasBranchProtectedScope();
7958 
7959   if ((isVM && NewVD->hasLinkage()) ||
7960       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7961     bool SizeIsNegative;
7962     llvm::APSInt Oversized;
7963     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7964         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7965     QualType FixedT;
7966     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7967       FixedT = FixedTInfo->getType();
7968     else if (FixedTInfo) {
7969       // Type and type-as-written are canonically different. We need to fix up
7970       // both types separately.
7971       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7972                                                    Oversized);
7973     }
7974     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7975       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7976       // FIXME: This won't give the correct result for
7977       // int a[10][n];
7978       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7979 
7980       if (NewVD->isFileVarDecl())
7981         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7982         << SizeRange;
7983       else if (NewVD->isStaticLocal())
7984         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7985         << SizeRange;
7986       else
7987         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7988         << SizeRange;
7989       NewVD->setInvalidDecl();
7990       return;
7991     }
7992 
7993     if (!FixedTInfo) {
7994       if (NewVD->isFileVarDecl())
7995         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7996       else
7997         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7998       NewVD->setInvalidDecl();
7999       return;
8000     }
8001 
8002     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
8003     NewVD->setType(FixedT);
8004     NewVD->setTypeSourceInfo(FixedTInfo);
8005   }
8006 
8007   if (T->isVoidType()) {
8008     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8009     //                    of objects and functions.
8010     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8011       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8012         << T;
8013       NewVD->setInvalidDecl();
8014       return;
8015     }
8016   }
8017 
8018   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8019     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8020     NewVD->setInvalidDecl();
8021     return;
8022   }
8023 
8024   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8025     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8026     NewVD->setInvalidDecl();
8027     return;
8028   }
8029 
8030   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8031     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8032     NewVD->setInvalidDecl();
8033     return;
8034   }
8035 
8036   if (NewVD->isConstexpr() && !T->isDependentType() &&
8037       RequireLiteralType(NewVD->getLocation(), T,
8038                          diag::err_constexpr_var_non_literal)) {
8039     NewVD->setInvalidDecl();
8040     return;
8041   }
8042 }
8043 
8044 /// Perform semantic checking on a newly-created variable
8045 /// declaration.
8046 ///
8047 /// This routine performs all of the type-checking required for a
8048 /// variable declaration once it has been built. It is used both to
8049 /// check variables after they have been parsed and their declarators
8050 /// have been translated into a declaration, and to check variables
8051 /// that have been instantiated from a template.
8052 ///
8053 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8054 ///
8055 /// Returns true if the variable declaration is a redeclaration.
8056 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8057   CheckVariableDeclarationType(NewVD);
8058 
8059   // If the decl is already known invalid, don't check it.
8060   if (NewVD->isInvalidDecl())
8061     return false;
8062 
8063   // If we did not find anything by this name, look for a non-visible
8064   // extern "C" declaration with the same name.
8065   if (Previous.empty() &&
8066       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8067     Previous.setShadowed();
8068 
8069   if (!Previous.empty()) {
8070     MergeVarDecl(NewVD, Previous);
8071     return true;
8072   }
8073   return false;
8074 }
8075 
8076 namespace {
8077 struct FindOverriddenMethod {
8078   Sema *S;
8079   CXXMethodDecl *Method;
8080 
8081   /// Member lookup function that determines whether a given C++
8082   /// method overrides a method in a base class, to be used with
8083   /// CXXRecordDecl::lookupInBases().
8084   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8085     RecordDecl *BaseRecord =
8086         Specifier->getType()->castAs<RecordType>()->getDecl();
8087 
8088     DeclarationName Name = Method->getDeclName();
8089 
8090     // FIXME: Do we care about other names here too?
8091     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8092       // We really want to find the base class destructor here.
8093       QualType T = S->Context.getTypeDeclType(BaseRecord);
8094       CanQualType CT = S->Context.getCanonicalType(T);
8095 
8096       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8097     }
8098 
8099     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8100          Path.Decls = Path.Decls.slice(1)) {
8101       NamedDecl *D = Path.Decls.front();
8102       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8103         if (MD->isVirtual() &&
8104             !S->IsOverload(
8105                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8106                 /*ConsiderCudaAttrs=*/true,
8107                 // C++2a [class.virtual]p2 does not consider requires clauses
8108                 // when overriding.
8109                 /*ConsiderRequiresClauses=*/false))
8110           return true;
8111       }
8112     }
8113 
8114     return false;
8115   }
8116 };
8117 } // end anonymous namespace
8118 
8119 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8120 /// and if so, check that it's a valid override and remember it.
8121 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8122   // Look for methods in base classes that this method might override.
8123   CXXBasePaths Paths;
8124   FindOverriddenMethod FOM;
8125   FOM.Method = MD;
8126   FOM.S = this;
8127   bool AddedAny = false;
8128   if (DC->lookupInBases(FOM, Paths)) {
8129     for (auto *I : Paths.found_decls()) {
8130       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8131         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8132         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8133             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8134             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8135             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8136           AddedAny = true;
8137         }
8138       }
8139     }
8140   }
8141 
8142   return AddedAny;
8143 }
8144 
8145 namespace {
8146   // Struct for holding all of the extra arguments needed by
8147   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8148   struct ActOnFDArgs {
8149     Scope *S;
8150     Declarator &D;
8151     MultiTemplateParamsArg TemplateParamLists;
8152     bool AddToScope;
8153   };
8154 } // end anonymous namespace
8155 
8156 namespace {
8157 
8158 // Callback to only accept typo corrections that have a non-zero edit distance.
8159 // Also only accept corrections that have the same parent decl.
8160 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8161  public:
8162   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8163                             CXXRecordDecl *Parent)
8164       : Context(Context), OriginalFD(TypoFD),
8165         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8166 
8167   bool ValidateCandidate(const TypoCorrection &candidate) override {
8168     if (candidate.getEditDistance() == 0)
8169       return false;
8170 
8171     SmallVector<unsigned, 1> MismatchedParams;
8172     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8173                                           CDeclEnd = candidate.end();
8174          CDecl != CDeclEnd; ++CDecl) {
8175       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8176 
8177       if (FD && !FD->hasBody() &&
8178           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8179         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8180           CXXRecordDecl *Parent = MD->getParent();
8181           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8182             return true;
8183         } else if (!ExpectedParent) {
8184           return true;
8185         }
8186       }
8187     }
8188 
8189     return false;
8190   }
8191 
8192   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8193     return std::make_unique<DifferentNameValidatorCCC>(*this);
8194   }
8195 
8196  private:
8197   ASTContext &Context;
8198   FunctionDecl *OriginalFD;
8199   CXXRecordDecl *ExpectedParent;
8200 };
8201 
8202 } // end anonymous namespace
8203 
8204 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8205   TypoCorrectedFunctionDefinitions.insert(F);
8206 }
8207 
8208 /// Generate diagnostics for an invalid function redeclaration.
8209 ///
8210 /// This routine handles generating the diagnostic messages for an invalid
8211 /// function redeclaration, including finding possible similar declarations
8212 /// or performing typo correction if there are no previous declarations with
8213 /// the same name.
8214 ///
8215 /// Returns a NamedDecl iff typo correction was performed and substituting in
8216 /// the new declaration name does not cause new errors.
8217 static NamedDecl *DiagnoseInvalidRedeclaration(
8218     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8219     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8220   DeclarationName Name = NewFD->getDeclName();
8221   DeclContext *NewDC = NewFD->getDeclContext();
8222   SmallVector<unsigned, 1> MismatchedParams;
8223   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8224   TypoCorrection Correction;
8225   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8226   unsigned DiagMsg =
8227     IsLocalFriend ? diag::err_no_matching_local_friend :
8228     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8229     diag::err_member_decl_does_not_match;
8230   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8231                     IsLocalFriend ? Sema::LookupLocalFriendName
8232                                   : Sema::LookupOrdinaryName,
8233                     Sema::ForVisibleRedeclaration);
8234 
8235   NewFD->setInvalidDecl();
8236   if (IsLocalFriend)
8237     SemaRef.LookupName(Prev, S);
8238   else
8239     SemaRef.LookupQualifiedName(Prev, NewDC);
8240   assert(!Prev.isAmbiguous() &&
8241          "Cannot have an ambiguity in previous-declaration lookup");
8242   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8243   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8244                                 MD ? MD->getParent() : nullptr);
8245   if (!Prev.empty()) {
8246     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8247          Func != FuncEnd; ++Func) {
8248       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8249       if (FD &&
8250           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8251         // Add 1 to the index so that 0 can mean the mismatch didn't
8252         // involve a parameter
8253         unsigned ParamNum =
8254             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8255         NearMatches.push_back(std::make_pair(FD, ParamNum));
8256       }
8257     }
8258   // If the qualified name lookup yielded nothing, try typo correction
8259   } else if ((Correction = SemaRef.CorrectTypo(
8260                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8261                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8262                   IsLocalFriend ? nullptr : NewDC))) {
8263     // Set up everything for the call to ActOnFunctionDeclarator
8264     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8265                               ExtraArgs.D.getIdentifierLoc());
8266     Previous.clear();
8267     Previous.setLookupName(Correction.getCorrection());
8268     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8269                                     CDeclEnd = Correction.end();
8270          CDecl != CDeclEnd; ++CDecl) {
8271       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8272       if (FD && !FD->hasBody() &&
8273           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8274         Previous.addDecl(FD);
8275       }
8276     }
8277     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8278 
8279     NamedDecl *Result;
8280     // Retry building the function declaration with the new previous
8281     // declarations, and with errors suppressed.
8282     {
8283       // Trap errors.
8284       Sema::SFINAETrap Trap(SemaRef);
8285 
8286       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8287       // pieces need to verify the typo-corrected C++ declaration and hopefully
8288       // eliminate the need for the parameter pack ExtraArgs.
8289       Result = SemaRef.ActOnFunctionDeclarator(
8290           ExtraArgs.S, ExtraArgs.D,
8291           Correction.getCorrectionDecl()->getDeclContext(),
8292           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8293           ExtraArgs.AddToScope);
8294 
8295       if (Trap.hasErrorOccurred())
8296         Result = nullptr;
8297     }
8298 
8299     if (Result) {
8300       // Determine which correction we picked.
8301       Decl *Canonical = Result->getCanonicalDecl();
8302       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8303            I != E; ++I)
8304         if ((*I)->getCanonicalDecl() == Canonical)
8305           Correction.setCorrectionDecl(*I);
8306 
8307       // Let Sema know about the correction.
8308       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8309       SemaRef.diagnoseTypo(
8310           Correction,
8311           SemaRef.PDiag(IsLocalFriend
8312                           ? diag::err_no_matching_local_friend_suggest
8313                           : diag::err_member_decl_does_not_match_suggest)
8314             << Name << NewDC << IsDefinition);
8315       return Result;
8316     }
8317 
8318     // Pretend the typo correction never occurred
8319     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8320                               ExtraArgs.D.getIdentifierLoc());
8321     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8322     Previous.clear();
8323     Previous.setLookupName(Name);
8324   }
8325 
8326   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8327       << Name << NewDC << IsDefinition << NewFD->getLocation();
8328 
8329   bool NewFDisConst = false;
8330   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8331     NewFDisConst = NewMD->isConst();
8332 
8333   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8334        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8335        NearMatch != NearMatchEnd; ++NearMatch) {
8336     FunctionDecl *FD = NearMatch->first;
8337     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8338     bool FDisConst = MD && MD->isConst();
8339     bool IsMember = MD || !IsLocalFriend;
8340 
8341     // FIXME: These notes are poorly worded for the local friend case.
8342     if (unsigned Idx = NearMatch->second) {
8343       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8344       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8345       if (Loc.isInvalid()) Loc = FD->getLocation();
8346       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8347                                  : diag::note_local_decl_close_param_match)
8348         << Idx << FDParam->getType()
8349         << NewFD->getParamDecl(Idx - 1)->getType();
8350     } else if (FDisConst != NewFDisConst) {
8351       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8352           << NewFDisConst << FD->getSourceRange().getEnd();
8353     } else
8354       SemaRef.Diag(FD->getLocation(),
8355                    IsMember ? diag::note_member_def_close_match
8356                             : diag::note_local_decl_close_match);
8357   }
8358   return nullptr;
8359 }
8360 
8361 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8362   switch (D.getDeclSpec().getStorageClassSpec()) {
8363   default: llvm_unreachable("Unknown storage class!");
8364   case DeclSpec::SCS_auto:
8365   case DeclSpec::SCS_register:
8366   case DeclSpec::SCS_mutable:
8367     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8368                  diag::err_typecheck_sclass_func);
8369     D.getMutableDeclSpec().ClearStorageClassSpecs();
8370     D.setInvalidType();
8371     break;
8372   case DeclSpec::SCS_unspecified: break;
8373   case DeclSpec::SCS_extern:
8374     if (D.getDeclSpec().isExternInLinkageSpec())
8375       return SC_None;
8376     return SC_Extern;
8377   case DeclSpec::SCS_static: {
8378     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8379       // C99 6.7.1p5:
8380       //   The declaration of an identifier for a function that has
8381       //   block scope shall have no explicit storage-class specifier
8382       //   other than extern
8383       // See also (C++ [dcl.stc]p4).
8384       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8385                    diag::err_static_block_func);
8386       break;
8387     } else
8388       return SC_Static;
8389   }
8390   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8391   }
8392 
8393   // No explicit storage class has already been returned
8394   return SC_None;
8395 }
8396 
8397 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8398                                            DeclContext *DC, QualType &R,
8399                                            TypeSourceInfo *TInfo,
8400                                            StorageClass SC,
8401                                            bool &IsVirtualOkay) {
8402   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8403   DeclarationName Name = NameInfo.getName();
8404 
8405   FunctionDecl *NewFD = nullptr;
8406   bool isInline = D.getDeclSpec().isInlineSpecified();
8407 
8408   if (!SemaRef.getLangOpts().CPlusPlus) {
8409     // Determine whether the function was written with a
8410     // prototype. This true when:
8411     //   - there is a prototype in the declarator, or
8412     //   - the type R of the function is some kind of typedef or other non-
8413     //     attributed reference to a type name (which eventually refers to a
8414     //     function type).
8415     bool HasPrototype =
8416       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8417       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8418 
8419     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8420                                  R, TInfo, SC, isInline, HasPrototype,
8421                                  CSK_unspecified,
8422                                  /*TrailingRequiresClause=*/nullptr);
8423     if (D.isInvalidType())
8424       NewFD->setInvalidDecl();
8425 
8426     return NewFD;
8427   }
8428 
8429   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8430 
8431   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8432   if (ConstexprKind == CSK_constinit) {
8433     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8434                  diag::err_constexpr_wrong_decl_kind)
8435         << ConstexprKind;
8436     ConstexprKind = CSK_unspecified;
8437     D.getMutableDeclSpec().ClearConstexprSpec();
8438   }
8439   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8440 
8441   // Check that the return type is not an abstract class type.
8442   // For record types, this is done by the AbstractClassUsageDiagnoser once
8443   // the class has been completely parsed.
8444   if (!DC->isRecord() &&
8445       SemaRef.RequireNonAbstractType(
8446           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8447           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8448     D.setInvalidType();
8449 
8450   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8451     // This is a C++ constructor declaration.
8452     assert(DC->isRecord() &&
8453            "Constructors can only be declared in a member context");
8454 
8455     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8456     return CXXConstructorDecl::Create(
8457         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8458         TInfo, ExplicitSpecifier, isInline,
8459         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8460         TrailingRequiresClause);
8461 
8462   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8463     // This is a C++ destructor declaration.
8464     if (DC->isRecord()) {
8465       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8466       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8467       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8468           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8469           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8470           TrailingRequiresClause);
8471 
8472       // If the destructor needs an implicit exception specification, set it
8473       // now. FIXME: It'd be nice to be able to create the right type to start
8474       // with, but the type needs to reference the destructor declaration.
8475       if (SemaRef.getLangOpts().CPlusPlus11)
8476         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8477 
8478       IsVirtualOkay = true;
8479       return NewDD;
8480 
8481     } else {
8482       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8483       D.setInvalidType();
8484 
8485       // Create a FunctionDecl to satisfy the function definition parsing
8486       // code path.
8487       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8488                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8489                                   isInline,
8490                                   /*hasPrototype=*/true, ConstexprKind,
8491                                   TrailingRequiresClause);
8492     }
8493 
8494   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8495     if (!DC->isRecord()) {
8496       SemaRef.Diag(D.getIdentifierLoc(),
8497            diag::err_conv_function_not_member);
8498       return nullptr;
8499     }
8500 
8501     SemaRef.CheckConversionDeclarator(D, R, SC);
8502     if (D.isInvalidType())
8503       return nullptr;
8504 
8505     IsVirtualOkay = true;
8506     return CXXConversionDecl::Create(
8507         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8508         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8509         TrailingRequiresClause);
8510 
8511   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8512     if (TrailingRequiresClause)
8513       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8514                    diag::err_trailing_requires_clause_on_deduction_guide)
8515           << TrailingRequiresClause->getSourceRange();
8516     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8517 
8518     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8519                                          ExplicitSpecifier, NameInfo, R, TInfo,
8520                                          D.getEndLoc());
8521   } else if (DC->isRecord()) {
8522     // If the name of the function is the same as the name of the record,
8523     // then this must be an invalid constructor that has a return type.
8524     // (The parser checks for a return type and makes the declarator a
8525     // constructor if it has no return type).
8526     if (Name.getAsIdentifierInfo() &&
8527         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8528       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8529         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8530         << SourceRange(D.getIdentifierLoc());
8531       return nullptr;
8532     }
8533 
8534     // This is a C++ method declaration.
8535     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8536         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8537         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8538         TrailingRequiresClause);
8539     IsVirtualOkay = !Ret->isStatic();
8540     return Ret;
8541   } else {
8542     bool isFriend =
8543         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8544     if (!isFriend && SemaRef.CurContext->isRecord())
8545       return nullptr;
8546 
8547     // Determine whether the function was written with a
8548     // prototype. This true when:
8549     //   - we're in C++ (where every function has a prototype),
8550     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8551                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8552                                 ConstexprKind, TrailingRequiresClause);
8553   }
8554 }
8555 
8556 enum OpenCLParamType {
8557   ValidKernelParam,
8558   PtrPtrKernelParam,
8559   PtrKernelParam,
8560   InvalidAddrSpacePtrKernelParam,
8561   InvalidKernelParam,
8562   RecordKernelParam
8563 };
8564 
8565 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8566   // Size dependent types are just typedefs to normal integer types
8567   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8568   // integers other than by their names.
8569   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8570 
8571   // Remove typedefs one by one until we reach a typedef
8572   // for a size dependent type.
8573   QualType DesugaredTy = Ty;
8574   do {
8575     ArrayRef<StringRef> Names(SizeTypeNames);
8576     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8577     if (Names.end() != Match)
8578       return true;
8579 
8580     Ty = DesugaredTy;
8581     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8582   } while (DesugaredTy != Ty);
8583 
8584   return false;
8585 }
8586 
8587 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8588   if (PT->isPointerType()) {
8589     QualType PointeeType = PT->getPointeeType();
8590     if (PointeeType->isPointerType())
8591       return PtrPtrKernelParam;
8592     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8593         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8594         PointeeType.getAddressSpace() == LangAS::Default)
8595       return InvalidAddrSpacePtrKernelParam;
8596     return PtrKernelParam;
8597   }
8598 
8599   // OpenCL v1.2 s6.9.k:
8600   // Arguments to kernel functions in a program cannot be declared with the
8601   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8602   // uintptr_t or a struct and/or union that contain fields declared to be one
8603   // of these built-in scalar types.
8604   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8605     return InvalidKernelParam;
8606 
8607   if (PT->isImageType())
8608     return PtrKernelParam;
8609 
8610   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8611     return InvalidKernelParam;
8612 
8613   // OpenCL extension spec v1.2 s9.5:
8614   // This extension adds support for half scalar and vector types as built-in
8615   // types that can be used for arithmetic operations, conversions etc.
8616   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8617     return InvalidKernelParam;
8618 
8619   if (PT->isRecordType())
8620     return RecordKernelParam;
8621 
8622   // Look into an array argument to check if it has a forbidden type.
8623   if (PT->isArrayType()) {
8624     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8625     // Call ourself to check an underlying type of an array. Since the
8626     // getPointeeOrArrayElementType returns an innermost type which is not an
8627     // array, this recursive call only happens once.
8628     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8629   }
8630 
8631   return ValidKernelParam;
8632 }
8633 
8634 static void checkIsValidOpenCLKernelParameter(
8635   Sema &S,
8636   Declarator &D,
8637   ParmVarDecl *Param,
8638   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8639   QualType PT = Param->getType();
8640 
8641   // Cache the valid types we encounter to avoid rechecking structs that are
8642   // used again
8643   if (ValidTypes.count(PT.getTypePtr()))
8644     return;
8645 
8646   switch (getOpenCLKernelParameterType(S, PT)) {
8647   case PtrPtrKernelParam:
8648     // OpenCL v1.2 s6.9.a:
8649     // A kernel function argument cannot be declared as a
8650     // pointer to a pointer type.
8651     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8652     D.setInvalidType();
8653     return;
8654 
8655   case InvalidAddrSpacePtrKernelParam:
8656     // OpenCL v1.0 s6.5:
8657     // __kernel function arguments declared to be a pointer of a type can point
8658     // to one of the following address spaces only : __global, __local or
8659     // __constant.
8660     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8661     D.setInvalidType();
8662     return;
8663 
8664     // OpenCL v1.2 s6.9.k:
8665     // Arguments to kernel functions in a program cannot be declared with the
8666     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8667     // uintptr_t or a struct and/or union that contain fields declared to be
8668     // one of these built-in scalar types.
8669 
8670   case InvalidKernelParam:
8671     // OpenCL v1.2 s6.8 n:
8672     // A kernel function argument cannot be declared
8673     // of event_t type.
8674     // Do not diagnose half type since it is diagnosed as invalid argument
8675     // type for any function elsewhere.
8676     if (!PT->isHalfType()) {
8677       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8678 
8679       // Explain what typedefs are involved.
8680       const TypedefType *Typedef = nullptr;
8681       while ((Typedef = PT->getAs<TypedefType>())) {
8682         SourceLocation Loc = Typedef->getDecl()->getLocation();
8683         // SourceLocation may be invalid for a built-in type.
8684         if (Loc.isValid())
8685           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8686         PT = Typedef->desugar();
8687       }
8688     }
8689 
8690     D.setInvalidType();
8691     return;
8692 
8693   case PtrKernelParam:
8694   case ValidKernelParam:
8695     ValidTypes.insert(PT.getTypePtr());
8696     return;
8697 
8698   case RecordKernelParam:
8699     break;
8700   }
8701 
8702   // Track nested structs we will inspect
8703   SmallVector<const Decl *, 4> VisitStack;
8704 
8705   // Track where we are in the nested structs. Items will migrate from
8706   // VisitStack to HistoryStack as we do the DFS for bad field.
8707   SmallVector<const FieldDecl *, 4> HistoryStack;
8708   HistoryStack.push_back(nullptr);
8709 
8710   // At this point we already handled everything except of a RecordType or
8711   // an ArrayType of a RecordType.
8712   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8713   const RecordType *RecTy =
8714       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8715   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8716 
8717   VisitStack.push_back(RecTy->getDecl());
8718   assert(VisitStack.back() && "First decl null?");
8719 
8720   do {
8721     const Decl *Next = VisitStack.pop_back_val();
8722     if (!Next) {
8723       assert(!HistoryStack.empty());
8724       // Found a marker, we have gone up a level
8725       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8726         ValidTypes.insert(Hist->getType().getTypePtr());
8727 
8728       continue;
8729     }
8730 
8731     // Adds everything except the original parameter declaration (which is not a
8732     // field itself) to the history stack.
8733     const RecordDecl *RD;
8734     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8735       HistoryStack.push_back(Field);
8736 
8737       QualType FieldTy = Field->getType();
8738       // Other field types (known to be valid or invalid) are handled while we
8739       // walk around RecordDecl::fields().
8740       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8741              "Unexpected type.");
8742       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8743 
8744       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8745     } else {
8746       RD = cast<RecordDecl>(Next);
8747     }
8748 
8749     // Add a null marker so we know when we've gone back up a level
8750     VisitStack.push_back(nullptr);
8751 
8752     for (const auto *FD : RD->fields()) {
8753       QualType QT = FD->getType();
8754 
8755       if (ValidTypes.count(QT.getTypePtr()))
8756         continue;
8757 
8758       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8759       if (ParamType == ValidKernelParam)
8760         continue;
8761 
8762       if (ParamType == RecordKernelParam) {
8763         VisitStack.push_back(FD);
8764         continue;
8765       }
8766 
8767       // OpenCL v1.2 s6.9.p:
8768       // Arguments to kernel functions that are declared to be a struct or union
8769       // do not allow OpenCL objects to be passed as elements of the struct or
8770       // union.
8771       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8772           ParamType == InvalidAddrSpacePtrKernelParam) {
8773         S.Diag(Param->getLocation(),
8774                diag::err_record_with_pointers_kernel_param)
8775           << PT->isUnionType()
8776           << PT;
8777       } else {
8778         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8779       }
8780 
8781       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8782           << OrigRecDecl->getDeclName();
8783 
8784       // We have an error, now let's go back up through history and show where
8785       // the offending field came from
8786       for (ArrayRef<const FieldDecl *>::const_iterator
8787                I = HistoryStack.begin() + 1,
8788                E = HistoryStack.end();
8789            I != E; ++I) {
8790         const FieldDecl *OuterField = *I;
8791         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8792           << OuterField->getType();
8793       }
8794 
8795       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8796         << QT->isPointerType()
8797         << QT;
8798       D.setInvalidType();
8799       return;
8800     }
8801   } while (!VisitStack.empty());
8802 }
8803 
8804 /// Find the DeclContext in which a tag is implicitly declared if we see an
8805 /// elaborated type specifier in the specified context, and lookup finds
8806 /// nothing.
8807 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8808   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8809     DC = DC->getParent();
8810   return DC;
8811 }
8812 
8813 /// Find the Scope in which a tag is implicitly declared if we see an
8814 /// elaborated type specifier in the specified context, and lookup finds
8815 /// nothing.
8816 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8817   while (S->isClassScope() ||
8818          (LangOpts.CPlusPlus &&
8819           S->isFunctionPrototypeScope()) ||
8820          ((S->getFlags() & Scope::DeclScope) == 0) ||
8821          (S->getEntity() && S->getEntity()->isTransparentContext()))
8822     S = S->getParent();
8823   return S;
8824 }
8825 
8826 NamedDecl*
8827 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8828                               TypeSourceInfo *TInfo, LookupResult &Previous,
8829                               MultiTemplateParamsArg TemplateParamListsRef,
8830                               bool &AddToScope) {
8831   QualType R = TInfo->getType();
8832 
8833   assert(R->isFunctionType());
8834   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8835     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8836 
8837   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8838   for (TemplateParameterList *TPL : TemplateParamListsRef)
8839     TemplateParamLists.push_back(TPL);
8840   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8841     if (!TemplateParamLists.empty() &&
8842         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8843       TemplateParamLists.back() = Invented;
8844     else
8845       TemplateParamLists.push_back(Invented);
8846   }
8847 
8848   // TODO: consider using NameInfo for diagnostic.
8849   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8850   DeclarationName Name = NameInfo.getName();
8851   StorageClass SC = getFunctionStorageClass(*this, D);
8852 
8853   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8854     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8855          diag::err_invalid_thread)
8856       << DeclSpec::getSpecifierName(TSCS);
8857 
8858   if (D.isFirstDeclarationOfMember())
8859     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8860                            D.getIdentifierLoc());
8861 
8862   bool isFriend = false;
8863   FunctionTemplateDecl *FunctionTemplate = nullptr;
8864   bool isMemberSpecialization = false;
8865   bool isFunctionTemplateSpecialization = false;
8866 
8867   bool isDependentClassScopeExplicitSpecialization = false;
8868   bool HasExplicitTemplateArgs = false;
8869   TemplateArgumentListInfo TemplateArgs;
8870 
8871   bool isVirtualOkay = false;
8872 
8873   DeclContext *OriginalDC = DC;
8874   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8875 
8876   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8877                                               isVirtualOkay);
8878   if (!NewFD) return nullptr;
8879 
8880   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8881     NewFD->setTopLevelDeclInObjCContainer();
8882 
8883   // Set the lexical context. If this is a function-scope declaration, or has a
8884   // C++ scope specifier, or is the object of a friend declaration, the lexical
8885   // context will be different from the semantic context.
8886   NewFD->setLexicalDeclContext(CurContext);
8887 
8888   if (IsLocalExternDecl)
8889     NewFD->setLocalExternDecl();
8890 
8891   if (getLangOpts().CPlusPlus) {
8892     bool isInline = D.getDeclSpec().isInlineSpecified();
8893     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8894     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8895     isFriend = D.getDeclSpec().isFriendSpecified();
8896     if (isFriend && !isInline && D.isFunctionDefinition()) {
8897       // C++ [class.friend]p5
8898       //   A function can be defined in a friend declaration of a
8899       //   class . . . . Such a function is implicitly inline.
8900       NewFD->setImplicitlyInline();
8901     }
8902 
8903     // If this is a method defined in an __interface, and is not a constructor
8904     // or an overloaded operator, then set the pure flag (isVirtual will already
8905     // return true).
8906     if (const CXXRecordDecl *Parent =
8907           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8908       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8909         NewFD->setPure(true);
8910 
8911       // C++ [class.union]p2
8912       //   A union can have member functions, but not virtual functions.
8913       if (isVirtual && Parent->isUnion())
8914         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8915     }
8916 
8917     SetNestedNameSpecifier(*this, NewFD, D);
8918     isMemberSpecialization = false;
8919     isFunctionTemplateSpecialization = false;
8920     if (D.isInvalidType())
8921       NewFD->setInvalidDecl();
8922 
8923     // Match up the template parameter lists with the scope specifier, then
8924     // determine whether we have a template or a template specialization.
8925     bool Invalid = false;
8926     TemplateParameterList *TemplateParams =
8927         MatchTemplateParametersToScopeSpecifier(
8928             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8929             D.getCXXScopeSpec(),
8930             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8931                 ? D.getName().TemplateId
8932                 : nullptr,
8933             TemplateParamLists, isFriend, isMemberSpecialization,
8934             Invalid);
8935     if (TemplateParams) {
8936       // Check that we can declare a template here.
8937       if (CheckTemplateDeclScope(S, TemplateParams))
8938         NewFD->setInvalidDecl();
8939 
8940       if (TemplateParams->size() > 0) {
8941         // This is a function template
8942 
8943         // A destructor cannot be a template.
8944         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8945           Diag(NewFD->getLocation(), diag::err_destructor_template);
8946           NewFD->setInvalidDecl();
8947         }
8948 
8949         // If we're adding a template to a dependent context, we may need to
8950         // rebuilding some of the types used within the template parameter list,
8951         // now that we know what the current instantiation is.
8952         if (DC->isDependentContext()) {
8953           ContextRAII SavedContext(*this, DC);
8954           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8955             Invalid = true;
8956         }
8957 
8958         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8959                                                         NewFD->getLocation(),
8960                                                         Name, TemplateParams,
8961                                                         NewFD);
8962         FunctionTemplate->setLexicalDeclContext(CurContext);
8963         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8964 
8965         // For source fidelity, store the other template param lists.
8966         if (TemplateParamLists.size() > 1) {
8967           NewFD->setTemplateParameterListsInfo(Context,
8968               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8969                   .drop_back(1));
8970         }
8971       } else {
8972         // This is a function template specialization.
8973         isFunctionTemplateSpecialization = true;
8974         // For source fidelity, store all the template param lists.
8975         if (TemplateParamLists.size() > 0)
8976           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8977 
8978         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8979         if (isFriend) {
8980           // We want to remove the "template<>", found here.
8981           SourceRange RemoveRange = TemplateParams->getSourceRange();
8982 
8983           // If we remove the template<> and the name is not a
8984           // template-id, we're actually silently creating a problem:
8985           // the friend declaration will refer to an untemplated decl,
8986           // and clearly the user wants a template specialization.  So
8987           // we need to insert '<>' after the name.
8988           SourceLocation InsertLoc;
8989           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8990             InsertLoc = D.getName().getSourceRange().getEnd();
8991             InsertLoc = getLocForEndOfToken(InsertLoc);
8992           }
8993 
8994           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8995             << Name << RemoveRange
8996             << FixItHint::CreateRemoval(RemoveRange)
8997             << FixItHint::CreateInsertion(InsertLoc, "<>");
8998         }
8999       }
9000     } else {
9001       // Check that we can declare a template here.
9002       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9003           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9004         NewFD->setInvalidDecl();
9005 
9006       // All template param lists were matched against the scope specifier:
9007       // this is NOT (an explicit specialization of) a template.
9008       if (TemplateParamLists.size() > 0)
9009         // For source fidelity, store all the template param lists.
9010         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9011     }
9012 
9013     if (Invalid) {
9014       NewFD->setInvalidDecl();
9015       if (FunctionTemplate)
9016         FunctionTemplate->setInvalidDecl();
9017     }
9018 
9019     // C++ [dcl.fct.spec]p5:
9020     //   The virtual specifier shall only be used in declarations of
9021     //   nonstatic class member functions that appear within a
9022     //   member-specification of a class declaration; see 10.3.
9023     //
9024     if (isVirtual && !NewFD->isInvalidDecl()) {
9025       if (!isVirtualOkay) {
9026         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9027              diag::err_virtual_non_function);
9028       } else if (!CurContext->isRecord()) {
9029         // 'virtual' was specified outside of the class.
9030         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9031              diag::err_virtual_out_of_class)
9032           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9033       } else if (NewFD->getDescribedFunctionTemplate()) {
9034         // C++ [temp.mem]p3:
9035         //  A member function template shall not be virtual.
9036         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9037              diag::err_virtual_member_function_template)
9038           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9039       } else {
9040         // Okay: Add virtual to the method.
9041         NewFD->setVirtualAsWritten(true);
9042       }
9043 
9044       if (getLangOpts().CPlusPlus14 &&
9045           NewFD->getReturnType()->isUndeducedType())
9046         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9047     }
9048 
9049     if (getLangOpts().CPlusPlus14 &&
9050         (NewFD->isDependentContext() ||
9051          (isFriend && CurContext->isDependentContext())) &&
9052         NewFD->getReturnType()->isUndeducedType()) {
9053       // If the function template is referenced directly (for instance, as a
9054       // member of the current instantiation), pretend it has a dependent type.
9055       // This is not really justified by the standard, but is the only sane
9056       // thing to do.
9057       // FIXME: For a friend function, we have not marked the function as being
9058       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9059       const FunctionProtoType *FPT =
9060           NewFD->getType()->castAs<FunctionProtoType>();
9061       QualType Result =
9062           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9063       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9064                                              FPT->getExtProtoInfo()));
9065     }
9066 
9067     // C++ [dcl.fct.spec]p3:
9068     //  The inline specifier shall not appear on a block scope function
9069     //  declaration.
9070     if (isInline && !NewFD->isInvalidDecl()) {
9071       if (CurContext->isFunctionOrMethod()) {
9072         // 'inline' is not allowed on block scope function declaration.
9073         Diag(D.getDeclSpec().getInlineSpecLoc(),
9074              diag::err_inline_declaration_block_scope) << Name
9075           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9076       }
9077     }
9078 
9079     // C++ [dcl.fct.spec]p6:
9080     //  The explicit specifier shall be used only in the declaration of a
9081     //  constructor or conversion function within its class definition;
9082     //  see 12.3.1 and 12.3.2.
9083     if (hasExplicit && !NewFD->isInvalidDecl() &&
9084         !isa<CXXDeductionGuideDecl>(NewFD)) {
9085       if (!CurContext->isRecord()) {
9086         // 'explicit' was specified outside of the class.
9087         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9088              diag::err_explicit_out_of_class)
9089             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9090       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9091                  !isa<CXXConversionDecl>(NewFD)) {
9092         // 'explicit' was specified on a function that wasn't a constructor
9093         // or conversion function.
9094         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9095              diag::err_explicit_non_ctor_or_conv_function)
9096             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9097       }
9098     }
9099 
9100     if (ConstexprSpecKind ConstexprKind =
9101             D.getDeclSpec().getConstexprSpecifier()) {
9102       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9103       // are implicitly inline.
9104       NewFD->setImplicitlyInline();
9105 
9106       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9107       // be either constructors or to return a literal type. Therefore,
9108       // destructors cannot be declared constexpr.
9109       if (isa<CXXDestructorDecl>(NewFD) &&
9110           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9111         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9112             << ConstexprKind;
9113         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9114       }
9115       // C++20 [dcl.constexpr]p2: An allocation function, or a
9116       // deallocation function shall not be declared with the consteval
9117       // specifier.
9118       if (ConstexprKind == CSK_consteval &&
9119           (NewFD->getOverloadedOperator() == OO_New ||
9120            NewFD->getOverloadedOperator() == OO_Array_New ||
9121            NewFD->getOverloadedOperator() == OO_Delete ||
9122            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9123         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9124              diag::err_invalid_consteval_decl_kind)
9125             << NewFD;
9126         NewFD->setConstexprKind(CSK_constexpr);
9127       }
9128     }
9129 
9130     // If __module_private__ was specified, mark the function accordingly.
9131     if (D.getDeclSpec().isModulePrivateSpecified()) {
9132       if (isFunctionTemplateSpecialization) {
9133         SourceLocation ModulePrivateLoc
9134           = D.getDeclSpec().getModulePrivateSpecLoc();
9135         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9136           << 0
9137           << FixItHint::CreateRemoval(ModulePrivateLoc);
9138       } else {
9139         NewFD->setModulePrivate();
9140         if (FunctionTemplate)
9141           FunctionTemplate->setModulePrivate();
9142       }
9143     }
9144 
9145     if (isFriend) {
9146       if (FunctionTemplate) {
9147         FunctionTemplate->setObjectOfFriendDecl();
9148         FunctionTemplate->setAccess(AS_public);
9149       }
9150       NewFD->setObjectOfFriendDecl();
9151       NewFD->setAccess(AS_public);
9152     }
9153 
9154     // If a function is defined as defaulted or deleted, mark it as such now.
9155     // We'll do the relevant checks on defaulted / deleted functions later.
9156     switch (D.getFunctionDefinitionKind()) {
9157       case FDK_Declaration:
9158       case FDK_Definition:
9159         break;
9160 
9161       case FDK_Defaulted:
9162         NewFD->setDefaulted();
9163         break;
9164 
9165       case FDK_Deleted:
9166         NewFD->setDeletedAsWritten();
9167         break;
9168     }
9169 
9170     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9171         D.isFunctionDefinition()) {
9172       // C++ [class.mfct]p2:
9173       //   A member function may be defined (8.4) in its class definition, in
9174       //   which case it is an inline member function (7.1.2)
9175       NewFD->setImplicitlyInline();
9176     }
9177 
9178     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9179         !CurContext->isRecord()) {
9180       // C++ [class.static]p1:
9181       //   A data or function member of a class may be declared static
9182       //   in a class definition, in which case it is a static member of
9183       //   the class.
9184 
9185       // Complain about the 'static' specifier if it's on an out-of-line
9186       // member function definition.
9187 
9188       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9189       // member function template declaration and class member template
9190       // declaration (MSVC versions before 2015), warn about this.
9191       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9192            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9193              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9194            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9195            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9196         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9197     }
9198 
9199     // C++11 [except.spec]p15:
9200     //   A deallocation function with no exception-specification is treated
9201     //   as if it were specified with noexcept(true).
9202     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9203     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9204          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9205         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9206       NewFD->setType(Context.getFunctionType(
9207           FPT->getReturnType(), FPT->getParamTypes(),
9208           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9209   }
9210 
9211   // Filter out previous declarations that don't match the scope.
9212   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9213                        D.getCXXScopeSpec().isNotEmpty() ||
9214                        isMemberSpecialization ||
9215                        isFunctionTemplateSpecialization);
9216 
9217   // Handle GNU asm-label extension (encoded as an attribute).
9218   if (Expr *E = (Expr*) D.getAsmLabel()) {
9219     // The parser guarantees this is a string.
9220     StringLiteral *SE = cast<StringLiteral>(E);
9221     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9222                                         /*IsLiteralLabel=*/true,
9223                                         SE->getStrTokenLoc(0)));
9224   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9225     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9226       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9227     if (I != ExtnameUndeclaredIdentifiers.end()) {
9228       if (isDeclExternC(NewFD)) {
9229         NewFD->addAttr(I->second);
9230         ExtnameUndeclaredIdentifiers.erase(I);
9231       } else
9232         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9233             << /*Variable*/0 << NewFD;
9234     }
9235   }
9236 
9237   // Copy the parameter declarations from the declarator D to the function
9238   // declaration NewFD, if they are available.  First scavenge them into Params.
9239   SmallVector<ParmVarDecl*, 16> Params;
9240   unsigned FTIIdx;
9241   if (D.isFunctionDeclarator(FTIIdx)) {
9242     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9243 
9244     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9245     // function that takes no arguments, not a function that takes a
9246     // single void argument.
9247     // We let through "const void" here because Sema::GetTypeForDeclarator
9248     // already checks for that case.
9249     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9250       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9251         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9252         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9253         Param->setDeclContext(NewFD);
9254         Params.push_back(Param);
9255 
9256         if (Param->isInvalidDecl())
9257           NewFD->setInvalidDecl();
9258       }
9259     }
9260 
9261     if (!getLangOpts().CPlusPlus) {
9262       // In C, find all the tag declarations from the prototype and move them
9263       // into the function DeclContext. Remove them from the surrounding tag
9264       // injection context of the function, which is typically but not always
9265       // the TU.
9266       DeclContext *PrototypeTagContext =
9267           getTagInjectionContext(NewFD->getLexicalDeclContext());
9268       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9269         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9270 
9271         // We don't want to reparent enumerators. Look at their parent enum
9272         // instead.
9273         if (!TD) {
9274           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9275             TD = cast<EnumDecl>(ECD->getDeclContext());
9276         }
9277         if (!TD)
9278           continue;
9279         DeclContext *TagDC = TD->getLexicalDeclContext();
9280         if (!TagDC->containsDecl(TD))
9281           continue;
9282         TagDC->removeDecl(TD);
9283         TD->setDeclContext(NewFD);
9284         NewFD->addDecl(TD);
9285 
9286         // Preserve the lexical DeclContext if it is not the surrounding tag
9287         // injection context of the FD. In this example, the semantic context of
9288         // E will be f and the lexical context will be S, while both the
9289         // semantic and lexical contexts of S will be f:
9290         //   void f(struct S { enum E { a } f; } s);
9291         if (TagDC != PrototypeTagContext)
9292           TD->setLexicalDeclContext(TagDC);
9293       }
9294     }
9295   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9296     // When we're declaring a function with a typedef, typeof, etc as in the
9297     // following example, we'll need to synthesize (unnamed)
9298     // parameters for use in the declaration.
9299     //
9300     // @code
9301     // typedef void fn(int);
9302     // fn f;
9303     // @endcode
9304 
9305     // Synthesize a parameter for each argument type.
9306     for (const auto &AI : FT->param_types()) {
9307       ParmVarDecl *Param =
9308           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9309       Param->setScopeInfo(0, Params.size());
9310       Params.push_back(Param);
9311     }
9312   } else {
9313     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9314            "Should not need args for typedef of non-prototype fn");
9315   }
9316 
9317   // Finally, we know we have the right number of parameters, install them.
9318   NewFD->setParams(Params);
9319 
9320   if (D.getDeclSpec().isNoreturnSpecified())
9321     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9322                                            D.getDeclSpec().getNoreturnSpecLoc(),
9323                                            AttributeCommonInfo::AS_Keyword));
9324 
9325   // Functions returning a variably modified type violate C99 6.7.5.2p2
9326   // because all functions have linkage.
9327   if (!NewFD->isInvalidDecl() &&
9328       NewFD->getReturnType()->isVariablyModifiedType()) {
9329     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9330     NewFD->setInvalidDecl();
9331   }
9332 
9333   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9334   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9335       !NewFD->hasAttr<SectionAttr>())
9336     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9337         Context, PragmaClangTextSection.SectionName,
9338         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9339 
9340   // Apply an implicit SectionAttr if #pragma code_seg is active.
9341   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9342       !NewFD->hasAttr<SectionAttr>()) {
9343     NewFD->addAttr(SectionAttr::CreateImplicit(
9344         Context, CodeSegStack.CurrentValue->getString(),
9345         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9346         SectionAttr::Declspec_allocate));
9347     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9348                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9349                          ASTContext::PSF_Read,
9350                      NewFD))
9351       NewFD->dropAttr<SectionAttr>();
9352   }
9353 
9354   // Apply an implicit CodeSegAttr from class declspec or
9355   // apply an implicit SectionAttr from #pragma code_seg if active.
9356   if (!NewFD->hasAttr<CodeSegAttr>()) {
9357     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9358                                                                  D.isFunctionDefinition())) {
9359       NewFD->addAttr(SAttr);
9360     }
9361   }
9362 
9363   // Handle attributes.
9364   ProcessDeclAttributes(S, NewFD, D);
9365 
9366   if (getLangOpts().OpenCL) {
9367     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9368     // type declaration will generate a compilation error.
9369     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9370     if (AddressSpace != LangAS::Default) {
9371       Diag(NewFD->getLocation(),
9372            diag::err_opencl_return_value_with_address_space);
9373       NewFD->setInvalidDecl();
9374     }
9375   }
9376 
9377   if (!getLangOpts().CPlusPlus) {
9378     // Perform semantic checking on the function declaration.
9379     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9380       CheckMain(NewFD, D.getDeclSpec());
9381 
9382     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9383       CheckMSVCRTEntryPoint(NewFD);
9384 
9385     if (!NewFD->isInvalidDecl())
9386       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9387                                                   isMemberSpecialization));
9388     else if (!Previous.empty())
9389       // Recover gracefully from an invalid redeclaration.
9390       D.setRedeclaration(true);
9391     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9392             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9393            "previous declaration set still overloaded");
9394 
9395     // Diagnose no-prototype function declarations with calling conventions that
9396     // don't support variadic calls. Only do this in C and do it after merging
9397     // possibly prototyped redeclarations.
9398     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9399     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9400       CallingConv CC = FT->getExtInfo().getCC();
9401       if (!supportsVariadicCall(CC)) {
9402         // Windows system headers sometimes accidentally use stdcall without
9403         // (void) parameters, so we relax this to a warning.
9404         int DiagID =
9405             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9406         Diag(NewFD->getLocation(), DiagID)
9407             << FunctionType::getNameForCallConv(CC);
9408       }
9409     }
9410 
9411    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9412        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9413      checkNonTrivialCUnion(NewFD->getReturnType(),
9414                            NewFD->getReturnTypeSourceRange().getBegin(),
9415                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9416   } else {
9417     // C++11 [replacement.functions]p3:
9418     //  The program's definitions shall not be specified as inline.
9419     //
9420     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9421     //
9422     // Suppress the diagnostic if the function is __attribute__((used)), since
9423     // that forces an external definition to be emitted.
9424     if (D.getDeclSpec().isInlineSpecified() &&
9425         NewFD->isReplaceableGlobalAllocationFunction() &&
9426         !NewFD->hasAttr<UsedAttr>())
9427       Diag(D.getDeclSpec().getInlineSpecLoc(),
9428            diag::ext_operator_new_delete_declared_inline)
9429         << NewFD->getDeclName();
9430 
9431     // If the declarator is a template-id, translate the parser's template
9432     // argument list into our AST format.
9433     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9434       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9435       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9436       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9437       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9438                                          TemplateId->NumArgs);
9439       translateTemplateArguments(TemplateArgsPtr,
9440                                  TemplateArgs);
9441 
9442       HasExplicitTemplateArgs = true;
9443 
9444       if (NewFD->isInvalidDecl()) {
9445         HasExplicitTemplateArgs = false;
9446       } else if (FunctionTemplate) {
9447         // Function template with explicit template arguments.
9448         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9449           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9450 
9451         HasExplicitTemplateArgs = false;
9452       } else {
9453         assert((isFunctionTemplateSpecialization ||
9454                 D.getDeclSpec().isFriendSpecified()) &&
9455                "should have a 'template<>' for this decl");
9456         // "friend void foo<>(int);" is an implicit specialization decl.
9457         isFunctionTemplateSpecialization = true;
9458       }
9459     } else if (isFriend && isFunctionTemplateSpecialization) {
9460       // This combination is only possible in a recovery case;  the user
9461       // wrote something like:
9462       //   template <> friend void foo(int);
9463       // which we're recovering from as if the user had written:
9464       //   friend void foo<>(int);
9465       // Go ahead and fake up a template id.
9466       HasExplicitTemplateArgs = true;
9467       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9468       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9469     }
9470 
9471     // We do not add HD attributes to specializations here because
9472     // they may have different constexpr-ness compared to their
9473     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9474     // may end up with different effective targets. Instead, a
9475     // specialization inherits its target attributes from its template
9476     // in the CheckFunctionTemplateSpecialization() call below.
9477     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9478       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9479 
9480     // If it's a friend (and only if it's a friend), it's possible
9481     // that either the specialized function type or the specialized
9482     // template is dependent, and therefore matching will fail.  In
9483     // this case, don't check the specialization yet.
9484     bool InstantiationDependent = false;
9485     if (isFunctionTemplateSpecialization && isFriend &&
9486         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9487          TemplateSpecializationType::anyDependentTemplateArguments(
9488             TemplateArgs,
9489             InstantiationDependent))) {
9490       assert(HasExplicitTemplateArgs &&
9491              "friend function specialization without template args");
9492       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9493                                                        Previous))
9494         NewFD->setInvalidDecl();
9495     } else if (isFunctionTemplateSpecialization) {
9496       if (CurContext->isDependentContext() && CurContext->isRecord()
9497           && !isFriend) {
9498         isDependentClassScopeExplicitSpecialization = true;
9499       } else if (!NewFD->isInvalidDecl() &&
9500                  CheckFunctionTemplateSpecialization(
9501                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9502                      Previous))
9503         NewFD->setInvalidDecl();
9504 
9505       // C++ [dcl.stc]p1:
9506       //   A storage-class-specifier shall not be specified in an explicit
9507       //   specialization (14.7.3)
9508       FunctionTemplateSpecializationInfo *Info =
9509           NewFD->getTemplateSpecializationInfo();
9510       if (Info && SC != SC_None) {
9511         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9512           Diag(NewFD->getLocation(),
9513                diag::err_explicit_specialization_inconsistent_storage_class)
9514             << SC
9515             << FixItHint::CreateRemoval(
9516                                       D.getDeclSpec().getStorageClassSpecLoc());
9517 
9518         else
9519           Diag(NewFD->getLocation(),
9520                diag::ext_explicit_specialization_storage_class)
9521             << FixItHint::CreateRemoval(
9522                                       D.getDeclSpec().getStorageClassSpecLoc());
9523       }
9524     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9525       if (CheckMemberSpecialization(NewFD, Previous))
9526           NewFD->setInvalidDecl();
9527     }
9528 
9529     // Perform semantic checking on the function declaration.
9530     if (!isDependentClassScopeExplicitSpecialization) {
9531       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9532         CheckMain(NewFD, D.getDeclSpec());
9533 
9534       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9535         CheckMSVCRTEntryPoint(NewFD);
9536 
9537       if (!NewFD->isInvalidDecl())
9538         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9539                                                     isMemberSpecialization));
9540       else if (!Previous.empty())
9541         // Recover gracefully from an invalid redeclaration.
9542         D.setRedeclaration(true);
9543     }
9544 
9545     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9546             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9547            "previous declaration set still overloaded");
9548 
9549     NamedDecl *PrincipalDecl = (FunctionTemplate
9550                                 ? cast<NamedDecl>(FunctionTemplate)
9551                                 : NewFD);
9552 
9553     if (isFriend && NewFD->getPreviousDecl()) {
9554       AccessSpecifier Access = AS_public;
9555       if (!NewFD->isInvalidDecl())
9556         Access = NewFD->getPreviousDecl()->getAccess();
9557 
9558       NewFD->setAccess(Access);
9559       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9560     }
9561 
9562     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9563         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9564       PrincipalDecl->setNonMemberOperator();
9565 
9566     // If we have a function template, check the template parameter
9567     // list. This will check and merge default template arguments.
9568     if (FunctionTemplate) {
9569       FunctionTemplateDecl *PrevTemplate =
9570                                      FunctionTemplate->getPreviousDecl();
9571       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9572                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9573                                     : nullptr,
9574                             D.getDeclSpec().isFriendSpecified()
9575                               ? (D.isFunctionDefinition()
9576                                    ? TPC_FriendFunctionTemplateDefinition
9577                                    : TPC_FriendFunctionTemplate)
9578                               : (D.getCXXScopeSpec().isSet() &&
9579                                  DC && DC->isRecord() &&
9580                                  DC->isDependentContext())
9581                                   ? TPC_ClassTemplateMember
9582                                   : TPC_FunctionTemplate);
9583     }
9584 
9585     if (NewFD->isInvalidDecl()) {
9586       // Ignore all the rest of this.
9587     } else if (!D.isRedeclaration()) {
9588       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9589                                        AddToScope };
9590       // Fake up an access specifier if it's supposed to be a class member.
9591       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9592         NewFD->setAccess(AS_public);
9593 
9594       // Qualified decls generally require a previous declaration.
9595       if (D.getCXXScopeSpec().isSet()) {
9596         // ...with the major exception of templated-scope or
9597         // dependent-scope friend declarations.
9598 
9599         // TODO: we currently also suppress this check in dependent
9600         // contexts because (1) the parameter depth will be off when
9601         // matching friend templates and (2) we might actually be
9602         // selecting a friend based on a dependent factor.  But there
9603         // are situations where these conditions don't apply and we
9604         // can actually do this check immediately.
9605         //
9606         // Unless the scope is dependent, it's always an error if qualified
9607         // redeclaration lookup found nothing at all. Diagnose that now;
9608         // nothing will diagnose that error later.
9609         if (isFriend &&
9610             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9611              (!Previous.empty() && CurContext->isDependentContext()))) {
9612           // ignore these
9613         } else {
9614           // The user tried to provide an out-of-line definition for a
9615           // function that is a member of a class or namespace, but there
9616           // was no such member function declared (C++ [class.mfct]p2,
9617           // C++ [namespace.memdef]p2). For example:
9618           //
9619           // class X {
9620           //   void f() const;
9621           // };
9622           //
9623           // void X::f() { } // ill-formed
9624           //
9625           // Complain about this problem, and attempt to suggest close
9626           // matches (e.g., those that differ only in cv-qualifiers and
9627           // whether the parameter types are references).
9628 
9629           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9630                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9631             AddToScope = ExtraArgs.AddToScope;
9632             return Result;
9633           }
9634         }
9635 
9636         // Unqualified local friend declarations are required to resolve
9637         // to something.
9638       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9639         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9640                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9641           AddToScope = ExtraArgs.AddToScope;
9642           return Result;
9643         }
9644       }
9645     } else if (!D.isFunctionDefinition() &&
9646                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9647                !isFriend && !isFunctionTemplateSpecialization &&
9648                !isMemberSpecialization) {
9649       // An out-of-line member function declaration must also be a
9650       // definition (C++ [class.mfct]p2).
9651       // Note that this is not the case for explicit specializations of
9652       // function templates or member functions of class templates, per
9653       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9654       // extension for compatibility with old SWIG code which likes to
9655       // generate them.
9656       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9657         << D.getCXXScopeSpec().getRange();
9658     }
9659   }
9660 
9661   // In C builtins get merged with implicitly lazily created declarations.
9662   // In C++ we need to check if it's a builtin and add the BuiltinAttr here.
9663   if (getLangOpts().CPlusPlus) {
9664     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9665       if (unsigned BuiltinID = II->getBuiltinID()) {
9666         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9667           // Declarations for builtins with custom typechecking by definition
9668           // don't make sense. Don't attempt typechecking and simply add the
9669           // attribute.
9670           if (Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
9671             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9672           } else {
9673             ASTContext::GetBuiltinTypeError Error;
9674             LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9675             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9676 
9677             if (!Error && !BuiltinType.isNull() &&
9678                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9679                     NewFD->getType(), BuiltinType))
9680               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9681           }
9682         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9683                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9684           // FIXME: We should consider this a builtin only in the std namespace.
9685           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9686         }
9687       }
9688     }
9689   }
9690 
9691   ProcessPragmaWeak(S, NewFD);
9692   checkAttributesAfterMerging(*this, *NewFD);
9693 
9694   AddKnownFunctionAttributes(NewFD);
9695 
9696   if (NewFD->hasAttr<OverloadableAttr>() &&
9697       !NewFD->getType()->getAs<FunctionProtoType>()) {
9698     Diag(NewFD->getLocation(),
9699          diag::err_attribute_overloadable_no_prototype)
9700       << NewFD;
9701 
9702     // Turn this into a variadic function with no parameters.
9703     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9704     FunctionProtoType::ExtProtoInfo EPI(
9705         Context.getDefaultCallingConvention(true, false));
9706     EPI.Variadic = true;
9707     EPI.ExtInfo = FT->getExtInfo();
9708 
9709     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9710     NewFD->setType(R);
9711   }
9712 
9713   // If there's a #pragma GCC visibility in scope, and this isn't a class
9714   // member, set the visibility of this function.
9715   if (!DC->isRecord() && NewFD->isExternallyVisible())
9716     AddPushedVisibilityAttribute(NewFD);
9717 
9718   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9719   // marking the function.
9720   AddCFAuditedAttribute(NewFD);
9721 
9722   // If this is a function definition, check if we have to apply optnone due to
9723   // a pragma.
9724   if(D.isFunctionDefinition())
9725     AddRangeBasedOptnone(NewFD);
9726 
9727   // If this is the first declaration of an extern C variable, update
9728   // the map of such variables.
9729   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9730       isIncompleteDeclExternC(*this, NewFD))
9731     RegisterLocallyScopedExternCDecl(NewFD, S);
9732 
9733   // Set this FunctionDecl's range up to the right paren.
9734   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9735 
9736   if (D.isRedeclaration() && !Previous.empty()) {
9737     NamedDecl *Prev = Previous.getRepresentativeDecl();
9738     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9739                                    isMemberSpecialization ||
9740                                        isFunctionTemplateSpecialization,
9741                                    D.isFunctionDefinition());
9742   }
9743 
9744   if (getLangOpts().CUDA) {
9745     IdentifierInfo *II = NewFD->getIdentifier();
9746     if (II && II->isStr(getCudaConfigureFuncName()) &&
9747         !NewFD->isInvalidDecl() &&
9748         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9749       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9750         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9751             << getCudaConfigureFuncName();
9752       Context.setcudaConfigureCallDecl(NewFD);
9753     }
9754 
9755     // Variadic functions, other than a *declaration* of printf, are not allowed
9756     // in device-side CUDA code, unless someone passed
9757     // -fcuda-allow-variadic-functions.
9758     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9759         (NewFD->hasAttr<CUDADeviceAttr>() ||
9760          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9761         !(II && II->isStr("printf") && NewFD->isExternC() &&
9762           !D.isFunctionDefinition())) {
9763       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9764     }
9765   }
9766 
9767   MarkUnusedFileScopedDecl(NewFD);
9768 
9769 
9770 
9771   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9772     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9773     if ((getLangOpts().OpenCLVersion >= 120)
9774         && (SC == SC_Static)) {
9775       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9776       D.setInvalidType();
9777     }
9778 
9779     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9780     if (!NewFD->getReturnType()->isVoidType()) {
9781       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9782       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9783           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9784                                 : FixItHint());
9785       D.setInvalidType();
9786     }
9787 
9788     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9789     for (auto Param : NewFD->parameters())
9790       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9791 
9792     if (getLangOpts().OpenCLCPlusPlus) {
9793       if (DC->isRecord()) {
9794         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9795         D.setInvalidType();
9796       }
9797       if (FunctionTemplate) {
9798         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9799         D.setInvalidType();
9800       }
9801     }
9802   }
9803 
9804   if (getLangOpts().CPlusPlus) {
9805     if (FunctionTemplate) {
9806       if (NewFD->isInvalidDecl())
9807         FunctionTemplate->setInvalidDecl();
9808       return FunctionTemplate;
9809     }
9810 
9811     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9812       CompleteMemberSpecialization(NewFD, Previous);
9813   }
9814 
9815   for (const ParmVarDecl *Param : NewFD->parameters()) {
9816     QualType PT = Param->getType();
9817 
9818     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9819     // types.
9820     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9821       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9822         QualType ElemTy = PipeTy->getElementType();
9823           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9824             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9825             D.setInvalidType();
9826           }
9827       }
9828     }
9829   }
9830 
9831   // Here we have an function template explicit specialization at class scope.
9832   // The actual specialization will be postponed to template instatiation
9833   // time via the ClassScopeFunctionSpecializationDecl node.
9834   if (isDependentClassScopeExplicitSpecialization) {
9835     ClassScopeFunctionSpecializationDecl *NewSpec =
9836                          ClassScopeFunctionSpecializationDecl::Create(
9837                                 Context, CurContext, NewFD->getLocation(),
9838                                 cast<CXXMethodDecl>(NewFD),
9839                                 HasExplicitTemplateArgs, TemplateArgs);
9840     CurContext->addDecl(NewSpec);
9841     AddToScope = false;
9842   }
9843 
9844   // Diagnose availability attributes. Availability cannot be used on functions
9845   // that are run during load/unload.
9846   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9847     if (NewFD->hasAttr<ConstructorAttr>()) {
9848       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9849           << 1;
9850       NewFD->dropAttr<AvailabilityAttr>();
9851     }
9852     if (NewFD->hasAttr<DestructorAttr>()) {
9853       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9854           << 2;
9855       NewFD->dropAttr<AvailabilityAttr>();
9856     }
9857   }
9858 
9859   // Diagnose no_builtin attribute on function declaration that are not a
9860   // definition.
9861   // FIXME: We should really be doing this in
9862   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9863   // the FunctionDecl and at this point of the code
9864   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9865   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9866   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9867     switch (D.getFunctionDefinitionKind()) {
9868     case FDK_Defaulted:
9869     case FDK_Deleted:
9870       Diag(NBA->getLocation(),
9871            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9872           << NBA->getSpelling();
9873       break;
9874     case FDK_Declaration:
9875       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9876           << NBA->getSpelling();
9877       break;
9878     case FDK_Definition:
9879       break;
9880     }
9881 
9882   return NewFD;
9883 }
9884 
9885 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9886 /// when __declspec(code_seg) "is applied to a class, all member functions of
9887 /// the class and nested classes -- this includes compiler-generated special
9888 /// member functions -- are put in the specified segment."
9889 /// The actual behavior is a little more complicated. The Microsoft compiler
9890 /// won't check outer classes if there is an active value from #pragma code_seg.
9891 /// The CodeSeg is always applied from the direct parent but only from outer
9892 /// classes when the #pragma code_seg stack is empty. See:
9893 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9894 /// available since MS has removed the page.
9895 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9896   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9897   if (!Method)
9898     return nullptr;
9899   const CXXRecordDecl *Parent = Method->getParent();
9900   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9901     Attr *NewAttr = SAttr->clone(S.getASTContext());
9902     NewAttr->setImplicit(true);
9903     return NewAttr;
9904   }
9905 
9906   // The Microsoft compiler won't check outer classes for the CodeSeg
9907   // when the #pragma code_seg stack is active.
9908   if (S.CodeSegStack.CurrentValue)
9909    return nullptr;
9910 
9911   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9912     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9913       Attr *NewAttr = SAttr->clone(S.getASTContext());
9914       NewAttr->setImplicit(true);
9915       return NewAttr;
9916     }
9917   }
9918   return nullptr;
9919 }
9920 
9921 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9922 /// containing class. Otherwise it will return implicit SectionAttr if the
9923 /// function is a definition and there is an active value on CodeSegStack
9924 /// (from the current #pragma code-seg value).
9925 ///
9926 /// \param FD Function being declared.
9927 /// \param IsDefinition Whether it is a definition or just a declarartion.
9928 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9929 ///          nullptr if no attribute should be added.
9930 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9931                                                        bool IsDefinition) {
9932   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9933     return A;
9934   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9935       CodeSegStack.CurrentValue)
9936     return SectionAttr::CreateImplicit(
9937         getASTContext(), CodeSegStack.CurrentValue->getString(),
9938         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9939         SectionAttr::Declspec_allocate);
9940   return nullptr;
9941 }
9942 
9943 /// Determines if we can perform a correct type check for \p D as a
9944 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9945 /// best-effort check.
9946 ///
9947 /// \param NewD The new declaration.
9948 /// \param OldD The old declaration.
9949 /// \param NewT The portion of the type of the new declaration to check.
9950 /// \param OldT The portion of the type of the old declaration to check.
9951 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9952                                           QualType NewT, QualType OldT) {
9953   if (!NewD->getLexicalDeclContext()->isDependentContext())
9954     return true;
9955 
9956   // For dependently-typed local extern declarations and friends, we can't
9957   // perform a correct type check in general until instantiation:
9958   //
9959   //   int f();
9960   //   template<typename T> void g() { T f(); }
9961   //
9962   // (valid if g() is only instantiated with T = int).
9963   if (NewT->isDependentType() &&
9964       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9965     return false;
9966 
9967   // Similarly, if the previous declaration was a dependent local extern
9968   // declaration, we don't really know its type yet.
9969   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9970     return false;
9971 
9972   return true;
9973 }
9974 
9975 /// Checks if the new declaration declared in dependent context must be
9976 /// put in the same redeclaration chain as the specified declaration.
9977 ///
9978 /// \param D Declaration that is checked.
9979 /// \param PrevDecl Previous declaration found with proper lookup method for the
9980 ///                 same declaration name.
9981 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9982 ///          belongs to.
9983 ///
9984 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9985   if (!D->getLexicalDeclContext()->isDependentContext())
9986     return true;
9987 
9988   // Don't chain dependent friend function definitions until instantiation, to
9989   // permit cases like
9990   //
9991   //   void func();
9992   //   template<typename T> class C1 { friend void func() {} };
9993   //   template<typename T> class C2 { friend void func() {} };
9994   //
9995   // ... which is valid if only one of C1 and C2 is ever instantiated.
9996   //
9997   // FIXME: This need only apply to function definitions. For now, we proxy
9998   // this by checking for a file-scope function. We do not want this to apply
9999   // to friend declarations nominating member functions, because that gets in
10000   // the way of access checks.
10001   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10002     return false;
10003 
10004   auto *VD = dyn_cast<ValueDecl>(D);
10005   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10006   return !VD || !PrevVD ||
10007          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10008                                         PrevVD->getType());
10009 }
10010 
10011 /// Check the target attribute of the function for MultiVersion
10012 /// validity.
10013 ///
10014 /// Returns true if there was an error, false otherwise.
10015 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10016   const auto *TA = FD->getAttr<TargetAttr>();
10017   assert(TA && "MultiVersion Candidate requires a target attribute");
10018   ParsedTargetAttr ParseInfo = TA->parse();
10019   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10020   enum ErrType { Feature = 0, Architecture = 1 };
10021 
10022   if (!ParseInfo.Architecture.empty() &&
10023       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10024     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10025         << Architecture << ParseInfo.Architecture;
10026     return true;
10027   }
10028 
10029   for (const auto &Feat : ParseInfo.Features) {
10030     auto BareFeat = StringRef{Feat}.substr(1);
10031     if (Feat[0] == '-') {
10032       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10033           << Feature << ("no-" + BareFeat).str();
10034       return true;
10035     }
10036 
10037     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10038         !TargetInfo.isValidFeatureName(BareFeat)) {
10039       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10040           << Feature << BareFeat;
10041       return true;
10042     }
10043   }
10044   return false;
10045 }
10046 
10047 // Provide a white-list of attributes that are allowed to be combined with
10048 // multiversion functions.
10049 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10050                                            MultiVersionKind MVType) {
10051   // Note: this list/diagnosis must match the list in
10052   // checkMultiversionAttributesAllSame.
10053   switch (Kind) {
10054   default:
10055     return false;
10056   case attr::Used:
10057     return MVType == MultiVersionKind::Target;
10058   case attr::NonNull:
10059   case attr::NoThrow:
10060     return true;
10061   }
10062 }
10063 
10064 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10065                                                  const FunctionDecl *FD,
10066                                                  const FunctionDecl *CausedFD,
10067                                                  MultiVersionKind MVType) {
10068   bool IsCPUSpecificCPUDispatchMVType =
10069       MVType == MultiVersionKind::CPUDispatch ||
10070       MVType == MultiVersionKind::CPUSpecific;
10071   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10072                             Sema &S, const Attr *A) {
10073     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10074         << IsCPUSpecificCPUDispatchMVType << A;
10075     if (CausedFD)
10076       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10077     return true;
10078   };
10079 
10080   for (const Attr *A : FD->attrs()) {
10081     switch (A->getKind()) {
10082     case attr::CPUDispatch:
10083     case attr::CPUSpecific:
10084       if (MVType != MultiVersionKind::CPUDispatch &&
10085           MVType != MultiVersionKind::CPUSpecific)
10086         return Diagnose(S, A);
10087       break;
10088     case attr::Target:
10089       if (MVType != MultiVersionKind::Target)
10090         return Diagnose(S, A);
10091       break;
10092     default:
10093       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10094         return Diagnose(S, A);
10095       break;
10096     }
10097   }
10098   return false;
10099 }
10100 
10101 bool Sema::areMultiversionVariantFunctionsCompatible(
10102     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10103     const PartialDiagnostic &NoProtoDiagID,
10104     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10105     const PartialDiagnosticAt &NoSupportDiagIDAt,
10106     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10107     bool ConstexprSupported, bool CLinkageMayDiffer) {
10108   enum DoesntSupport {
10109     FuncTemplates = 0,
10110     VirtFuncs = 1,
10111     DeducedReturn = 2,
10112     Constructors = 3,
10113     Destructors = 4,
10114     DeletedFuncs = 5,
10115     DefaultedFuncs = 6,
10116     ConstexprFuncs = 7,
10117     ConstevalFuncs = 8,
10118   };
10119   enum Different {
10120     CallingConv = 0,
10121     ReturnType = 1,
10122     ConstexprSpec = 2,
10123     InlineSpec = 3,
10124     StorageClass = 4,
10125     Linkage = 5,
10126   };
10127 
10128   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10129       !OldFD->getType()->getAs<FunctionProtoType>()) {
10130     Diag(OldFD->getLocation(), NoProtoDiagID);
10131     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10132     return true;
10133   }
10134 
10135   if (NoProtoDiagID.getDiagID() != 0 &&
10136       !NewFD->getType()->getAs<FunctionProtoType>())
10137     return Diag(NewFD->getLocation(), NoProtoDiagID);
10138 
10139   if (!TemplatesSupported &&
10140       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10141     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10142            << FuncTemplates;
10143 
10144   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10145     if (NewCXXFD->isVirtual())
10146       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10147              << VirtFuncs;
10148 
10149     if (isa<CXXConstructorDecl>(NewCXXFD))
10150       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10151              << Constructors;
10152 
10153     if (isa<CXXDestructorDecl>(NewCXXFD))
10154       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10155              << Destructors;
10156   }
10157 
10158   if (NewFD->isDeleted())
10159     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10160            << DeletedFuncs;
10161 
10162   if (NewFD->isDefaulted())
10163     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10164            << DefaultedFuncs;
10165 
10166   if (!ConstexprSupported && NewFD->isConstexpr())
10167     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10168            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10169 
10170   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10171   const auto *NewType = cast<FunctionType>(NewQType);
10172   QualType NewReturnType = NewType->getReturnType();
10173 
10174   if (NewReturnType->isUndeducedType())
10175     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10176            << DeducedReturn;
10177 
10178   // Ensure the return type is identical.
10179   if (OldFD) {
10180     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10181     const auto *OldType = cast<FunctionType>(OldQType);
10182     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10183     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10184 
10185     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10186       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10187 
10188     QualType OldReturnType = OldType->getReturnType();
10189 
10190     if (OldReturnType != NewReturnType)
10191       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10192 
10193     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10194       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10195 
10196     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10197       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10198 
10199     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10200       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10201 
10202     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10203       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10204 
10205     if (CheckEquivalentExceptionSpec(
10206             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10207             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10208       return true;
10209   }
10210   return false;
10211 }
10212 
10213 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10214                                              const FunctionDecl *NewFD,
10215                                              bool CausesMV,
10216                                              MultiVersionKind MVType) {
10217   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10218     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10219     if (OldFD)
10220       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10221     return true;
10222   }
10223 
10224   bool IsCPUSpecificCPUDispatchMVType =
10225       MVType == MultiVersionKind::CPUDispatch ||
10226       MVType == MultiVersionKind::CPUSpecific;
10227 
10228   if (CausesMV && OldFD &&
10229       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10230     return true;
10231 
10232   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10233     return true;
10234 
10235   // Only allow transition to MultiVersion if it hasn't been used.
10236   if (OldFD && CausesMV && OldFD->isUsed(false))
10237     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10238 
10239   return S.areMultiversionVariantFunctionsCompatible(
10240       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10241       PartialDiagnosticAt(NewFD->getLocation(),
10242                           S.PDiag(diag::note_multiversioning_caused_here)),
10243       PartialDiagnosticAt(NewFD->getLocation(),
10244                           S.PDiag(diag::err_multiversion_doesnt_support)
10245                               << IsCPUSpecificCPUDispatchMVType),
10246       PartialDiagnosticAt(NewFD->getLocation(),
10247                           S.PDiag(diag::err_multiversion_diff)),
10248       /*TemplatesSupported=*/false,
10249       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10250       /*CLinkageMayDiffer=*/false);
10251 }
10252 
10253 /// Check the validity of a multiversion function declaration that is the
10254 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10255 ///
10256 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10257 ///
10258 /// Returns true if there was an error, false otherwise.
10259 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10260                                            MultiVersionKind MVType,
10261                                            const TargetAttr *TA) {
10262   assert(MVType != MultiVersionKind::None &&
10263          "Function lacks multiversion attribute");
10264 
10265   // Target only causes MV if it is default, otherwise this is a normal
10266   // function.
10267   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10268     return false;
10269 
10270   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10271     FD->setInvalidDecl();
10272     return true;
10273   }
10274 
10275   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10276     FD->setInvalidDecl();
10277     return true;
10278   }
10279 
10280   FD->setIsMultiVersion();
10281   return false;
10282 }
10283 
10284 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10285   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10286     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10287       return true;
10288   }
10289 
10290   return false;
10291 }
10292 
10293 static bool CheckTargetCausesMultiVersioning(
10294     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10295     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10296     LookupResult &Previous) {
10297   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10298   ParsedTargetAttr NewParsed = NewTA->parse();
10299   // Sort order doesn't matter, it just needs to be consistent.
10300   llvm::sort(NewParsed.Features);
10301 
10302   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10303   // to change, this is a simple redeclaration.
10304   if (!NewTA->isDefaultVersion() &&
10305       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10306     return false;
10307 
10308   // Otherwise, this decl causes MultiVersioning.
10309   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10310     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10311     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10312     NewFD->setInvalidDecl();
10313     return true;
10314   }
10315 
10316   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10317                                        MultiVersionKind::Target)) {
10318     NewFD->setInvalidDecl();
10319     return true;
10320   }
10321 
10322   if (CheckMultiVersionValue(S, NewFD)) {
10323     NewFD->setInvalidDecl();
10324     return true;
10325   }
10326 
10327   // If this is 'default', permit the forward declaration.
10328   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10329     Redeclaration = true;
10330     OldDecl = OldFD;
10331     OldFD->setIsMultiVersion();
10332     NewFD->setIsMultiVersion();
10333     return false;
10334   }
10335 
10336   if (CheckMultiVersionValue(S, OldFD)) {
10337     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10338     NewFD->setInvalidDecl();
10339     return true;
10340   }
10341 
10342   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10343 
10344   if (OldParsed == NewParsed) {
10345     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10346     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10347     NewFD->setInvalidDecl();
10348     return true;
10349   }
10350 
10351   for (const auto *FD : OldFD->redecls()) {
10352     const auto *CurTA = FD->getAttr<TargetAttr>();
10353     // We allow forward declarations before ANY multiversioning attributes, but
10354     // nothing after the fact.
10355     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10356         (!CurTA || CurTA->isInherited())) {
10357       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10358           << 0;
10359       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10360       NewFD->setInvalidDecl();
10361       return true;
10362     }
10363   }
10364 
10365   OldFD->setIsMultiVersion();
10366   NewFD->setIsMultiVersion();
10367   Redeclaration = false;
10368   MergeTypeWithPrevious = false;
10369   OldDecl = nullptr;
10370   Previous.clear();
10371   return false;
10372 }
10373 
10374 /// Check the validity of a new function declaration being added to an existing
10375 /// multiversioned declaration collection.
10376 static bool CheckMultiVersionAdditionalDecl(
10377     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10378     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10379     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10380     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10381     LookupResult &Previous) {
10382 
10383   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10384   // Disallow mixing of multiversioning types.
10385   if ((OldMVType == MultiVersionKind::Target &&
10386        NewMVType != MultiVersionKind::Target) ||
10387       (NewMVType == MultiVersionKind::Target &&
10388        OldMVType != MultiVersionKind::Target)) {
10389     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10390     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10391     NewFD->setInvalidDecl();
10392     return true;
10393   }
10394 
10395   ParsedTargetAttr NewParsed;
10396   if (NewTA) {
10397     NewParsed = NewTA->parse();
10398     llvm::sort(NewParsed.Features);
10399   }
10400 
10401   bool UseMemberUsingDeclRules =
10402       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10403 
10404   // Next, check ALL non-overloads to see if this is a redeclaration of a
10405   // previous member of the MultiVersion set.
10406   for (NamedDecl *ND : Previous) {
10407     FunctionDecl *CurFD = ND->getAsFunction();
10408     if (!CurFD)
10409       continue;
10410     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10411       continue;
10412 
10413     if (NewMVType == MultiVersionKind::Target) {
10414       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10415       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10416         NewFD->setIsMultiVersion();
10417         Redeclaration = true;
10418         OldDecl = ND;
10419         return false;
10420       }
10421 
10422       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10423       if (CurParsed == NewParsed) {
10424         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10425         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10426         NewFD->setInvalidDecl();
10427         return true;
10428       }
10429     } else {
10430       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10431       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10432       // Handle CPUDispatch/CPUSpecific versions.
10433       // Only 1 CPUDispatch function is allowed, this will make it go through
10434       // the redeclaration errors.
10435       if (NewMVType == MultiVersionKind::CPUDispatch &&
10436           CurFD->hasAttr<CPUDispatchAttr>()) {
10437         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10438             std::equal(
10439                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10440                 NewCPUDisp->cpus_begin(),
10441                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10442                   return Cur->getName() == New->getName();
10443                 })) {
10444           NewFD->setIsMultiVersion();
10445           Redeclaration = true;
10446           OldDecl = ND;
10447           return false;
10448         }
10449 
10450         // If the declarations don't match, this is an error condition.
10451         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10452         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10453         NewFD->setInvalidDecl();
10454         return true;
10455       }
10456       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10457 
10458         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10459             std::equal(
10460                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10461                 NewCPUSpec->cpus_begin(),
10462                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10463                   return Cur->getName() == New->getName();
10464                 })) {
10465           NewFD->setIsMultiVersion();
10466           Redeclaration = true;
10467           OldDecl = ND;
10468           return false;
10469         }
10470 
10471         // Only 1 version of CPUSpecific is allowed for each CPU.
10472         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10473           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10474             if (CurII == NewII) {
10475               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10476                   << NewII;
10477               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10478               NewFD->setInvalidDecl();
10479               return true;
10480             }
10481           }
10482         }
10483       }
10484       // If the two decls aren't the same MVType, there is no possible error
10485       // condition.
10486     }
10487   }
10488 
10489   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10490   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10491   // handled in the attribute adding step.
10492   if (NewMVType == MultiVersionKind::Target &&
10493       CheckMultiVersionValue(S, NewFD)) {
10494     NewFD->setInvalidDecl();
10495     return true;
10496   }
10497 
10498   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10499                                        !OldFD->isMultiVersion(), NewMVType)) {
10500     NewFD->setInvalidDecl();
10501     return true;
10502   }
10503 
10504   // Permit forward declarations in the case where these two are compatible.
10505   if (!OldFD->isMultiVersion()) {
10506     OldFD->setIsMultiVersion();
10507     NewFD->setIsMultiVersion();
10508     Redeclaration = true;
10509     OldDecl = OldFD;
10510     return false;
10511   }
10512 
10513   NewFD->setIsMultiVersion();
10514   Redeclaration = false;
10515   MergeTypeWithPrevious = false;
10516   OldDecl = nullptr;
10517   Previous.clear();
10518   return false;
10519 }
10520 
10521 
10522 /// Check the validity of a mulitversion function declaration.
10523 /// Also sets the multiversion'ness' of the function itself.
10524 ///
10525 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10526 ///
10527 /// Returns true if there was an error, false otherwise.
10528 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10529                                       bool &Redeclaration, NamedDecl *&OldDecl,
10530                                       bool &MergeTypeWithPrevious,
10531                                       LookupResult &Previous) {
10532   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10533   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10534   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10535 
10536   // Mixing Multiversioning types is prohibited.
10537   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10538       (NewCPUDisp && NewCPUSpec)) {
10539     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10540     NewFD->setInvalidDecl();
10541     return true;
10542   }
10543 
10544   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10545 
10546   // Main isn't allowed to become a multiversion function, however it IS
10547   // permitted to have 'main' be marked with the 'target' optimization hint.
10548   if (NewFD->isMain()) {
10549     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10550         MVType == MultiVersionKind::CPUDispatch ||
10551         MVType == MultiVersionKind::CPUSpecific) {
10552       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10553       NewFD->setInvalidDecl();
10554       return true;
10555     }
10556     return false;
10557   }
10558 
10559   if (!OldDecl || !OldDecl->getAsFunction() ||
10560       OldDecl->getDeclContext()->getRedeclContext() !=
10561           NewFD->getDeclContext()->getRedeclContext()) {
10562     // If there's no previous declaration, AND this isn't attempting to cause
10563     // multiversioning, this isn't an error condition.
10564     if (MVType == MultiVersionKind::None)
10565       return false;
10566     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10567   }
10568 
10569   FunctionDecl *OldFD = OldDecl->getAsFunction();
10570 
10571   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10572     return false;
10573 
10574   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10575     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10576         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10577     NewFD->setInvalidDecl();
10578     return true;
10579   }
10580 
10581   // Handle the target potentially causes multiversioning case.
10582   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10583     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10584                                             Redeclaration, OldDecl,
10585                                             MergeTypeWithPrevious, Previous);
10586 
10587   // At this point, we have a multiversion function decl (in OldFD) AND an
10588   // appropriate attribute in the current function decl.  Resolve that these are
10589   // still compatible with previous declarations.
10590   return CheckMultiVersionAdditionalDecl(
10591       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10592       OldDecl, MergeTypeWithPrevious, Previous);
10593 }
10594 
10595 /// Perform semantic checking of a new function declaration.
10596 ///
10597 /// Performs semantic analysis of the new function declaration
10598 /// NewFD. This routine performs all semantic checking that does not
10599 /// require the actual declarator involved in the declaration, and is
10600 /// used both for the declaration of functions as they are parsed
10601 /// (called via ActOnDeclarator) and for the declaration of functions
10602 /// that have been instantiated via C++ template instantiation (called
10603 /// via InstantiateDecl).
10604 ///
10605 /// \param IsMemberSpecialization whether this new function declaration is
10606 /// a member specialization (that replaces any definition provided by the
10607 /// previous declaration).
10608 ///
10609 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10610 ///
10611 /// \returns true if the function declaration is a redeclaration.
10612 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10613                                     LookupResult &Previous,
10614                                     bool IsMemberSpecialization) {
10615   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10616          "Variably modified return types are not handled here");
10617 
10618   // Determine whether the type of this function should be merged with
10619   // a previous visible declaration. This never happens for functions in C++,
10620   // and always happens in C if the previous declaration was visible.
10621   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10622                                !Previous.isShadowed();
10623 
10624   bool Redeclaration = false;
10625   NamedDecl *OldDecl = nullptr;
10626   bool MayNeedOverloadableChecks = false;
10627 
10628   // Merge or overload the declaration with an existing declaration of
10629   // the same name, if appropriate.
10630   if (!Previous.empty()) {
10631     // Determine whether NewFD is an overload of PrevDecl or
10632     // a declaration that requires merging. If it's an overload,
10633     // there's no more work to do here; we'll just add the new
10634     // function to the scope.
10635     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10636       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10637       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10638         Redeclaration = true;
10639         OldDecl = Candidate;
10640       }
10641     } else {
10642       MayNeedOverloadableChecks = true;
10643       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10644                             /*NewIsUsingDecl*/ false)) {
10645       case Ovl_Match:
10646         Redeclaration = true;
10647         break;
10648 
10649       case Ovl_NonFunction:
10650         Redeclaration = true;
10651         break;
10652 
10653       case Ovl_Overload:
10654         Redeclaration = false;
10655         break;
10656       }
10657     }
10658   }
10659 
10660   // Check for a previous extern "C" declaration with this name.
10661   if (!Redeclaration &&
10662       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10663     if (!Previous.empty()) {
10664       // This is an extern "C" declaration with the same name as a previous
10665       // declaration, and thus redeclares that entity...
10666       Redeclaration = true;
10667       OldDecl = Previous.getFoundDecl();
10668       MergeTypeWithPrevious = false;
10669 
10670       // ... except in the presence of __attribute__((overloadable)).
10671       if (OldDecl->hasAttr<OverloadableAttr>() ||
10672           NewFD->hasAttr<OverloadableAttr>()) {
10673         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10674           MayNeedOverloadableChecks = true;
10675           Redeclaration = false;
10676           OldDecl = nullptr;
10677         }
10678       }
10679     }
10680   }
10681 
10682   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10683                                 MergeTypeWithPrevious, Previous))
10684     return Redeclaration;
10685 
10686   // C++11 [dcl.constexpr]p8:
10687   //   A constexpr specifier for a non-static member function that is not
10688   //   a constructor declares that member function to be const.
10689   //
10690   // This needs to be delayed until we know whether this is an out-of-line
10691   // definition of a static member function.
10692   //
10693   // This rule is not present in C++1y, so we produce a backwards
10694   // compatibility warning whenever it happens in C++11.
10695   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10696   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10697       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10698       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10699     CXXMethodDecl *OldMD = nullptr;
10700     if (OldDecl)
10701       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10702     if (!OldMD || !OldMD->isStatic()) {
10703       const FunctionProtoType *FPT =
10704         MD->getType()->castAs<FunctionProtoType>();
10705       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10706       EPI.TypeQuals.addConst();
10707       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10708                                           FPT->getParamTypes(), EPI));
10709 
10710       // Warn that we did this, if we're not performing template instantiation.
10711       // In that case, we'll have warned already when the template was defined.
10712       if (!inTemplateInstantiation()) {
10713         SourceLocation AddConstLoc;
10714         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10715                 .IgnoreParens().getAs<FunctionTypeLoc>())
10716           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10717 
10718         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10719           << FixItHint::CreateInsertion(AddConstLoc, " const");
10720       }
10721     }
10722   }
10723 
10724   if (Redeclaration) {
10725     // NewFD and OldDecl represent declarations that need to be
10726     // merged.
10727     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10728       NewFD->setInvalidDecl();
10729       return Redeclaration;
10730     }
10731 
10732     Previous.clear();
10733     Previous.addDecl(OldDecl);
10734 
10735     if (FunctionTemplateDecl *OldTemplateDecl =
10736             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10737       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10738       FunctionTemplateDecl *NewTemplateDecl
10739         = NewFD->getDescribedFunctionTemplate();
10740       assert(NewTemplateDecl && "Template/non-template mismatch");
10741 
10742       // The call to MergeFunctionDecl above may have created some state in
10743       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10744       // can add it as a redeclaration.
10745       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10746 
10747       NewFD->setPreviousDeclaration(OldFD);
10748       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10749       if (NewFD->isCXXClassMember()) {
10750         NewFD->setAccess(OldTemplateDecl->getAccess());
10751         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10752       }
10753 
10754       // If this is an explicit specialization of a member that is a function
10755       // template, mark it as a member specialization.
10756       if (IsMemberSpecialization &&
10757           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10758         NewTemplateDecl->setMemberSpecialization();
10759         assert(OldTemplateDecl->isMemberSpecialization());
10760         // Explicit specializations of a member template do not inherit deleted
10761         // status from the parent member template that they are specializing.
10762         if (OldFD->isDeleted()) {
10763           // FIXME: This assert will not hold in the presence of modules.
10764           assert(OldFD->getCanonicalDecl() == OldFD);
10765           // FIXME: We need an update record for this AST mutation.
10766           OldFD->setDeletedAsWritten(false);
10767         }
10768       }
10769 
10770     } else {
10771       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10772         auto *OldFD = cast<FunctionDecl>(OldDecl);
10773         // This needs to happen first so that 'inline' propagates.
10774         NewFD->setPreviousDeclaration(OldFD);
10775         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10776         if (NewFD->isCXXClassMember())
10777           NewFD->setAccess(OldFD->getAccess());
10778       }
10779     }
10780   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10781              !NewFD->getAttr<OverloadableAttr>()) {
10782     assert((Previous.empty() ||
10783             llvm::any_of(Previous,
10784                          [](const NamedDecl *ND) {
10785                            return ND->hasAttr<OverloadableAttr>();
10786                          })) &&
10787            "Non-redecls shouldn't happen without overloadable present");
10788 
10789     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10790       const auto *FD = dyn_cast<FunctionDecl>(ND);
10791       return FD && !FD->hasAttr<OverloadableAttr>();
10792     });
10793 
10794     if (OtherUnmarkedIter != Previous.end()) {
10795       Diag(NewFD->getLocation(),
10796            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10797       Diag((*OtherUnmarkedIter)->getLocation(),
10798            diag::note_attribute_overloadable_prev_overload)
10799           << false;
10800 
10801       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10802     }
10803   }
10804 
10805   // Semantic checking for this function declaration (in isolation).
10806 
10807   if (getLangOpts().CPlusPlus) {
10808     // C++-specific checks.
10809     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10810       CheckConstructor(Constructor);
10811     } else if (CXXDestructorDecl *Destructor =
10812                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10813       CXXRecordDecl *Record = Destructor->getParent();
10814       QualType ClassType = Context.getTypeDeclType(Record);
10815 
10816       // FIXME: Shouldn't we be able to perform this check even when the class
10817       // type is dependent? Both gcc and edg can handle that.
10818       if (!ClassType->isDependentType()) {
10819         DeclarationName Name
10820           = Context.DeclarationNames.getCXXDestructorName(
10821                                         Context.getCanonicalType(ClassType));
10822         if (NewFD->getDeclName() != Name) {
10823           Diag(NewFD->getLocation(), diag::err_destructor_name);
10824           NewFD->setInvalidDecl();
10825           return Redeclaration;
10826         }
10827       }
10828     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10829       if (auto *TD = Guide->getDescribedFunctionTemplate())
10830         CheckDeductionGuideTemplate(TD);
10831 
10832       // A deduction guide is not on the list of entities that can be
10833       // explicitly specialized.
10834       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10835         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10836             << /*explicit specialization*/ 1;
10837     }
10838 
10839     // Find any virtual functions that this function overrides.
10840     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10841       if (!Method->isFunctionTemplateSpecialization() &&
10842           !Method->getDescribedFunctionTemplate() &&
10843           Method->isCanonicalDecl()) {
10844         AddOverriddenMethods(Method->getParent(), Method);
10845       }
10846       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10847         // C++2a [class.virtual]p6
10848         // A virtual method shall not have a requires-clause.
10849         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10850              diag::err_constrained_virtual_method);
10851 
10852       if (Method->isStatic())
10853         checkThisInStaticMemberFunctionType(Method);
10854     }
10855 
10856     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10857       ActOnConversionDeclarator(Conversion);
10858 
10859     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10860     if (NewFD->isOverloadedOperator() &&
10861         CheckOverloadedOperatorDeclaration(NewFD)) {
10862       NewFD->setInvalidDecl();
10863       return Redeclaration;
10864     }
10865 
10866     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10867     if (NewFD->getLiteralIdentifier() &&
10868         CheckLiteralOperatorDeclaration(NewFD)) {
10869       NewFD->setInvalidDecl();
10870       return Redeclaration;
10871     }
10872 
10873     // In C++, check default arguments now that we have merged decls. Unless
10874     // the lexical context is the class, because in this case this is done
10875     // during delayed parsing anyway.
10876     if (!CurContext->isRecord())
10877       CheckCXXDefaultArguments(NewFD);
10878 
10879     // If this function declares a builtin function, check the type of this
10880     // declaration against the expected type for the builtin.
10881     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10882       ASTContext::GetBuiltinTypeError Error;
10883       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10884       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10885       // If the type of the builtin differs only in its exception
10886       // specification, that's OK.
10887       // FIXME: If the types do differ in this way, it would be better to
10888       // retain the 'noexcept' form of the type.
10889       if (!T.isNull() &&
10890           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10891                                                             NewFD->getType()))
10892         // The type of this function differs from the type of the builtin,
10893         // so forget about the builtin entirely.
10894         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10895     }
10896 
10897     // If this function is declared as being extern "C", then check to see if
10898     // the function returns a UDT (class, struct, or union type) that is not C
10899     // compatible, and if it does, warn the user.
10900     // But, issue any diagnostic on the first declaration only.
10901     if (Previous.empty() && NewFD->isExternC()) {
10902       QualType R = NewFD->getReturnType();
10903       if (R->isIncompleteType() && !R->isVoidType())
10904         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10905             << NewFD << R;
10906       else if (!R.isPODType(Context) && !R->isVoidType() &&
10907                !R->isObjCObjectPointerType())
10908         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10909     }
10910 
10911     // C++1z [dcl.fct]p6:
10912     //   [...] whether the function has a non-throwing exception-specification
10913     //   [is] part of the function type
10914     //
10915     // This results in an ABI break between C++14 and C++17 for functions whose
10916     // declared type includes an exception-specification in a parameter or
10917     // return type. (Exception specifications on the function itself are OK in
10918     // most cases, and exception specifications are not permitted in most other
10919     // contexts where they could make it into a mangling.)
10920     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10921       auto HasNoexcept = [&](QualType T) -> bool {
10922         // Strip off declarator chunks that could be between us and a function
10923         // type. We don't need to look far, exception specifications are very
10924         // restricted prior to C++17.
10925         if (auto *RT = T->getAs<ReferenceType>())
10926           T = RT->getPointeeType();
10927         else if (T->isAnyPointerType())
10928           T = T->getPointeeType();
10929         else if (auto *MPT = T->getAs<MemberPointerType>())
10930           T = MPT->getPointeeType();
10931         if (auto *FPT = T->getAs<FunctionProtoType>())
10932           if (FPT->isNothrow())
10933             return true;
10934         return false;
10935       };
10936 
10937       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10938       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10939       for (QualType T : FPT->param_types())
10940         AnyNoexcept |= HasNoexcept(T);
10941       if (AnyNoexcept)
10942         Diag(NewFD->getLocation(),
10943              diag::warn_cxx17_compat_exception_spec_in_signature)
10944             << NewFD;
10945     }
10946 
10947     if (!Redeclaration && LangOpts.CUDA)
10948       checkCUDATargetOverload(NewFD, Previous);
10949   }
10950   return Redeclaration;
10951 }
10952 
10953 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10954   // C++11 [basic.start.main]p3:
10955   //   A program that [...] declares main to be inline, static or
10956   //   constexpr is ill-formed.
10957   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10958   //   appear in a declaration of main.
10959   // static main is not an error under C99, but we should warn about it.
10960   // We accept _Noreturn main as an extension.
10961   if (FD->getStorageClass() == SC_Static)
10962     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10963          ? diag::err_static_main : diag::warn_static_main)
10964       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10965   if (FD->isInlineSpecified())
10966     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10967       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10968   if (DS.isNoreturnSpecified()) {
10969     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10970     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10971     Diag(NoreturnLoc, diag::ext_noreturn_main);
10972     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10973       << FixItHint::CreateRemoval(NoreturnRange);
10974   }
10975   if (FD->isConstexpr()) {
10976     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10977         << FD->isConsteval()
10978         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10979     FD->setConstexprKind(CSK_unspecified);
10980   }
10981 
10982   if (getLangOpts().OpenCL) {
10983     Diag(FD->getLocation(), diag::err_opencl_no_main)
10984         << FD->hasAttr<OpenCLKernelAttr>();
10985     FD->setInvalidDecl();
10986     return;
10987   }
10988 
10989   QualType T = FD->getType();
10990   assert(T->isFunctionType() && "function decl is not of function type");
10991   const FunctionType* FT = T->castAs<FunctionType>();
10992 
10993   // Set default calling convention for main()
10994   if (FT->getCallConv() != CC_C) {
10995     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10996     FD->setType(QualType(FT, 0));
10997     T = Context.getCanonicalType(FD->getType());
10998   }
10999 
11000   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11001     // In C with GNU extensions we allow main() to have non-integer return
11002     // type, but we should warn about the extension, and we disable the
11003     // implicit-return-zero rule.
11004 
11005     // GCC in C mode accepts qualified 'int'.
11006     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11007       FD->setHasImplicitReturnZero(true);
11008     else {
11009       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11010       SourceRange RTRange = FD->getReturnTypeSourceRange();
11011       if (RTRange.isValid())
11012         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11013             << FixItHint::CreateReplacement(RTRange, "int");
11014     }
11015   } else {
11016     // In C and C++, main magically returns 0 if you fall off the end;
11017     // set the flag which tells us that.
11018     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11019 
11020     // All the standards say that main() should return 'int'.
11021     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11022       FD->setHasImplicitReturnZero(true);
11023     else {
11024       // Otherwise, this is just a flat-out error.
11025       SourceRange RTRange = FD->getReturnTypeSourceRange();
11026       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11027           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11028                                 : FixItHint());
11029       FD->setInvalidDecl(true);
11030     }
11031   }
11032 
11033   // Treat protoless main() as nullary.
11034   if (isa<FunctionNoProtoType>(FT)) return;
11035 
11036   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11037   unsigned nparams = FTP->getNumParams();
11038   assert(FD->getNumParams() == nparams);
11039 
11040   bool HasExtraParameters = (nparams > 3);
11041 
11042   if (FTP->isVariadic()) {
11043     Diag(FD->getLocation(), diag::ext_variadic_main);
11044     // FIXME: if we had information about the location of the ellipsis, we
11045     // could add a FixIt hint to remove it as a parameter.
11046   }
11047 
11048   // Darwin passes an undocumented fourth argument of type char**.  If
11049   // other platforms start sprouting these, the logic below will start
11050   // getting shifty.
11051   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11052     HasExtraParameters = false;
11053 
11054   if (HasExtraParameters) {
11055     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11056     FD->setInvalidDecl(true);
11057     nparams = 3;
11058   }
11059 
11060   // FIXME: a lot of the following diagnostics would be improved
11061   // if we had some location information about types.
11062 
11063   QualType CharPP =
11064     Context.getPointerType(Context.getPointerType(Context.CharTy));
11065   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11066 
11067   for (unsigned i = 0; i < nparams; ++i) {
11068     QualType AT = FTP->getParamType(i);
11069 
11070     bool mismatch = true;
11071 
11072     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11073       mismatch = false;
11074     else if (Expected[i] == CharPP) {
11075       // As an extension, the following forms are okay:
11076       //   char const **
11077       //   char const * const *
11078       //   char * const *
11079 
11080       QualifierCollector qs;
11081       const PointerType* PT;
11082       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11083           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11084           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11085                               Context.CharTy)) {
11086         qs.removeConst();
11087         mismatch = !qs.empty();
11088       }
11089     }
11090 
11091     if (mismatch) {
11092       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11093       // TODO: suggest replacing given type with expected type
11094       FD->setInvalidDecl(true);
11095     }
11096   }
11097 
11098   if (nparams == 1 && !FD->isInvalidDecl()) {
11099     Diag(FD->getLocation(), diag::warn_main_one_arg);
11100   }
11101 
11102   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11103     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11104     FD->setInvalidDecl();
11105   }
11106 }
11107 
11108 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11109   QualType T = FD->getType();
11110   assert(T->isFunctionType() && "function decl is not of function type");
11111   const FunctionType *FT = T->castAs<FunctionType>();
11112 
11113   // Set an implicit return of 'zero' if the function can return some integral,
11114   // enumeration, pointer or nullptr type.
11115   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11116       FT->getReturnType()->isAnyPointerType() ||
11117       FT->getReturnType()->isNullPtrType())
11118     // DllMain is exempt because a return value of zero means it failed.
11119     if (FD->getName() != "DllMain")
11120       FD->setHasImplicitReturnZero(true);
11121 
11122   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11123     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11124     FD->setInvalidDecl();
11125   }
11126 }
11127 
11128 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11129   // FIXME: Need strict checking.  In C89, we need to check for
11130   // any assignment, increment, decrement, function-calls, or
11131   // commas outside of a sizeof.  In C99, it's the same list,
11132   // except that the aforementioned are allowed in unevaluated
11133   // expressions.  Everything else falls under the
11134   // "may accept other forms of constant expressions" exception.
11135   //
11136   // Regular C++ code will not end up here (exceptions: language extensions,
11137   // OpenCL C++ etc), so the constant expression rules there don't matter.
11138   if (Init->isValueDependent()) {
11139     assert(Init->containsErrors() &&
11140            "Dependent code should only occur in error-recovery path.");
11141     return true;
11142   }
11143   const Expr *Culprit;
11144   if (Init->isConstantInitializer(Context, false, &Culprit))
11145     return false;
11146   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11147     << Culprit->getSourceRange();
11148   return true;
11149 }
11150 
11151 namespace {
11152   // Visits an initialization expression to see if OrigDecl is evaluated in
11153   // its own initialization and throws a warning if it does.
11154   class SelfReferenceChecker
11155       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11156     Sema &S;
11157     Decl *OrigDecl;
11158     bool isRecordType;
11159     bool isPODType;
11160     bool isReferenceType;
11161 
11162     bool isInitList;
11163     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11164 
11165   public:
11166     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11167 
11168     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11169                                                     S(S), OrigDecl(OrigDecl) {
11170       isPODType = false;
11171       isRecordType = false;
11172       isReferenceType = false;
11173       isInitList = false;
11174       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11175         isPODType = VD->getType().isPODType(S.Context);
11176         isRecordType = VD->getType()->isRecordType();
11177         isReferenceType = VD->getType()->isReferenceType();
11178       }
11179     }
11180 
11181     // For most expressions, just call the visitor.  For initializer lists,
11182     // track the index of the field being initialized since fields are
11183     // initialized in order allowing use of previously initialized fields.
11184     void CheckExpr(Expr *E) {
11185       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11186       if (!InitList) {
11187         Visit(E);
11188         return;
11189       }
11190 
11191       // Track and increment the index here.
11192       isInitList = true;
11193       InitFieldIndex.push_back(0);
11194       for (auto Child : InitList->children()) {
11195         CheckExpr(cast<Expr>(Child));
11196         ++InitFieldIndex.back();
11197       }
11198       InitFieldIndex.pop_back();
11199     }
11200 
11201     // Returns true if MemberExpr is checked and no further checking is needed.
11202     // Returns false if additional checking is required.
11203     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11204       llvm::SmallVector<FieldDecl*, 4> Fields;
11205       Expr *Base = E;
11206       bool ReferenceField = false;
11207 
11208       // Get the field members used.
11209       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11210         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11211         if (!FD)
11212           return false;
11213         Fields.push_back(FD);
11214         if (FD->getType()->isReferenceType())
11215           ReferenceField = true;
11216         Base = ME->getBase()->IgnoreParenImpCasts();
11217       }
11218 
11219       // Keep checking only if the base Decl is the same.
11220       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11221       if (!DRE || DRE->getDecl() != OrigDecl)
11222         return false;
11223 
11224       // A reference field can be bound to an unininitialized field.
11225       if (CheckReference && !ReferenceField)
11226         return true;
11227 
11228       // Convert FieldDecls to their index number.
11229       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11230       for (const FieldDecl *I : llvm::reverse(Fields))
11231         UsedFieldIndex.push_back(I->getFieldIndex());
11232 
11233       // See if a warning is needed by checking the first difference in index
11234       // numbers.  If field being used has index less than the field being
11235       // initialized, then the use is safe.
11236       for (auto UsedIter = UsedFieldIndex.begin(),
11237                 UsedEnd = UsedFieldIndex.end(),
11238                 OrigIter = InitFieldIndex.begin(),
11239                 OrigEnd = InitFieldIndex.end();
11240            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11241         if (*UsedIter < *OrigIter)
11242           return true;
11243         if (*UsedIter > *OrigIter)
11244           break;
11245       }
11246 
11247       // TODO: Add a different warning which will print the field names.
11248       HandleDeclRefExpr(DRE);
11249       return true;
11250     }
11251 
11252     // For most expressions, the cast is directly above the DeclRefExpr.
11253     // For conditional operators, the cast can be outside the conditional
11254     // operator if both expressions are DeclRefExpr's.
11255     void HandleValue(Expr *E) {
11256       E = E->IgnoreParens();
11257       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11258         HandleDeclRefExpr(DRE);
11259         return;
11260       }
11261 
11262       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11263         Visit(CO->getCond());
11264         HandleValue(CO->getTrueExpr());
11265         HandleValue(CO->getFalseExpr());
11266         return;
11267       }
11268 
11269       if (BinaryConditionalOperator *BCO =
11270               dyn_cast<BinaryConditionalOperator>(E)) {
11271         Visit(BCO->getCond());
11272         HandleValue(BCO->getFalseExpr());
11273         return;
11274       }
11275 
11276       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11277         HandleValue(OVE->getSourceExpr());
11278         return;
11279       }
11280 
11281       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11282         if (BO->getOpcode() == BO_Comma) {
11283           Visit(BO->getLHS());
11284           HandleValue(BO->getRHS());
11285           return;
11286         }
11287       }
11288 
11289       if (isa<MemberExpr>(E)) {
11290         if (isInitList) {
11291           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11292                                       false /*CheckReference*/))
11293             return;
11294         }
11295 
11296         Expr *Base = E->IgnoreParenImpCasts();
11297         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11298           // Check for static member variables and don't warn on them.
11299           if (!isa<FieldDecl>(ME->getMemberDecl()))
11300             return;
11301           Base = ME->getBase()->IgnoreParenImpCasts();
11302         }
11303         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11304           HandleDeclRefExpr(DRE);
11305         return;
11306       }
11307 
11308       Visit(E);
11309     }
11310 
11311     // Reference types not handled in HandleValue are handled here since all
11312     // uses of references are bad, not just r-value uses.
11313     void VisitDeclRefExpr(DeclRefExpr *E) {
11314       if (isReferenceType)
11315         HandleDeclRefExpr(E);
11316     }
11317 
11318     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11319       if (E->getCastKind() == CK_LValueToRValue) {
11320         HandleValue(E->getSubExpr());
11321         return;
11322       }
11323 
11324       Inherited::VisitImplicitCastExpr(E);
11325     }
11326 
11327     void VisitMemberExpr(MemberExpr *E) {
11328       if (isInitList) {
11329         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11330           return;
11331       }
11332 
11333       // Don't warn on arrays since they can be treated as pointers.
11334       if (E->getType()->canDecayToPointerType()) return;
11335 
11336       // Warn when a non-static method call is followed by non-static member
11337       // field accesses, which is followed by a DeclRefExpr.
11338       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11339       bool Warn = (MD && !MD->isStatic());
11340       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11341       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11342         if (!isa<FieldDecl>(ME->getMemberDecl()))
11343           Warn = false;
11344         Base = ME->getBase()->IgnoreParenImpCasts();
11345       }
11346 
11347       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11348         if (Warn)
11349           HandleDeclRefExpr(DRE);
11350         return;
11351       }
11352 
11353       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11354       // Visit that expression.
11355       Visit(Base);
11356     }
11357 
11358     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11359       Expr *Callee = E->getCallee();
11360 
11361       if (isa<UnresolvedLookupExpr>(Callee))
11362         return Inherited::VisitCXXOperatorCallExpr(E);
11363 
11364       Visit(Callee);
11365       for (auto Arg: E->arguments())
11366         HandleValue(Arg->IgnoreParenImpCasts());
11367     }
11368 
11369     void VisitUnaryOperator(UnaryOperator *E) {
11370       // For POD record types, addresses of its own members are well-defined.
11371       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11372           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11373         if (!isPODType)
11374           HandleValue(E->getSubExpr());
11375         return;
11376       }
11377 
11378       if (E->isIncrementDecrementOp()) {
11379         HandleValue(E->getSubExpr());
11380         return;
11381       }
11382 
11383       Inherited::VisitUnaryOperator(E);
11384     }
11385 
11386     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11387 
11388     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11389       if (E->getConstructor()->isCopyConstructor()) {
11390         Expr *ArgExpr = E->getArg(0);
11391         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11392           if (ILE->getNumInits() == 1)
11393             ArgExpr = ILE->getInit(0);
11394         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11395           if (ICE->getCastKind() == CK_NoOp)
11396             ArgExpr = ICE->getSubExpr();
11397         HandleValue(ArgExpr);
11398         return;
11399       }
11400       Inherited::VisitCXXConstructExpr(E);
11401     }
11402 
11403     void VisitCallExpr(CallExpr *E) {
11404       // Treat std::move as a use.
11405       if (E->isCallToStdMove()) {
11406         HandleValue(E->getArg(0));
11407         return;
11408       }
11409 
11410       Inherited::VisitCallExpr(E);
11411     }
11412 
11413     void VisitBinaryOperator(BinaryOperator *E) {
11414       if (E->isCompoundAssignmentOp()) {
11415         HandleValue(E->getLHS());
11416         Visit(E->getRHS());
11417         return;
11418       }
11419 
11420       Inherited::VisitBinaryOperator(E);
11421     }
11422 
11423     // A custom visitor for BinaryConditionalOperator is needed because the
11424     // regular visitor would check the condition and true expression separately
11425     // but both point to the same place giving duplicate diagnostics.
11426     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11427       Visit(E->getCond());
11428       Visit(E->getFalseExpr());
11429     }
11430 
11431     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11432       Decl* ReferenceDecl = DRE->getDecl();
11433       if (OrigDecl != ReferenceDecl) return;
11434       unsigned diag;
11435       if (isReferenceType) {
11436         diag = diag::warn_uninit_self_reference_in_reference_init;
11437       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11438         diag = diag::warn_static_self_reference_in_init;
11439       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11440                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11441                  DRE->getDecl()->getType()->isRecordType()) {
11442         diag = diag::warn_uninit_self_reference_in_init;
11443       } else {
11444         // Local variables will be handled by the CFG analysis.
11445         return;
11446       }
11447 
11448       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11449                             S.PDiag(diag)
11450                                 << DRE->getDecl() << OrigDecl->getLocation()
11451                                 << DRE->getSourceRange());
11452     }
11453   };
11454 
11455   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11456   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11457                                  bool DirectInit) {
11458     // Parameters arguments are occassionially constructed with itself,
11459     // for instance, in recursive functions.  Skip them.
11460     if (isa<ParmVarDecl>(OrigDecl))
11461       return;
11462 
11463     E = E->IgnoreParens();
11464 
11465     // Skip checking T a = a where T is not a record or reference type.
11466     // Doing so is a way to silence uninitialized warnings.
11467     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11468       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11469         if (ICE->getCastKind() == CK_LValueToRValue)
11470           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11471             if (DRE->getDecl() == OrigDecl)
11472               return;
11473 
11474     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11475   }
11476 } // end anonymous namespace
11477 
11478 namespace {
11479   // Simple wrapper to add the name of a variable or (if no variable is
11480   // available) a DeclarationName into a diagnostic.
11481   struct VarDeclOrName {
11482     VarDecl *VDecl;
11483     DeclarationName Name;
11484 
11485     friend const Sema::SemaDiagnosticBuilder &
11486     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11487       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11488     }
11489   };
11490 } // end anonymous namespace
11491 
11492 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11493                                             DeclarationName Name, QualType Type,
11494                                             TypeSourceInfo *TSI,
11495                                             SourceRange Range, bool DirectInit,
11496                                             Expr *Init) {
11497   bool IsInitCapture = !VDecl;
11498   assert((!VDecl || !VDecl->isInitCapture()) &&
11499          "init captures are expected to be deduced prior to initialization");
11500 
11501   VarDeclOrName VN{VDecl, Name};
11502 
11503   DeducedType *Deduced = Type->getContainedDeducedType();
11504   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11505 
11506   // C++11 [dcl.spec.auto]p3
11507   if (!Init) {
11508     assert(VDecl && "no init for init capture deduction?");
11509 
11510     // Except for class argument deduction, and then for an initializing
11511     // declaration only, i.e. no static at class scope or extern.
11512     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11513         VDecl->hasExternalStorage() ||
11514         VDecl->isStaticDataMember()) {
11515       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11516         << VDecl->getDeclName() << Type;
11517       return QualType();
11518     }
11519   }
11520 
11521   ArrayRef<Expr*> DeduceInits;
11522   if (Init)
11523     DeduceInits = Init;
11524 
11525   if (DirectInit) {
11526     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11527       DeduceInits = PL->exprs();
11528   }
11529 
11530   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11531     assert(VDecl && "non-auto type for init capture deduction?");
11532     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11533     InitializationKind Kind = InitializationKind::CreateForInit(
11534         VDecl->getLocation(), DirectInit, Init);
11535     // FIXME: Initialization should not be taking a mutable list of inits.
11536     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11537     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11538                                                        InitsCopy);
11539   }
11540 
11541   if (DirectInit) {
11542     if (auto *IL = dyn_cast<InitListExpr>(Init))
11543       DeduceInits = IL->inits();
11544   }
11545 
11546   // Deduction only works if we have exactly one source expression.
11547   if (DeduceInits.empty()) {
11548     // It isn't possible to write this directly, but it is possible to
11549     // end up in this situation with "auto x(some_pack...);"
11550     Diag(Init->getBeginLoc(), IsInitCapture
11551                                   ? diag::err_init_capture_no_expression
11552                                   : diag::err_auto_var_init_no_expression)
11553         << VN << Type << Range;
11554     return QualType();
11555   }
11556 
11557   if (DeduceInits.size() > 1) {
11558     Diag(DeduceInits[1]->getBeginLoc(),
11559          IsInitCapture ? diag::err_init_capture_multiple_expressions
11560                        : diag::err_auto_var_init_multiple_expressions)
11561         << VN << Type << Range;
11562     return QualType();
11563   }
11564 
11565   Expr *DeduceInit = DeduceInits[0];
11566   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11567     Diag(Init->getBeginLoc(), IsInitCapture
11568                                   ? diag::err_init_capture_paren_braces
11569                                   : diag::err_auto_var_init_paren_braces)
11570         << isa<InitListExpr>(Init) << VN << Type << Range;
11571     return QualType();
11572   }
11573 
11574   // Expressions default to 'id' when we're in a debugger.
11575   bool DefaultedAnyToId = false;
11576   if (getLangOpts().DebuggerCastResultToId &&
11577       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11578     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11579     if (Result.isInvalid()) {
11580       return QualType();
11581     }
11582     Init = Result.get();
11583     DefaultedAnyToId = true;
11584   }
11585 
11586   // C++ [dcl.decomp]p1:
11587   //   If the assignment-expression [...] has array type A and no ref-qualifier
11588   //   is present, e has type cv A
11589   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11590       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11591       DeduceInit->getType()->isConstantArrayType())
11592     return Context.getQualifiedType(DeduceInit->getType(),
11593                                     Type.getQualifiers());
11594 
11595   QualType DeducedType;
11596   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11597     if (!IsInitCapture)
11598       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11599     else if (isa<InitListExpr>(Init))
11600       Diag(Range.getBegin(),
11601            diag::err_init_capture_deduction_failure_from_init_list)
11602           << VN
11603           << (DeduceInit->getType().isNull() ? TSI->getType()
11604                                              : DeduceInit->getType())
11605           << DeduceInit->getSourceRange();
11606     else
11607       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11608           << VN << TSI->getType()
11609           << (DeduceInit->getType().isNull() ? TSI->getType()
11610                                              : DeduceInit->getType())
11611           << DeduceInit->getSourceRange();
11612   }
11613 
11614   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11615   // 'id' instead of a specific object type prevents most of our usual
11616   // checks.
11617   // We only want to warn outside of template instantiations, though:
11618   // inside a template, the 'id' could have come from a parameter.
11619   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11620       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11621     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11622     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11623   }
11624 
11625   return DeducedType;
11626 }
11627 
11628 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11629                                          Expr *Init) {
11630   assert(!Init || !Init->containsErrors());
11631   QualType DeducedType = deduceVarTypeFromInitializer(
11632       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11633       VDecl->getSourceRange(), DirectInit, Init);
11634   if (DeducedType.isNull()) {
11635     VDecl->setInvalidDecl();
11636     return true;
11637   }
11638 
11639   VDecl->setType(DeducedType);
11640   assert(VDecl->isLinkageValid());
11641 
11642   // In ARC, infer lifetime.
11643   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11644     VDecl->setInvalidDecl();
11645 
11646   if (getLangOpts().OpenCL)
11647     deduceOpenCLAddressSpace(VDecl);
11648 
11649   // If this is a redeclaration, check that the type we just deduced matches
11650   // the previously declared type.
11651   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11652     // We never need to merge the type, because we cannot form an incomplete
11653     // array of auto, nor deduce such a type.
11654     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11655   }
11656 
11657   // Check the deduced type is valid for a variable declaration.
11658   CheckVariableDeclarationType(VDecl);
11659   return VDecl->isInvalidDecl();
11660 }
11661 
11662 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11663                                               SourceLocation Loc) {
11664   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11665     Init = EWC->getSubExpr();
11666 
11667   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11668     Init = CE->getSubExpr();
11669 
11670   QualType InitType = Init->getType();
11671   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11672           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11673          "shouldn't be called if type doesn't have a non-trivial C struct");
11674   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11675     for (auto I : ILE->inits()) {
11676       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11677           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11678         continue;
11679       SourceLocation SL = I->getExprLoc();
11680       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11681     }
11682     return;
11683   }
11684 
11685   if (isa<ImplicitValueInitExpr>(Init)) {
11686     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11687       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11688                             NTCUK_Init);
11689   } else {
11690     // Assume all other explicit initializers involving copying some existing
11691     // object.
11692     // TODO: ignore any explicit initializers where we can guarantee
11693     // copy-elision.
11694     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11695       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11696   }
11697 }
11698 
11699 namespace {
11700 
11701 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11702   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11703   // in the source code or implicitly by the compiler if it is in a union
11704   // defined in a system header and has non-trivial ObjC ownership
11705   // qualifications. We don't want those fields to participate in determining
11706   // whether the containing union is non-trivial.
11707   return FD->hasAttr<UnavailableAttr>();
11708 }
11709 
11710 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11711     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11712                                     void> {
11713   using Super =
11714       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11715                                     void>;
11716 
11717   DiagNonTrivalCUnionDefaultInitializeVisitor(
11718       QualType OrigTy, SourceLocation OrigLoc,
11719       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11720       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11721 
11722   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11723                      const FieldDecl *FD, bool InNonTrivialUnion) {
11724     if (const auto *AT = S.Context.getAsArrayType(QT))
11725       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11726                                      InNonTrivialUnion);
11727     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11728   }
11729 
11730   void visitARCStrong(QualType QT, const FieldDecl *FD,
11731                       bool InNonTrivialUnion) {
11732     if (InNonTrivialUnion)
11733       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11734           << 1 << 0 << QT << FD->getName();
11735   }
11736 
11737   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11738     if (InNonTrivialUnion)
11739       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11740           << 1 << 0 << QT << FD->getName();
11741   }
11742 
11743   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11744     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11745     if (RD->isUnion()) {
11746       if (OrigLoc.isValid()) {
11747         bool IsUnion = false;
11748         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11749           IsUnion = OrigRD->isUnion();
11750         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11751             << 0 << OrigTy << IsUnion << UseContext;
11752         // Reset OrigLoc so that this diagnostic is emitted only once.
11753         OrigLoc = SourceLocation();
11754       }
11755       InNonTrivialUnion = true;
11756     }
11757 
11758     if (InNonTrivialUnion)
11759       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11760           << 0 << 0 << QT.getUnqualifiedType() << "";
11761 
11762     for (const FieldDecl *FD : RD->fields())
11763       if (!shouldIgnoreForRecordTriviality(FD))
11764         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11765   }
11766 
11767   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11768 
11769   // The non-trivial C union type or the struct/union type that contains a
11770   // non-trivial C union.
11771   QualType OrigTy;
11772   SourceLocation OrigLoc;
11773   Sema::NonTrivialCUnionContext UseContext;
11774   Sema &S;
11775 };
11776 
11777 struct DiagNonTrivalCUnionDestructedTypeVisitor
11778     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11779   using Super =
11780       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11781 
11782   DiagNonTrivalCUnionDestructedTypeVisitor(
11783       QualType OrigTy, SourceLocation OrigLoc,
11784       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11785       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11786 
11787   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11788                      const FieldDecl *FD, bool InNonTrivialUnion) {
11789     if (const auto *AT = S.Context.getAsArrayType(QT))
11790       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11791                                      InNonTrivialUnion);
11792     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11793   }
11794 
11795   void visitARCStrong(QualType QT, const FieldDecl *FD,
11796                       bool InNonTrivialUnion) {
11797     if (InNonTrivialUnion)
11798       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11799           << 1 << 1 << QT << FD->getName();
11800   }
11801 
11802   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11803     if (InNonTrivialUnion)
11804       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11805           << 1 << 1 << QT << FD->getName();
11806   }
11807 
11808   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11809     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11810     if (RD->isUnion()) {
11811       if (OrigLoc.isValid()) {
11812         bool IsUnion = false;
11813         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11814           IsUnion = OrigRD->isUnion();
11815         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11816             << 1 << OrigTy << IsUnion << UseContext;
11817         // Reset OrigLoc so that this diagnostic is emitted only once.
11818         OrigLoc = SourceLocation();
11819       }
11820       InNonTrivialUnion = true;
11821     }
11822 
11823     if (InNonTrivialUnion)
11824       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11825           << 0 << 1 << QT.getUnqualifiedType() << "";
11826 
11827     for (const FieldDecl *FD : RD->fields())
11828       if (!shouldIgnoreForRecordTriviality(FD))
11829         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11830   }
11831 
11832   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11833   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11834                           bool InNonTrivialUnion) {}
11835 
11836   // The non-trivial C union type or the struct/union type that contains a
11837   // non-trivial C union.
11838   QualType OrigTy;
11839   SourceLocation OrigLoc;
11840   Sema::NonTrivialCUnionContext UseContext;
11841   Sema &S;
11842 };
11843 
11844 struct DiagNonTrivalCUnionCopyVisitor
11845     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11846   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11847 
11848   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11849                                  Sema::NonTrivialCUnionContext UseContext,
11850                                  Sema &S)
11851       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11852 
11853   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11854                      const FieldDecl *FD, bool InNonTrivialUnion) {
11855     if (const auto *AT = S.Context.getAsArrayType(QT))
11856       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11857                                      InNonTrivialUnion);
11858     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11859   }
11860 
11861   void visitARCStrong(QualType QT, const FieldDecl *FD,
11862                       bool InNonTrivialUnion) {
11863     if (InNonTrivialUnion)
11864       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11865           << 1 << 2 << QT << FD->getName();
11866   }
11867 
11868   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11869     if (InNonTrivialUnion)
11870       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11871           << 1 << 2 << QT << FD->getName();
11872   }
11873 
11874   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11875     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11876     if (RD->isUnion()) {
11877       if (OrigLoc.isValid()) {
11878         bool IsUnion = false;
11879         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11880           IsUnion = OrigRD->isUnion();
11881         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11882             << 2 << OrigTy << IsUnion << UseContext;
11883         // Reset OrigLoc so that this diagnostic is emitted only once.
11884         OrigLoc = SourceLocation();
11885       }
11886       InNonTrivialUnion = true;
11887     }
11888 
11889     if (InNonTrivialUnion)
11890       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11891           << 0 << 2 << QT.getUnqualifiedType() << "";
11892 
11893     for (const FieldDecl *FD : RD->fields())
11894       if (!shouldIgnoreForRecordTriviality(FD))
11895         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11896   }
11897 
11898   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11899                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11900   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11901   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11902                             bool InNonTrivialUnion) {}
11903 
11904   // The non-trivial C union type or the struct/union type that contains a
11905   // non-trivial C union.
11906   QualType OrigTy;
11907   SourceLocation OrigLoc;
11908   Sema::NonTrivialCUnionContext UseContext;
11909   Sema &S;
11910 };
11911 
11912 } // namespace
11913 
11914 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11915                                  NonTrivialCUnionContext UseContext,
11916                                  unsigned NonTrivialKind) {
11917   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11918           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11919           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11920          "shouldn't be called if type doesn't have a non-trivial C union");
11921 
11922   if ((NonTrivialKind & NTCUK_Init) &&
11923       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11924     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11925         .visit(QT, nullptr, false);
11926   if ((NonTrivialKind & NTCUK_Destruct) &&
11927       QT.hasNonTrivialToPrimitiveDestructCUnion())
11928     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11929         .visit(QT, nullptr, false);
11930   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11931     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11932         .visit(QT, nullptr, false);
11933 }
11934 
11935 /// AddInitializerToDecl - Adds the initializer Init to the
11936 /// declaration dcl. If DirectInit is true, this is C++ direct
11937 /// initialization rather than copy initialization.
11938 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11939   // If there is no declaration, there was an error parsing it.  Just ignore
11940   // the initializer.
11941   if (!RealDecl || RealDecl->isInvalidDecl()) {
11942     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11943     return;
11944   }
11945 
11946   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11947     // Pure-specifiers are handled in ActOnPureSpecifier.
11948     Diag(Method->getLocation(), diag::err_member_function_initialization)
11949       << Method->getDeclName() << Init->getSourceRange();
11950     Method->setInvalidDecl();
11951     return;
11952   }
11953 
11954   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11955   if (!VDecl) {
11956     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11957     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11958     RealDecl->setInvalidDecl();
11959     return;
11960   }
11961 
11962   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11963   if (VDecl->getType()->isUndeducedType()) {
11964     // Attempt typo correction early so that the type of the init expression can
11965     // be deduced based on the chosen correction if the original init contains a
11966     // TypoExpr.
11967     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11968     if (!Res.isUsable()) {
11969       // There are unresolved typos in Init, just drop them.
11970       // FIXME: improve the recovery strategy to preserve the Init.
11971       RealDecl->setInvalidDecl();
11972       return;
11973     }
11974     if (Res.get()->containsErrors()) {
11975       // Invalidate the decl as we don't know the type for recovery-expr yet.
11976       RealDecl->setInvalidDecl();
11977       VDecl->setInit(Res.get());
11978       return;
11979     }
11980     Init = Res.get();
11981 
11982     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11983       return;
11984   }
11985 
11986   // dllimport cannot be used on variable definitions.
11987   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11988     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11989     VDecl->setInvalidDecl();
11990     return;
11991   }
11992 
11993   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11994     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11995     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11996     VDecl->setInvalidDecl();
11997     return;
11998   }
11999 
12000   if (!VDecl->getType()->isDependentType()) {
12001     // A definition must end up with a complete type, which means it must be
12002     // complete with the restriction that an array type might be completed by
12003     // the initializer; note that later code assumes this restriction.
12004     QualType BaseDeclType = VDecl->getType();
12005     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12006       BaseDeclType = Array->getElementType();
12007     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12008                             diag::err_typecheck_decl_incomplete_type)) {
12009       RealDecl->setInvalidDecl();
12010       return;
12011     }
12012 
12013     // The variable can not have an abstract class type.
12014     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12015                                diag::err_abstract_type_in_decl,
12016                                AbstractVariableType))
12017       VDecl->setInvalidDecl();
12018   }
12019 
12020   // If adding the initializer will turn this declaration into a definition,
12021   // and we already have a definition for this variable, diagnose or otherwise
12022   // handle the situation.
12023   VarDecl *Def;
12024   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12025       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12026       !VDecl->isThisDeclarationADemotedDefinition() &&
12027       checkVarDeclRedefinition(Def, VDecl))
12028     return;
12029 
12030   if (getLangOpts().CPlusPlus) {
12031     // C++ [class.static.data]p4
12032     //   If a static data member is of const integral or const
12033     //   enumeration type, its declaration in the class definition can
12034     //   specify a constant-initializer which shall be an integral
12035     //   constant expression (5.19). In that case, the member can appear
12036     //   in integral constant expressions. The member shall still be
12037     //   defined in a namespace scope if it is used in the program and the
12038     //   namespace scope definition shall not contain an initializer.
12039     //
12040     // We already performed a redefinition check above, but for static
12041     // data members we also need to check whether there was an in-class
12042     // declaration with an initializer.
12043     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12044       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12045           << VDecl->getDeclName();
12046       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12047            diag::note_previous_initializer)
12048           << 0;
12049       return;
12050     }
12051 
12052     if (VDecl->hasLocalStorage())
12053       setFunctionHasBranchProtectedScope();
12054 
12055     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12056       VDecl->setInvalidDecl();
12057       return;
12058     }
12059   }
12060 
12061   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12062   // a kernel function cannot be initialized."
12063   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12064     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12065     VDecl->setInvalidDecl();
12066     return;
12067   }
12068 
12069   // The LoaderUninitialized attribute acts as a definition (of undef).
12070   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12071     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12072     VDecl->setInvalidDecl();
12073     return;
12074   }
12075 
12076   // Get the decls type and save a reference for later, since
12077   // CheckInitializerTypes may change it.
12078   QualType DclT = VDecl->getType(), SavT = DclT;
12079 
12080   // Expressions default to 'id' when we're in a debugger
12081   // and we are assigning it to a variable of Objective-C pointer type.
12082   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12083       Init->getType() == Context.UnknownAnyTy) {
12084     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12085     if (Result.isInvalid()) {
12086       VDecl->setInvalidDecl();
12087       return;
12088     }
12089     Init = Result.get();
12090   }
12091 
12092   // Perform the initialization.
12093   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12094   if (!VDecl->isInvalidDecl()) {
12095     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12096     InitializationKind Kind = InitializationKind::CreateForInit(
12097         VDecl->getLocation(), DirectInit, Init);
12098 
12099     MultiExprArg Args = Init;
12100     if (CXXDirectInit)
12101       Args = MultiExprArg(CXXDirectInit->getExprs(),
12102                           CXXDirectInit->getNumExprs());
12103 
12104     // Try to correct any TypoExprs in the initialization arguments.
12105     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12106       ExprResult Res = CorrectDelayedTyposInExpr(
12107           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12108           [this, Entity, Kind](Expr *E) {
12109             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12110             return Init.Failed() ? ExprError() : E;
12111           });
12112       if (Res.isInvalid()) {
12113         VDecl->setInvalidDecl();
12114       } else if (Res.get() != Args[Idx]) {
12115         Args[Idx] = Res.get();
12116       }
12117     }
12118     if (VDecl->isInvalidDecl())
12119       return;
12120 
12121     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12122                                    /*TopLevelOfInitList=*/false,
12123                                    /*TreatUnavailableAsInvalid=*/false);
12124     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12125     if (Result.isInvalid()) {
12126       // If the provied initializer fails to initialize the var decl,
12127       // we attach a recovery expr for better recovery.
12128       auto RecoveryExpr =
12129           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12130       if (RecoveryExpr.get())
12131         VDecl->setInit(RecoveryExpr.get());
12132       return;
12133     }
12134 
12135     Init = Result.getAs<Expr>();
12136   }
12137 
12138   // Check for self-references within variable initializers.
12139   // Variables declared within a function/method body (except for references)
12140   // are handled by a dataflow analysis.
12141   // This is undefined behavior in C++, but valid in C.
12142   if (getLangOpts().CPlusPlus) {
12143     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12144         VDecl->getType()->isReferenceType()) {
12145       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12146     }
12147   }
12148 
12149   // If the type changed, it means we had an incomplete type that was
12150   // completed by the initializer. For example:
12151   //   int ary[] = { 1, 3, 5 };
12152   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12153   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12154     VDecl->setType(DclT);
12155 
12156   if (!VDecl->isInvalidDecl()) {
12157     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12158 
12159     if (VDecl->hasAttr<BlocksAttr>())
12160       checkRetainCycles(VDecl, Init);
12161 
12162     // It is safe to assign a weak reference into a strong variable.
12163     // Although this code can still have problems:
12164     //   id x = self.weakProp;
12165     //   id y = self.weakProp;
12166     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12167     // paths through the function. This should be revisited if
12168     // -Wrepeated-use-of-weak is made flow-sensitive.
12169     if (FunctionScopeInfo *FSI = getCurFunction())
12170       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12171            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12172           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12173                            Init->getBeginLoc()))
12174         FSI->markSafeWeakUse(Init);
12175   }
12176 
12177   // The initialization is usually a full-expression.
12178   //
12179   // FIXME: If this is a braced initialization of an aggregate, it is not
12180   // an expression, and each individual field initializer is a separate
12181   // full-expression. For instance, in:
12182   //
12183   //   struct Temp { ~Temp(); };
12184   //   struct S { S(Temp); };
12185   //   struct T { S a, b; } t = { Temp(), Temp() }
12186   //
12187   // we should destroy the first Temp before constructing the second.
12188   ExprResult Result =
12189       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12190                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12191   if (Result.isInvalid()) {
12192     VDecl->setInvalidDecl();
12193     return;
12194   }
12195   Init = Result.get();
12196 
12197   // Attach the initializer to the decl.
12198   VDecl->setInit(Init);
12199 
12200   if (VDecl->isLocalVarDecl()) {
12201     // Don't check the initializer if the declaration is malformed.
12202     if (VDecl->isInvalidDecl()) {
12203       // do nothing
12204 
12205     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12206     // This is true even in C++ for OpenCL.
12207     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12208       CheckForConstantInitializer(Init, DclT);
12209 
12210     // Otherwise, C++ does not restrict the initializer.
12211     } else if (getLangOpts().CPlusPlus) {
12212       // do nothing
12213 
12214     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12215     // static storage duration shall be constant expressions or string literals.
12216     } else if (VDecl->getStorageClass() == SC_Static) {
12217       CheckForConstantInitializer(Init, DclT);
12218 
12219     // C89 is stricter than C99 for aggregate initializers.
12220     // C89 6.5.7p3: All the expressions [...] in an initializer list
12221     // for an object that has aggregate or union type shall be
12222     // constant expressions.
12223     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12224                isa<InitListExpr>(Init)) {
12225       const Expr *Culprit;
12226       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12227         Diag(Culprit->getExprLoc(),
12228              diag::ext_aggregate_init_not_constant)
12229           << Culprit->getSourceRange();
12230       }
12231     }
12232 
12233     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12234       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12235         if (VDecl->hasLocalStorage())
12236           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12237   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12238              VDecl->getLexicalDeclContext()->isRecord()) {
12239     // This is an in-class initialization for a static data member, e.g.,
12240     //
12241     // struct S {
12242     //   static const int value = 17;
12243     // };
12244 
12245     // C++ [class.mem]p4:
12246     //   A member-declarator can contain a constant-initializer only
12247     //   if it declares a static member (9.4) of const integral or
12248     //   const enumeration type, see 9.4.2.
12249     //
12250     // C++11 [class.static.data]p3:
12251     //   If a non-volatile non-inline const static data member is of integral
12252     //   or enumeration type, its declaration in the class definition can
12253     //   specify a brace-or-equal-initializer in which every initializer-clause
12254     //   that is an assignment-expression is a constant expression. A static
12255     //   data member of literal type can be declared in the class definition
12256     //   with the constexpr specifier; if so, its declaration shall specify a
12257     //   brace-or-equal-initializer in which every initializer-clause that is
12258     //   an assignment-expression is a constant expression.
12259 
12260     // Do nothing on dependent types.
12261     if (DclT->isDependentType()) {
12262 
12263     // Allow any 'static constexpr' members, whether or not they are of literal
12264     // type. We separately check that every constexpr variable is of literal
12265     // type.
12266     } else if (VDecl->isConstexpr()) {
12267 
12268     // Require constness.
12269     } else if (!DclT.isConstQualified()) {
12270       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12271         << Init->getSourceRange();
12272       VDecl->setInvalidDecl();
12273 
12274     // We allow integer constant expressions in all cases.
12275     } else if (DclT->isIntegralOrEnumerationType()) {
12276       // Check whether the expression is a constant expression.
12277       SourceLocation Loc;
12278       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12279         // In C++11, a non-constexpr const static data member with an
12280         // in-class initializer cannot be volatile.
12281         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12282       else if (Init->isValueDependent())
12283         ; // Nothing to check.
12284       else if (Init->isIntegerConstantExpr(Context, &Loc))
12285         ; // Ok, it's an ICE!
12286       else if (Init->getType()->isScopedEnumeralType() &&
12287                Init->isCXX11ConstantExpr(Context))
12288         ; // Ok, it is a scoped-enum constant expression.
12289       else if (Init->isEvaluatable(Context)) {
12290         // If we can constant fold the initializer through heroics, accept it,
12291         // but report this as a use of an extension for -pedantic.
12292         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12293           << Init->getSourceRange();
12294       } else {
12295         // Otherwise, this is some crazy unknown case.  Report the issue at the
12296         // location provided by the isIntegerConstantExpr failed check.
12297         Diag(Loc, diag::err_in_class_initializer_non_constant)
12298           << Init->getSourceRange();
12299         VDecl->setInvalidDecl();
12300       }
12301 
12302     // We allow foldable floating-point constants as an extension.
12303     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12304       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12305       // it anyway and provide a fixit to add the 'constexpr'.
12306       if (getLangOpts().CPlusPlus11) {
12307         Diag(VDecl->getLocation(),
12308              diag::ext_in_class_initializer_float_type_cxx11)
12309             << DclT << Init->getSourceRange();
12310         Diag(VDecl->getBeginLoc(),
12311              diag::note_in_class_initializer_float_type_cxx11)
12312             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12313       } else {
12314         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12315           << DclT << Init->getSourceRange();
12316 
12317         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12318           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12319             << Init->getSourceRange();
12320           VDecl->setInvalidDecl();
12321         }
12322       }
12323 
12324     // Suggest adding 'constexpr' in C++11 for literal types.
12325     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12326       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12327           << DclT << Init->getSourceRange()
12328           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12329       VDecl->setConstexpr(true);
12330 
12331     } else {
12332       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12333         << DclT << Init->getSourceRange();
12334       VDecl->setInvalidDecl();
12335     }
12336   } else if (VDecl->isFileVarDecl()) {
12337     // In C, extern is typically used to avoid tentative definitions when
12338     // declaring variables in headers, but adding an intializer makes it a
12339     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12340     // In C++, extern is often used to give implictly static const variables
12341     // external linkage, so don't warn in that case. If selectany is present,
12342     // this might be header code intended for C and C++ inclusion, so apply the
12343     // C++ rules.
12344     if (VDecl->getStorageClass() == SC_Extern &&
12345         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12346          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12347         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12348         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12349       Diag(VDecl->getLocation(), diag::warn_extern_init);
12350 
12351     // In Microsoft C++ mode, a const variable defined in namespace scope has
12352     // external linkage by default if the variable is declared with
12353     // __declspec(dllexport).
12354     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12355         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12356         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12357       VDecl->setStorageClass(SC_Extern);
12358 
12359     // C99 6.7.8p4. All file scoped initializers need to be constant.
12360     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12361       CheckForConstantInitializer(Init, DclT);
12362   }
12363 
12364   QualType InitType = Init->getType();
12365   if (!InitType.isNull() &&
12366       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12367        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12368     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12369 
12370   // We will represent direct-initialization similarly to copy-initialization:
12371   //    int x(1);  -as-> int x = 1;
12372   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12373   //
12374   // Clients that want to distinguish between the two forms, can check for
12375   // direct initializer using VarDecl::getInitStyle().
12376   // A major benefit is that clients that don't particularly care about which
12377   // exactly form was it (like the CodeGen) can handle both cases without
12378   // special case code.
12379 
12380   // C++ 8.5p11:
12381   // The form of initialization (using parentheses or '=') is generally
12382   // insignificant, but does matter when the entity being initialized has a
12383   // class type.
12384   if (CXXDirectInit) {
12385     assert(DirectInit && "Call-style initializer must be direct init.");
12386     VDecl->setInitStyle(VarDecl::CallInit);
12387   } else if (DirectInit) {
12388     // This must be list-initialization. No other way is direct-initialization.
12389     VDecl->setInitStyle(VarDecl::ListInit);
12390   }
12391 
12392   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12393     DeclsToCheckForDeferredDiags.push_back(VDecl);
12394   CheckCompleteVariableDeclaration(VDecl);
12395 }
12396 
12397 /// ActOnInitializerError - Given that there was an error parsing an
12398 /// initializer for the given declaration, try to return to some form
12399 /// of sanity.
12400 void Sema::ActOnInitializerError(Decl *D) {
12401   // Our main concern here is re-establishing invariants like "a
12402   // variable's type is either dependent or complete".
12403   if (!D || D->isInvalidDecl()) return;
12404 
12405   VarDecl *VD = dyn_cast<VarDecl>(D);
12406   if (!VD) return;
12407 
12408   // Bindings are not usable if we can't make sense of the initializer.
12409   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12410     for (auto *BD : DD->bindings())
12411       BD->setInvalidDecl();
12412 
12413   // Auto types are meaningless if we can't make sense of the initializer.
12414   if (VD->getType()->isUndeducedType()) {
12415     D->setInvalidDecl();
12416     return;
12417   }
12418 
12419   QualType Ty = VD->getType();
12420   if (Ty->isDependentType()) return;
12421 
12422   // Require a complete type.
12423   if (RequireCompleteType(VD->getLocation(),
12424                           Context.getBaseElementType(Ty),
12425                           diag::err_typecheck_decl_incomplete_type)) {
12426     VD->setInvalidDecl();
12427     return;
12428   }
12429 
12430   // Require a non-abstract type.
12431   if (RequireNonAbstractType(VD->getLocation(), Ty,
12432                              diag::err_abstract_type_in_decl,
12433                              AbstractVariableType)) {
12434     VD->setInvalidDecl();
12435     return;
12436   }
12437 
12438   // Don't bother complaining about constructors or destructors,
12439   // though.
12440 }
12441 
12442 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12443   // If there is no declaration, there was an error parsing it. Just ignore it.
12444   if (!RealDecl)
12445     return;
12446 
12447   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12448     QualType Type = Var->getType();
12449 
12450     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12451     if (isa<DecompositionDecl>(RealDecl)) {
12452       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12453       Var->setInvalidDecl();
12454       return;
12455     }
12456 
12457     if (Type->isUndeducedType() &&
12458         DeduceVariableDeclarationType(Var, false, nullptr))
12459       return;
12460 
12461     // C++11 [class.static.data]p3: A static data member can be declared with
12462     // the constexpr specifier; if so, its declaration shall specify
12463     // a brace-or-equal-initializer.
12464     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12465     // the definition of a variable [...] or the declaration of a static data
12466     // member.
12467     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12468         !Var->isThisDeclarationADemotedDefinition()) {
12469       if (Var->isStaticDataMember()) {
12470         // C++1z removes the relevant rule; the in-class declaration is always
12471         // a definition there.
12472         if (!getLangOpts().CPlusPlus17 &&
12473             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12474           Diag(Var->getLocation(),
12475                diag::err_constexpr_static_mem_var_requires_init)
12476               << Var;
12477           Var->setInvalidDecl();
12478           return;
12479         }
12480       } else {
12481         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12482         Var->setInvalidDecl();
12483         return;
12484       }
12485     }
12486 
12487     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12488     // be initialized.
12489     if (!Var->isInvalidDecl() &&
12490         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12491         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12492       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12493       Var->setInvalidDecl();
12494       return;
12495     }
12496 
12497     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12498       if (Var->getStorageClass() == SC_Extern) {
12499         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12500             << Var;
12501         Var->setInvalidDecl();
12502         return;
12503       }
12504       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12505                               diag::err_typecheck_decl_incomplete_type)) {
12506         Var->setInvalidDecl();
12507         return;
12508       }
12509       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12510         if (!RD->hasTrivialDefaultConstructor()) {
12511           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12512           Var->setInvalidDecl();
12513           return;
12514         }
12515       }
12516     }
12517 
12518     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12519     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12520         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12521       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12522                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12523 
12524 
12525     switch (DefKind) {
12526     case VarDecl::Definition:
12527       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12528         break;
12529 
12530       // We have an out-of-line definition of a static data member
12531       // that has an in-class initializer, so we type-check this like
12532       // a declaration.
12533       //
12534       LLVM_FALLTHROUGH;
12535 
12536     case VarDecl::DeclarationOnly:
12537       // It's only a declaration.
12538 
12539       // Block scope. C99 6.7p7: If an identifier for an object is
12540       // declared with no linkage (C99 6.2.2p6), the type for the
12541       // object shall be complete.
12542       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12543           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12544           RequireCompleteType(Var->getLocation(), Type,
12545                               diag::err_typecheck_decl_incomplete_type))
12546         Var->setInvalidDecl();
12547 
12548       // Make sure that the type is not abstract.
12549       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12550           RequireNonAbstractType(Var->getLocation(), Type,
12551                                  diag::err_abstract_type_in_decl,
12552                                  AbstractVariableType))
12553         Var->setInvalidDecl();
12554       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12555           Var->getStorageClass() == SC_PrivateExtern) {
12556         Diag(Var->getLocation(), diag::warn_private_extern);
12557         Diag(Var->getLocation(), diag::note_private_extern);
12558       }
12559 
12560       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12561           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12562         ExternalDeclarations.push_back(Var);
12563 
12564       return;
12565 
12566     case VarDecl::TentativeDefinition:
12567       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12568       // object that has file scope without an initializer, and without a
12569       // storage-class specifier or with the storage-class specifier "static",
12570       // constitutes a tentative definition. Note: A tentative definition with
12571       // external linkage is valid (C99 6.2.2p5).
12572       if (!Var->isInvalidDecl()) {
12573         if (const IncompleteArrayType *ArrayT
12574                                     = Context.getAsIncompleteArrayType(Type)) {
12575           if (RequireCompleteSizedType(
12576                   Var->getLocation(), ArrayT->getElementType(),
12577                   diag::err_array_incomplete_or_sizeless_type))
12578             Var->setInvalidDecl();
12579         } else if (Var->getStorageClass() == SC_Static) {
12580           // C99 6.9.2p3: If the declaration of an identifier for an object is
12581           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12582           // declared type shall not be an incomplete type.
12583           // NOTE: code such as the following
12584           //     static struct s;
12585           //     struct s { int a; };
12586           // is accepted by gcc. Hence here we issue a warning instead of
12587           // an error and we do not invalidate the static declaration.
12588           // NOTE: to avoid multiple warnings, only check the first declaration.
12589           if (Var->isFirstDecl())
12590             RequireCompleteType(Var->getLocation(), Type,
12591                                 diag::ext_typecheck_decl_incomplete_type);
12592         }
12593       }
12594 
12595       // Record the tentative definition; we're done.
12596       if (!Var->isInvalidDecl())
12597         TentativeDefinitions.push_back(Var);
12598       return;
12599     }
12600 
12601     // Provide a specific diagnostic for uninitialized variable
12602     // definitions with incomplete array type.
12603     if (Type->isIncompleteArrayType()) {
12604       Diag(Var->getLocation(),
12605            diag::err_typecheck_incomplete_array_needs_initializer);
12606       Var->setInvalidDecl();
12607       return;
12608     }
12609 
12610     // Provide a specific diagnostic for uninitialized variable
12611     // definitions with reference type.
12612     if (Type->isReferenceType()) {
12613       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12614           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12615       Var->setInvalidDecl();
12616       return;
12617     }
12618 
12619     // Do not attempt to type-check the default initializer for a
12620     // variable with dependent type.
12621     if (Type->isDependentType())
12622       return;
12623 
12624     if (Var->isInvalidDecl())
12625       return;
12626 
12627     if (!Var->hasAttr<AliasAttr>()) {
12628       if (RequireCompleteType(Var->getLocation(),
12629                               Context.getBaseElementType(Type),
12630                               diag::err_typecheck_decl_incomplete_type)) {
12631         Var->setInvalidDecl();
12632         return;
12633       }
12634     } else {
12635       return;
12636     }
12637 
12638     // The variable can not have an abstract class type.
12639     if (RequireNonAbstractType(Var->getLocation(), Type,
12640                                diag::err_abstract_type_in_decl,
12641                                AbstractVariableType)) {
12642       Var->setInvalidDecl();
12643       return;
12644     }
12645 
12646     // Check for jumps past the implicit initializer.  C++0x
12647     // clarifies that this applies to a "variable with automatic
12648     // storage duration", not a "local variable".
12649     // C++11 [stmt.dcl]p3
12650     //   A program that jumps from a point where a variable with automatic
12651     //   storage duration is not in scope to a point where it is in scope is
12652     //   ill-formed unless the variable has scalar type, class type with a
12653     //   trivial default constructor and a trivial destructor, a cv-qualified
12654     //   version of one of these types, or an array of one of the preceding
12655     //   types and is declared without an initializer.
12656     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12657       if (const RecordType *Record
12658             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12659         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12660         // Mark the function (if we're in one) for further checking even if the
12661         // looser rules of C++11 do not require such checks, so that we can
12662         // diagnose incompatibilities with C++98.
12663         if (!CXXRecord->isPOD())
12664           setFunctionHasBranchProtectedScope();
12665       }
12666     }
12667     // In OpenCL, we can't initialize objects in the __local address space,
12668     // even implicitly, so don't synthesize an implicit initializer.
12669     if (getLangOpts().OpenCL &&
12670         Var->getType().getAddressSpace() == LangAS::opencl_local)
12671       return;
12672     // C++03 [dcl.init]p9:
12673     //   If no initializer is specified for an object, and the
12674     //   object is of (possibly cv-qualified) non-POD class type (or
12675     //   array thereof), the object shall be default-initialized; if
12676     //   the object is of const-qualified type, the underlying class
12677     //   type shall have a user-declared default
12678     //   constructor. Otherwise, if no initializer is specified for
12679     //   a non- static object, the object and its subobjects, if
12680     //   any, have an indeterminate initial value); if the object
12681     //   or any of its subobjects are of const-qualified type, the
12682     //   program is ill-formed.
12683     // C++0x [dcl.init]p11:
12684     //   If no initializer is specified for an object, the object is
12685     //   default-initialized; [...].
12686     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12687     InitializationKind Kind
12688       = InitializationKind::CreateDefault(Var->getLocation());
12689 
12690     InitializationSequence InitSeq(*this, Entity, Kind, None);
12691     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12692 
12693     if (Init.get()) {
12694       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12695       // This is important for template substitution.
12696       Var->setInitStyle(VarDecl::CallInit);
12697     } else if (Init.isInvalid()) {
12698       // If default-init fails, attach a recovery-expr initializer to track
12699       // that initialization was attempted and failed.
12700       auto RecoveryExpr =
12701           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12702       if (RecoveryExpr.get())
12703         Var->setInit(RecoveryExpr.get());
12704     }
12705 
12706     CheckCompleteVariableDeclaration(Var);
12707   }
12708 }
12709 
12710 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12711   // If there is no declaration, there was an error parsing it. Ignore it.
12712   if (!D)
12713     return;
12714 
12715   VarDecl *VD = dyn_cast<VarDecl>(D);
12716   if (!VD) {
12717     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12718     D->setInvalidDecl();
12719     return;
12720   }
12721 
12722   VD->setCXXForRangeDecl(true);
12723 
12724   // for-range-declaration cannot be given a storage class specifier.
12725   int Error = -1;
12726   switch (VD->getStorageClass()) {
12727   case SC_None:
12728     break;
12729   case SC_Extern:
12730     Error = 0;
12731     break;
12732   case SC_Static:
12733     Error = 1;
12734     break;
12735   case SC_PrivateExtern:
12736     Error = 2;
12737     break;
12738   case SC_Auto:
12739     Error = 3;
12740     break;
12741   case SC_Register:
12742     Error = 4;
12743     break;
12744   }
12745   if (Error != -1) {
12746     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12747         << VD << Error;
12748     D->setInvalidDecl();
12749   }
12750 }
12751 
12752 StmtResult
12753 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12754                                  IdentifierInfo *Ident,
12755                                  ParsedAttributes &Attrs,
12756                                  SourceLocation AttrEnd) {
12757   // C++1y [stmt.iter]p1:
12758   //   A range-based for statement of the form
12759   //      for ( for-range-identifier : for-range-initializer ) statement
12760   //   is equivalent to
12761   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12762   DeclSpec DS(Attrs.getPool().getFactory());
12763 
12764   const char *PrevSpec;
12765   unsigned DiagID;
12766   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12767                      getPrintingPolicy());
12768 
12769   Declarator D(DS, DeclaratorContext::ForContext);
12770   D.SetIdentifier(Ident, IdentLoc);
12771   D.takeAttributes(Attrs, AttrEnd);
12772 
12773   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12774                 IdentLoc);
12775   Decl *Var = ActOnDeclarator(S, D);
12776   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12777   FinalizeDeclaration(Var);
12778   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12779                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12780 }
12781 
12782 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12783   if (var->isInvalidDecl()) return;
12784 
12785   if (getLangOpts().OpenCL) {
12786     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12787     // initialiser
12788     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12789         !var->hasInit()) {
12790       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12791           << 1 /*Init*/;
12792       var->setInvalidDecl();
12793       return;
12794     }
12795   }
12796 
12797   // In Objective-C, don't allow jumps past the implicit initialization of a
12798   // local retaining variable.
12799   if (getLangOpts().ObjC &&
12800       var->hasLocalStorage()) {
12801     switch (var->getType().getObjCLifetime()) {
12802     case Qualifiers::OCL_None:
12803     case Qualifiers::OCL_ExplicitNone:
12804     case Qualifiers::OCL_Autoreleasing:
12805       break;
12806 
12807     case Qualifiers::OCL_Weak:
12808     case Qualifiers::OCL_Strong:
12809       setFunctionHasBranchProtectedScope();
12810       break;
12811     }
12812   }
12813 
12814   if (var->hasLocalStorage() &&
12815       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12816     setFunctionHasBranchProtectedScope();
12817 
12818   // Warn about externally-visible variables being defined without a
12819   // prior declaration.  We only want to do this for global
12820   // declarations, but we also specifically need to avoid doing it for
12821   // class members because the linkage of an anonymous class can
12822   // change if it's later given a typedef name.
12823   if (var->isThisDeclarationADefinition() &&
12824       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12825       var->isExternallyVisible() && var->hasLinkage() &&
12826       !var->isInline() && !var->getDescribedVarTemplate() &&
12827       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12828       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12829       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12830                                   var->getLocation())) {
12831     // Find a previous declaration that's not a definition.
12832     VarDecl *prev = var->getPreviousDecl();
12833     while (prev && prev->isThisDeclarationADefinition())
12834       prev = prev->getPreviousDecl();
12835 
12836     if (!prev) {
12837       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12838       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12839           << /* variable */ 0;
12840     }
12841   }
12842 
12843   // Cache the result of checking for constant initialization.
12844   Optional<bool> CacheHasConstInit;
12845   const Expr *CacheCulprit = nullptr;
12846   auto checkConstInit = [&]() mutable {
12847     if (!CacheHasConstInit)
12848       CacheHasConstInit = var->getInit()->isConstantInitializer(
12849             Context, var->getType()->isReferenceType(), &CacheCulprit);
12850     return *CacheHasConstInit;
12851   };
12852 
12853   if (var->getTLSKind() == VarDecl::TLS_Static) {
12854     if (var->getType().isDestructedType()) {
12855       // GNU C++98 edits for __thread, [basic.start.term]p3:
12856       //   The type of an object with thread storage duration shall not
12857       //   have a non-trivial destructor.
12858       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12859       if (getLangOpts().CPlusPlus11)
12860         Diag(var->getLocation(), diag::note_use_thread_local);
12861     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12862       if (!checkConstInit()) {
12863         // GNU C++98 edits for __thread, [basic.start.init]p4:
12864         //   An object of thread storage duration shall not require dynamic
12865         //   initialization.
12866         // FIXME: Need strict checking here.
12867         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12868           << CacheCulprit->getSourceRange();
12869         if (getLangOpts().CPlusPlus11)
12870           Diag(var->getLocation(), diag::note_use_thread_local);
12871       }
12872     }
12873   }
12874 
12875   // Apply section attributes and pragmas to global variables.
12876   bool GlobalStorage = var->hasGlobalStorage();
12877   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12878       !inTemplateInstantiation()) {
12879     PragmaStack<StringLiteral *> *Stack = nullptr;
12880     int SectionFlags = ASTContext::PSF_Read;
12881     if (var->getType().isConstQualified())
12882       Stack = &ConstSegStack;
12883     else if (!var->getInit()) {
12884       Stack = &BSSSegStack;
12885       SectionFlags |= ASTContext::PSF_Write;
12886     } else {
12887       Stack = &DataSegStack;
12888       SectionFlags |= ASTContext::PSF_Write;
12889     }
12890     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12891       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12892         SectionFlags |= ASTContext::PSF_Implicit;
12893       UnifySection(SA->getName(), SectionFlags, var);
12894     } else if (Stack->CurrentValue) {
12895       SectionFlags |= ASTContext::PSF_Implicit;
12896       auto SectionName = Stack->CurrentValue->getString();
12897       var->addAttr(SectionAttr::CreateImplicit(
12898           Context, SectionName, Stack->CurrentPragmaLocation,
12899           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12900       if (UnifySection(SectionName, SectionFlags, var))
12901         var->dropAttr<SectionAttr>();
12902     }
12903 
12904     // Apply the init_seg attribute if this has an initializer.  If the
12905     // initializer turns out to not be dynamic, we'll end up ignoring this
12906     // attribute.
12907     if (CurInitSeg && var->getInit())
12908       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12909                                                CurInitSegLoc,
12910                                                AttributeCommonInfo::AS_Pragma));
12911   }
12912 
12913   if (!var->getType()->isStructureType() && var->hasInit() &&
12914       isa<InitListExpr>(var->getInit())) {
12915     const auto *ILE = cast<InitListExpr>(var->getInit());
12916     unsigned NumInits = ILE->getNumInits();
12917     if (NumInits > 2)
12918       for (unsigned I = 0; I < NumInits; ++I) {
12919         const auto *Init = ILE->getInit(I);
12920         if (!Init)
12921           break;
12922         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12923         if (!SL)
12924           break;
12925 
12926         unsigned NumConcat = SL->getNumConcatenated();
12927         // Diagnose missing comma in string array initialization.
12928         // Do not warn when all the elements in the initializer are concatenated
12929         // together. Do not warn for macros too.
12930         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12931           bool OnlyOneMissingComma = true;
12932           for (unsigned J = I + 1; J < NumInits; ++J) {
12933             const auto *Init = ILE->getInit(J);
12934             if (!Init)
12935               break;
12936             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12937             if (!SLJ || SLJ->getNumConcatenated() > 1) {
12938               OnlyOneMissingComma = false;
12939               break;
12940             }
12941           }
12942 
12943           if (OnlyOneMissingComma) {
12944             SmallVector<FixItHint, 1> Hints;
12945             for (unsigned i = 0; i < NumConcat - 1; ++i)
12946               Hints.push_back(FixItHint::CreateInsertion(
12947                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12948 
12949             Diag(SL->getStrTokenLoc(1),
12950                  diag::warn_concatenated_literal_array_init)
12951                 << Hints;
12952             Diag(SL->getBeginLoc(),
12953                  diag::note_concatenated_string_literal_silence);
12954           }
12955           // In any case, stop now.
12956           break;
12957         }
12958       }
12959   }
12960 
12961   // All the following checks are C++ only.
12962   if (!getLangOpts().CPlusPlus) {
12963       // If this variable must be emitted, add it as an initializer for the
12964       // current module.
12965      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12966        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12967      return;
12968   }
12969 
12970   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12971     CheckCompleteDecompositionDeclaration(DD);
12972 
12973   QualType type = var->getType();
12974   if (type->isDependentType()) return;
12975 
12976   if (var->hasAttr<BlocksAttr>())
12977     getCurFunction()->addByrefBlockVar(var);
12978 
12979   Expr *Init = var->getInit();
12980   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12981   QualType baseType = Context.getBaseElementType(type);
12982 
12983   if (Init && !Init->isValueDependent()) {
12984     if (var->isConstexpr()) {
12985       SmallVector<PartialDiagnosticAt, 8> Notes;
12986       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12987         SourceLocation DiagLoc = var->getLocation();
12988         // If the note doesn't add any useful information other than a source
12989         // location, fold it into the primary diagnostic.
12990         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12991               diag::note_invalid_subexpr_in_const_expr) {
12992           DiagLoc = Notes[0].first;
12993           Notes.clear();
12994         }
12995         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12996           << var << Init->getSourceRange();
12997         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12998           Diag(Notes[I].first, Notes[I].second);
12999       }
13000     } else if (var->mightBeUsableInConstantExpressions(Context)) {
13001       // Check whether the initializer of a const variable of integral or
13002       // enumeration type is an ICE now, since we can't tell whether it was
13003       // initialized by a constant expression if we check later.
13004       var->checkInitIsICE();
13005     }
13006 
13007     // Don't emit further diagnostics about constexpr globals since they
13008     // were just diagnosed.
13009     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13010       // FIXME: Need strict checking in C++03 here.
13011       bool DiagErr = getLangOpts().CPlusPlus11
13012           ? !var->checkInitIsICE() : !checkConstInit();
13013       if (DiagErr) {
13014         auto *Attr = var->getAttr<ConstInitAttr>();
13015         Diag(var->getLocation(), diag::err_require_constant_init_failed)
13016           << Init->getSourceRange();
13017         Diag(Attr->getLocation(),
13018              diag::note_declared_required_constant_init_here)
13019             << Attr->getRange() << Attr->isConstinit();
13020         if (getLangOpts().CPlusPlus11) {
13021           APValue Value;
13022           SmallVector<PartialDiagnosticAt, 8> Notes;
13023           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
13024           for (auto &it : Notes)
13025             Diag(it.first, it.second);
13026         } else {
13027           Diag(CacheCulprit->getExprLoc(),
13028                diag::note_invalid_subexpr_in_const_expr)
13029               << CacheCulprit->getSourceRange();
13030         }
13031       }
13032     }
13033     else if (!var->isConstexpr() && IsGlobal &&
13034              !getDiagnostics().isIgnored(diag::warn_global_constructor,
13035                                     var->getLocation())) {
13036       // Warn about globals which don't have a constant initializer.  Don't
13037       // warn about globals with a non-trivial destructor because we already
13038       // warned about them.
13039       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13040       if (!(RD && !RD->hasTrivialDestructor())) {
13041         if (!checkConstInit())
13042           Diag(var->getLocation(), diag::warn_global_constructor)
13043             << Init->getSourceRange();
13044       }
13045     }
13046   }
13047 
13048   // Require the destructor.
13049   if (const RecordType *recordType = baseType->getAs<RecordType>())
13050     FinalizeVarWithDestructor(var, recordType);
13051 
13052   // If this variable must be emitted, add it as an initializer for the current
13053   // module.
13054   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13055     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13056 }
13057 
13058 /// Determines if a variable's alignment is dependent.
13059 static bool hasDependentAlignment(VarDecl *VD) {
13060   if (VD->getType()->isDependentType())
13061     return true;
13062   for (auto *I : VD->specific_attrs<AlignedAttr>())
13063     if (I->isAlignmentDependent())
13064       return true;
13065   return false;
13066 }
13067 
13068 /// Check if VD needs to be dllexport/dllimport due to being in a
13069 /// dllexport/import function.
13070 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13071   assert(VD->isStaticLocal());
13072 
13073   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13074 
13075   // Find outermost function when VD is in lambda function.
13076   while (FD && !getDLLAttr(FD) &&
13077          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13078          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13079     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13080   }
13081 
13082   if (!FD)
13083     return;
13084 
13085   // Static locals inherit dll attributes from their function.
13086   if (Attr *A = getDLLAttr(FD)) {
13087     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13088     NewAttr->setInherited(true);
13089     VD->addAttr(NewAttr);
13090   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13091     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13092     NewAttr->setInherited(true);
13093     VD->addAttr(NewAttr);
13094 
13095     // Export this function to enforce exporting this static variable even
13096     // if it is not used in this compilation unit.
13097     if (!FD->hasAttr<DLLExportAttr>())
13098       FD->addAttr(NewAttr);
13099 
13100   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13101     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13102     NewAttr->setInherited(true);
13103     VD->addAttr(NewAttr);
13104   }
13105 }
13106 
13107 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13108 /// any semantic actions necessary after any initializer has been attached.
13109 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13110   // Note that we are no longer parsing the initializer for this declaration.
13111   ParsingInitForAutoVars.erase(ThisDecl);
13112 
13113   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13114   if (!VD)
13115     return;
13116 
13117   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13118   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13119       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13120     if (PragmaClangBSSSection.Valid)
13121       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13122           Context, PragmaClangBSSSection.SectionName,
13123           PragmaClangBSSSection.PragmaLocation,
13124           AttributeCommonInfo::AS_Pragma));
13125     if (PragmaClangDataSection.Valid)
13126       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13127           Context, PragmaClangDataSection.SectionName,
13128           PragmaClangDataSection.PragmaLocation,
13129           AttributeCommonInfo::AS_Pragma));
13130     if (PragmaClangRodataSection.Valid)
13131       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13132           Context, PragmaClangRodataSection.SectionName,
13133           PragmaClangRodataSection.PragmaLocation,
13134           AttributeCommonInfo::AS_Pragma));
13135     if (PragmaClangRelroSection.Valid)
13136       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13137           Context, PragmaClangRelroSection.SectionName,
13138           PragmaClangRelroSection.PragmaLocation,
13139           AttributeCommonInfo::AS_Pragma));
13140   }
13141 
13142   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13143     for (auto *BD : DD->bindings()) {
13144       FinalizeDeclaration(BD);
13145     }
13146   }
13147 
13148   checkAttributesAfterMerging(*this, *VD);
13149 
13150   // Perform TLS alignment check here after attributes attached to the variable
13151   // which may affect the alignment have been processed. Only perform the check
13152   // if the target has a maximum TLS alignment (zero means no constraints).
13153   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13154     // Protect the check so that it's not performed on dependent types and
13155     // dependent alignments (we can't determine the alignment in that case).
13156     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13157         !VD->isInvalidDecl()) {
13158       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13159       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13160         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13161           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13162           << (unsigned)MaxAlignChars.getQuantity();
13163       }
13164     }
13165   }
13166 
13167   if (VD->isStaticLocal()) {
13168     CheckStaticLocalForDllExport(VD);
13169 
13170     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13171       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13172       // function, only __shared__ variables or variables without any device
13173       // memory qualifiers may be declared with static storage class.
13174       // Note: It is unclear how a function-scope non-const static variable
13175       // without device memory qualifier is implemented, therefore only static
13176       // const variable without device memory qualifier is allowed.
13177       [&]() {
13178         if (!getLangOpts().CUDA)
13179           return;
13180         if (VD->hasAttr<CUDASharedAttr>())
13181           return;
13182         if (VD->getType().isConstQualified() &&
13183             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13184           return;
13185         if (CUDADiagIfDeviceCode(VD->getLocation(),
13186                                  diag::err_device_static_local_var)
13187             << CurrentCUDATarget())
13188           VD->setInvalidDecl();
13189       }();
13190     }
13191   }
13192 
13193   // Perform check for initializers of device-side global variables.
13194   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13195   // 7.5). We must also apply the same checks to all __shared__
13196   // variables whether they are local or not. CUDA also allows
13197   // constant initializers for __constant__ and __device__ variables.
13198   if (getLangOpts().CUDA)
13199     checkAllowedCUDAInitializer(VD);
13200 
13201   // Grab the dllimport or dllexport attribute off of the VarDecl.
13202   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13203 
13204   // Imported static data members cannot be defined out-of-line.
13205   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13206     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13207         VD->isThisDeclarationADefinition()) {
13208       // We allow definitions of dllimport class template static data members
13209       // with a warning.
13210       CXXRecordDecl *Context =
13211         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13212       bool IsClassTemplateMember =
13213           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13214           Context->getDescribedClassTemplate();
13215 
13216       Diag(VD->getLocation(),
13217            IsClassTemplateMember
13218                ? diag::warn_attribute_dllimport_static_field_definition
13219                : diag::err_attribute_dllimport_static_field_definition);
13220       Diag(IA->getLocation(), diag::note_attribute);
13221       if (!IsClassTemplateMember)
13222         VD->setInvalidDecl();
13223     }
13224   }
13225 
13226   // dllimport/dllexport variables cannot be thread local, their TLS index
13227   // isn't exported with the variable.
13228   if (DLLAttr && VD->getTLSKind()) {
13229     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13230     if (F && getDLLAttr(F)) {
13231       assert(VD->isStaticLocal());
13232       // But if this is a static local in a dlimport/dllexport function, the
13233       // function will never be inlined, which means the var would never be
13234       // imported, so having it marked import/export is safe.
13235     } else {
13236       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13237                                                                     << DLLAttr;
13238       VD->setInvalidDecl();
13239     }
13240   }
13241 
13242   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13243     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13244       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13245       VD->dropAttr<UsedAttr>();
13246     }
13247   }
13248 
13249   const DeclContext *DC = VD->getDeclContext();
13250   // If there's a #pragma GCC visibility in scope, and this isn't a class
13251   // member, set the visibility of this variable.
13252   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13253     AddPushedVisibilityAttribute(VD);
13254 
13255   // FIXME: Warn on unused var template partial specializations.
13256   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13257     MarkUnusedFileScopedDecl(VD);
13258 
13259   // Now we have parsed the initializer and can update the table of magic
13260   // tag values.
13261   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13262       !VD->getType()->isIntegralOrEnumerationType())
13263     return;
13264 
13265   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13266     const Expr *MagicValueExpr = VD->getInit();
13267     if (!MagicValueExpr) {
13268       continue;
13269     }
13270     Optional<llvm::APSInt> MagicValueInt;
13271     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13272       Diag(I->getRange().getBegin(),
13273            diag::err_type_tag_for_datatype_not_ice)
13274         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13275       continue;
13276     }
13277     if (MagicValueInt->getActiveBits() > 64) {
13278       Diag(I->getRange().getBegin(),
13279            diag::err_type_tag_for_datatype_too_large)
13280         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13281       continue;
13282     }
13283     uint64_t MagicValue = MagicValueInt->getZExtValue();
13284     RegisterTypeTagForDatatype(I->getArgumentKind(),
13285                                MagicValue,
13286                                I->getMatchingCType(),
13287                                I->getLayoutCompatible(),
13288                                I->getMustBeNull());
13289   }
13290 }
13291 
13292 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13293   auto *VD = dyn_cast<VarDecl>(DD);
13294   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13295 }
13296 
13297 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13298                                                    ArrayRef<Decl *> Group) {
13299   SmallVector<Decl*, 8> Decls;
13300 
13301   if (DS.isTypeSpecOwned())
13302     Decls.push_back(DS.getRepAsDecl());
13303 
13304   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13305   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13306   bool DiagnosedMultipleDecomps = false;
13307   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13308   bool DiagnosedNonDeducedAuto = false;
13309 
13310   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13311     if (Decl *D = Group[i]) {
13312       // For declarators, there are some additional syntactic-ish checks we need
13313       // to perform.
13314       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13315         if (!FirstDeclaratorInGroup)
13316           FirstDeclaratorInGroup = DD;
13317         if (!FirstDecompDeclaratorInGroup)
13318           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13319         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13320             !hasDeducedAuto(DD))
13321           FirstNonDeducedAutoInGroup = DD;
13322 
13323         if (FirstDeclaratorInGroup != DD) {
13324           // A decomposition declaration cannot be combined with any other
13325           // declaration in the same group.
13326           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13327             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13328                  diag::err_decomp_decl_not_alone)
13329                 << FirstDeclaratorInGroup->getSourceRange()
13330                 << DD->getSourceRange();
13331             DiagnosedMultipleDecomps = true;
13332           }
13333 
13334           // A declarator that uses 'auto' in any way other than to declare a
13335           // variable with a deduced type cannot be combined with any other
13336           // declarator in the same group.
13337           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13338             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13339                  diag::err_auto_non_deduced_not_alone)
13340                 << FirstNonDeducedAutoInGroup->getType()
13341                        ->hasAutoForTrailingReturnType()
13342                 << FirstDeclaratorInGroup->getSourceRange()
13343                 << DD->getSourceRange();
13344             DiagnosedNonDeducedAuto = true;
13345           }
13346         }
13347       }
13348 
13349       Decls.push_back(D);
13350     }
13351   }
13352 
13353   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13354     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13355       handleTagNumbering(Tag, S);
13356       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13357           getLangOpts().CPlusPlus)
13358         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13359     }
13360   }
13361 
13362   return BuildDeclaratorGroup(Decls);
13363 }
13364 
13365 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13366 /// group, performing any necessary semantic checking.
13367 Sema::DeclGroupPtrTy
13368 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13369   // C++14 [dcl.spec.auto]p7: (DR1347)
13370   //   If the type that replaces the placeholder type is not the same in each
13371   //   deduction, the program is ill-formed.
13372   if (Group.size() > 1) {
13373     QualType Deduced;
13374     VarDecl *DeducedDecl = nullptr;
13375     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13376       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13377       if (!D || D->isInvalidDecl())
13378         break;
13379       DeducedType *DT = D->getType()->getContainedDeducedType();
13380       if (!DT || DT->getDeducedType().isNull())
13381         continue;
13382       if (Deduced.isNull()) {
13383         Deduced = DT->getDeducedType();
13384         DeducedDecl = D;
13385       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13386         auto *AT = dyn_cast<AutoType>(DT);
13387         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13388                         diag::err_auto_different_deductions)
13389                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13390                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13391                    << D->getDeclName();
13392         if (DeducedDecl->hasInit())
13393           Dia << DeducedDecl->getInit()->getSourceRange();
13394         if (D->getInit())
13395           Dia << D->getInit()->getSourceRange();
13396         D->setInvalidDecl();
13397         break;
13398       }
13399     }
13400   }
13401 
13402   ActOnDocumentableDecls(Group);
13403 
13404   return DeclGroupPtrTy::make(
13405       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13406 }
13407 
13408 void Sema::ActOnDocumentableDecl(Decl *D) {
13409   ActOnDocumentableDecls(D);
13410 }
13411 
13412 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13413   // Don't parse the comment if Doxygen diagnostics are ignored.
13414   if (Group.empty() || !Group[0])
13415     return;
13416 
13417   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13418                       Group[0]->getLocation()) &&
13419       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13420                       Group[0]->getLocation()))
13421     return;
13422 
13423   if (Group.size() >= 2) {
13424     // This is a decl group.  Normally it will contain only declarations
13425     // produced from declarator list.  But in case we have any definitions or
13426     // additional declaration references:
13427     //   'typedef struct S {} S;'
13428     //   'typedef struct S *S;'
13429     //   'struct S *pS;'
13430     // FinalizeDeclaratorGroup adds these as separate declarations.
13431     Decl *MaybeTagDecl = Group[0];
13432     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13433       Group = Group.slice(1);
13434     }
13435   }
13436 
13437   // FIMXE: We assume every Decl in the group is in the same file.
13438   // This is false when preprocessor constructs the group from decls in
13439   // different files (e. g. macros or #include).
13440   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13441 }
13442 
13443 /// Common checks for a parameter-declaration that should apply to both function
13444 /// parameters and non-type template parameters.
13445 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13446   // Check that there are no default arguments inside the type of this
13447   // parameter.
13448   if (getLangOpts().CPlusPlus)
13449     CheckExtraCXXDefaultArguments(D);
13450 
13451   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13452   if (D.getCXXScopeSpec().isSet()) {
13453     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13454       << D.getCXXScopeSpec().getRange();
13455   }
13456 
13457   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13458   // simple identifier except [...irrelevant cases...].
13459   switch (D.getName().getKind()) {
13460   case UnqualifiedIdKind::IK_Identifier:
13461     break;
13462 
13463   case UnqualifiedIdKind::IK_OperatorFunctionId:
13464   case UnqualifiedIdKind::IK_ConversionFunctionId:
13465   case UnqualifiedIdKind::IK_LiteralOperatorId:
13466   case UnqualifiedIdKind::IK_ConstructorName:
13467   case UnqualifiedIdKind::IK_DestructorName:
13468   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13469   case UnqualifiedIdKind::IK_DeductionGuideName:
13470     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13471       << GetNameForDeclarator(D).getName();
13472     break;
13473 
13474   case UnqualifiedIdKind::IK_TemplateId:
13475   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13476     // GetNameForDeclarator would not produce a useful name in this case.
13477     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13478     break;
13479   }
13480 }
13481 
13482 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13483 /// to introduce parameters into function prototype scope.
13484 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13485   const DeclSpec &DS = D.getDeclSpec();
13486 
13487   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13488 
13489   // C++03 [dcl.stc]p2 also permits 'auto'.
13490   StorageClass SC = SC_None;
13491   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13492     SC = SC_Register;
13493     // In C++11, the 'register' storage class specifier is deprecated.
13494     // In C++17, it is not allowed, but we tolerate it as an extension.
13495     if (getLangOpts().CPlusPlus11) {
13496       Diag(DS.getStorageClassSpecLoc(),
13497            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13498                                      : diag::warn_deprecated_register)
13499         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13500     }
13501   } else if (getLangOpts().CPlusPlus &&
13502              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13503     SC = SC_Auto;
13504   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13505     Diag(DS.getStorageClassSpecLoc(),
13506          diag::err_invalid_storage_class_in_func_decl);
13507     D.getMutableDeclSpec().ClearStorageClassSpecs();
13508   }
13509 
13510   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13511     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13512       << DeclSpec::getSpecifierName(TSCS);
13513   if (DS.isInlineSpecified())
13514     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13515         << getLangOpts().CPlusPlus17;
13516   if (DS.hasConstexprSpecifier())
13517     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13518         << 0 << D.getDeclSpec().getConstexprSpecifier();
13519 
13520   DiagnoseFunctionSpecifiers(DS);
13521 
13522   CheckFunctionOrTemplateParamDeclarator(S, D);
13523 
13524   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13525   QualType parmDeclType = TInfo->getType();
13526 
13527   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13528   IdentifierInfo *II = D.getIdentifier();
13529   if (II) {
13530     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13531                    ForVisibleRedeclaration);
13532     LookupName(R, S);
13533     if (R.isSingleResult()) {
13534       NamedDecl *PrevDecl = R.getFoundDecl();
13535       if (PrevDecl->isTemplateParameter()) {
13536         // Maybe we will complain about the shadowed template parameter.
13537         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13538         // Just pretend that we didn't see the previous declaration.
13539         PrevDecl = nullptr;
13540       } else if (S->isDeclScope(PrevDecl)) {
13541         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13542         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13543 
13544         // Recover by removing the name
13545         II = nullptr;
13546         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13547         D.setInvalidType(true);
13548       }
13549     }
13550   }
13551 
13552   // Temporarily put parameter variables in the translation unit, not
13553   // the enclosing context.  This prevents them from accidentally
13554   // looking like class members in C++.
13555   ParmVarDecl *New =
13556       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13557                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13558 
13559   if (D.isInvalidType())
13560     New->setInvalidDecl();
13561 
13562   assert(S->isFunctionPrototypeScope());
13563   assert(S->getFunctionPrototypeDepth() >= 1);
13564   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13565                     S->getNextFunctionPrototypeIndex());
13566 
13567   // Add the parameter declaration into this scope.
13568   S->AddDecl(New);
13569   if (II)
13570     IdResolver.AddDecl(New);
13571 
13572   ProcessDeclAttributes(S, New, D);
13573 
13574   if (D.getDeclSpec().isModulePrivateSpecified())
13575     Diag(New->getLocation(), diag::err_module_private_local)
13576         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13577         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13578 
13579   if (New->hasAttr<BlocksAttr>()) {
13580     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13581   }
13582 
13583   if (getLangOpts().OpenCL)
13584     deduceOpenCLAddressSpace(New);
13585 
13586   return New;
13587 }
13588 
13589 /// Synthesizes a variable for a parameter arising from a
13590 /// typedef.
13591 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13592                                               SourceLocation Loc,
13593                                               QualType T) {
13594   /* FIXME: setting StartLoc == Loc.
13595      Would it be worth to modify callers so as to provide proper source
13596      location for the unnamed parameters, embedding the parameter's type? */
13597   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13598                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13599                                            SC_None, nullptr);
13600   Param->setImplicit();
13601   return Param;
13602 }
13603 
13604 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13605   // Don't diagnose unused-parameter errors in template instantiations; we
13606   // will already have done so in the template itself.
13607   if (inTemplateInstantiation())
13608     return;
13609 
13610   for (const ParmVarDecl *Parameter : Parameters) {
13611     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13612         !Parameter->hasAttr<UnusedAttr>()) {
13613       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13614         << Parameter->getDeclName();
13615     }
13616   }
13617 }
13618 
13619 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13620     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13621   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13622     return;
13623 
13624   // Warn if the return value is pass-by-value and larger than the specified
13625   // threshold.
13626   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13627     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13628     if (Size > LangOpts.NumLargeByValueCopy)
13629       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13630   }
13631 
13632   // Warn if any parameter is pass-by-value and larger than the specified
13633   // threshold.
13634   for (const ParmVarDecl *Parameter : Parameters) {
13635     QualType T = Parameter->getType();
13636     if (T->isDependentType() || !T.isPODType(Context))
13637       continue;
13638     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13639     if (Size > LangOpts.NumLargeByValueCopy)
13640       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13641           << Parameter << Size;
13642   }
13643 }
13644 
13645 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13646                                   SourceLocation NameLoc, IdentifierInfo *Name,
13647                                   QualType T, TypeSourceInfo *TSInfo,
13648                                   StorageClass SC) {
13649   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13650   if (getLangOpts().ObjCAutoRefCount &&
13651       T.getObjCLifetime() == Qualifiers::OCL_None &&
13652       T->isObjCLifetimeType()) {
13653 
13654     Qualifiers::ObjCLifetime lifetime;
13655 
13656     // Special cases for arrays:
13657     //   - if it's const, use __unsafe_unretained
13658     //   - otherwise, it's an error
13659     if (T->isArrayType()) {
13660       if (!T.isConstQualified()) {
13661         if (DelayedDiagnostics.shouldDelayDiagnostics())
13662           DelayedDiagnostics.add(
13663               sema::DelayedDiagnostic::makeForbiddenType(
13664               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13665         else
13666           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13667               << TSInfo->getTypeLoc().getSourceRange();
13668       }
13669       lifetime = Qualifiers::OCL_ExplicitNone;
13670     } else {
13671       lifetime = T->getObjCARCImplicitLifetime();
13672     }
13673     T = Context.getLifetimeQualifiedType(T, lifetime);
13674   }
13675 
13676   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13677                                          Context.getAdjustedParameterType(T),
13678                                          TSInfo, SC, nullptr);
13679 
13680   // Make a note if we created a new pack in the scope of a lambda, so that
13681   // we know that references to that pack must also be expanded within the
13682   // lambda scope.
13683   if (New->isParameterPack())
13684     if (auto *LSI = getEnclosingLambda())
13685       LSI->LocalPacks.push_back(New);
13686 
13687   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13688       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13689     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13690                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13691 
13692   // Parameters can not be abstract class types.
13693   // For record types, this is done by the AbstractClassUsageDiagnoser once
13694   // the class has been completely parsed.
13695   if (!CurContext->isRecord() &&
13696       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13697                              AbstractParamType))
13698     New->setInvalidDecl();
13699 
13700   // Parameter declarators cannot be interface types. All ObjC objects are
13701   // passed by reference.
13702   if (T->isObjCObjectType()) {
13703     SourceLocation TypeEndLoc =
13704         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13705     Diag(NameLoc,
13706          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13707       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13708     T = Context.getObjCObjectPointerType(T);
13709     New->setType(T);
13710   }
13711 
13712   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13713   // duration shall not be qualified by an address-space qualifier."
13714   // Since all parameters have automatic store duration, they can not have
13715   // an address space.
13716   if (T.getAddressSpace() != LangAS::Default &&
13717       // OpenCL allows function arguments declared to be an array of a type
13718       // to be qualified with an address space.
13719       !(getLangOpts().OpenCL &&
13720         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13721     Diag(NameLoc, diag::err_arg_with_address_space);
13722     New->setInvalidDecl();
13723   }
13724 
13725   return New;
13726 }
13727 
13728 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13729                                            SourceLocation LocAfterDecls) {
13730   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13731 
13732   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13733   // for a K&R function.
13734   if (!FTI.hasPrototype) {
13735     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13736       --i;
13737       if (FTI.Params[i].Param == nullptr) {
13738         SmallString<256> Code;
13739         llvm::raw_svector_ostream(Code)
13740             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13741         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13742             << FTI.Params[i].Ident
13743             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13744 
13745         // Implicitly declare the argument as type 'int' for lack of a better
13746         // type.
13747         AttributeFactory attrs;
13748         DeclSpec DS(attrs);
13749         const char* PrevSpec; // unused
13750         unsigned DiagID; // unused
13751         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13752                            DiagID, Context.getPrintingPolicy());
13753         // Use the identifier location for the type source range.
13754         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13755         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13756         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13757         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13758         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13759       }
13760     }
13761   }
13762 }
13763 
13764 Decl *
13765 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13766                               MultiTemplateParamsArg TemplateParameterLists,
13767                               SkipBodyInfo *SkipBody) {
13768   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13769   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13770   Scope *ParentScope = FnBodyScope->getParent();
13771 
13772   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13773   // we define a non-templated function definition, we will create a declaration
13774   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13775   // The base function declaration will have the equivalent of an `omp declare
13776   // variant` annotation which specifies the mangled definition as a
13777   // specialization function under the OpenMP context defined as part of the
13778   // `omp begin declare variant`.
13779   SmallVector<FunctionDecl *, 4> Bases;
13780   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13781     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13782         ParentScope, D, TemplateParameterLists, Bases);
13783 
13784   D.setFunctionDefinitionKind(FDK_Definition);
13785   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13786   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13787 
13788   if (!Bases.empty())
13789     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13790 
13791   return Dcl;
13792 }
13793 
13794 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13795   Consumer.HandleInlineFunctionDefinition(D);
13796 }
13797 
13798 static bool
13799 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13800                                 const FunctionDecl *&PossiblePrototype) {
13801   // Don't warn about invalid declarations.
13802   if (FD->isInvalidDecl())
13803     return false;
13804 
13805   // Or declarations that aren't global.
13806   if (!FD->isGlobal())
13807     return false;
13808 
13809   // Don't warn about C++ member functions.
13810   if (isa<CXXMethodDecl>(FD))
13811     return false;
13812 
13813   // Don't warn about 'main'.
13814   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13815     if (IdentifierInfo *II = FD->getIdentifier())
13816       if (II->isStr("main"))
13817         return false;
13818 
13819   // Don't warn about inline functions.
13820   if (FD->isInlined())
13821     return false;
13822 
13823   // Don't warn about function templates.
13824   if (FD->getDescribedFunctionTemplate())
13825     return false;
13826 
13827   // Don't warn about function template specializations.
13828   if (FD->isFunctionTemplateSpecialization())
13829     return false;
13830 
13831   // Don't warn for OpenCL kernels.
13832   if (FD->hasAttr<OpenCLKernelAttr>())
13833     return false;
13834 
13835   // Don't warn on explicitly deleted functions.
13836   if (FD->isDeleted())
13837     return false;
13838 
13839   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13840        Prev; Prev = Prev->getPreviousDecl()) {
13841     // Ignore any declarations that occur in function or method
13842     // scope, because they aren't visible from the header.
13843     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13844       continue;
13845 
13846     PossiblePrototype = Prev;
13847     return Prev->getType()->isFunctionNoProtoType();
13848   }
13849 
13850   return true;
13851 }
13852 
13853 void
13854 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13855                                    const FunctionDecl *EffectiveDefinition,
13856                                    SkipBodyInfo *SkipBody) {
13857   const FunctionDecl *Definition = EffectiveDefinition;
13858   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13859     // If this is a friend function defined in a class template, it does not
13860     // have a body until it is used, nevertheless it is a definition, see
13861     // [temp.inst]p2:
13862     //
13863     // ... for the purpose of determining whether an instantiated redeclaration
13864     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13865     // corresponds to a definition in the template is considered to be a
13866     // definition.
13867     //
13868     // The following code must produce redefinition error:
13869     //
13870     //     template<typename T> struct C20 { friend void func_20() {} };
13871     //     C20<int> c20i;
13872     //     void func_20() {}
13873     //
13874     for (auto I : FD->redecls()) {
13875       if (I != FD && !I->isInvalidDecl() &&
13876           I->getFriendObjectKind() != Decl::FOK_None) {
13877         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13878           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13879             // A merged copy of the same function, instantiated as a member of
13880             // the same class, is OK.
13881             if (declaresSameEntity(OrigFD, Original) &&
13882                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13883                                    cast<Decl>(FD->getLexicalDeclContext())))
13884               continue;
13885           }
13886 
13887           if (Original->isThisDeclarationADefinition()) {
13888             Definition = I;
13889             break;
13890           }
13891         }
13892       }
13893     }
13894   }
13895 
13896   if (!Definition)
13897     // Similar to friend functions a friend function template may be a
13898     // definition and do not have a body if it is instantiated in a class
13899     // template.
13900     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13901       for (auto I : FTD->redecls()) {
13902         auto D = cast<FunctionTemplateDecl>(I);
13903         if (D != FTD) {
13904           assert(!D->isThisDeclarationADefinition() &&
13905                  "More than one definition in redeclaration chain");
13906           if (D->getFriendObjectKind() != Decl::FOK_None)
13907             if (FunctionTemplateDecl *FT =
13908                                        D->getInstantiatedFromMemberTemplate()) {
13909               if (FT->isThisDeclarationADefinition()) {
13910                 Definition = D->getTemplatedDecl();
13911                 break;
13912               }
13913             }
13914         }
13915       }
13916     }
13917 
13918   if (!Definition)
13919     return;
13920 
13921   if (canRedefineFunction(Definition, getLangOpts()))
13922     return;
13923 
13924   // Don't emit an error when this is redefinition of a typo-corrected
13925   // definition.
13926   if (TypoCorrectedFunctionDefinitions.count(Definition))
13927     return;
13928 
13929   // If we don't have a visible definition of the function, and it's inline or
13930   // a template, skip the new definition.
13931   if (SkipBody && !hasVisibleDefinition(Definition) &&
13932       (Definition->getFormalLinkage() == InternalLinkage ||
13933        Definition->isInlined() ||
13934        Definition->getDescribedFunctionTemplate() ||
13935        Definition->getNumTemplateParameterLists())) {
13936     SkipBody->ShouldSkip = true;
13937     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13938     if (auto *TD = Definition->getDescribedFunctionTemplate())
13939       makeMergedDefinitionVisible(TD);
13940     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13941     return;
13942   }
13943 
13944   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13945       Definition->getStorageClass() == SC_Extern)
13946     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13947         << FD << getLangOpts().CPlusPlus;
13948   else
13949     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13950 
13951   Diag(Definition->getLocation(), diag::note_previous_definition);
13952   FD->setInvalidDecl();
13953 }
13954 
13955 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13956                                    Sema &S) {
13957   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13958 
13959   LambdaScopeInfo *LSI = S.PushLambdaScope();
13960   LSI->CallOperator = CallOperator;
13961   LSI->Lambda = LambdaClass;
13962   LSI->ReturnType = CallOperator->getReturnType();
13963   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13964 
13965   if (LCD == LCD_None)
13966     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13967   else if (LCD == LCD_ByCopy)
13968     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13969   else if (LCD == LCD_ByRef)
13970     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13971   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13972 
13973   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13974   LSI->Mutable = !CallOperator->isConst();
13975 
13976   // Add the captures to the LSI so they can be noted as already
13977   // captured within tryCaptureVar.
13978   auto I = LambdaClass->field_begin();
13979   for (const auto &C : LambdaClass->captures()) {
13980     if (C.capturesVariable()) {
13981       VarDecl *VD = C.getCapturedVar();
13982       if (VD->isInitCapture())
13983         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13984       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13985       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13986           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13987           /*EllipsisLoc*/C.isPackExpansion()
13988                          ? C.getEllipsisLoc() : SourceLocation(),
13989           I->getType(), /*Invalid*/false);
13990 
13991     } else if (C.capturesThis()) {
13992       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13993                           C.getCaptureKind() == LCK_StarThis);
13994     } else {
13995       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13996                              I->getType());
13997     }
13998     ++I;
13999   }
14000 }
14001 
14002 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14003                                     SkipBodyInfo *SkipBody) {
14004   if (!D) {
14005     // Parsing the function declaration failed in some way. Push on a fake scope
14006     // anyway so we can try to parse the function body.
14007     PushFunctionScope();
14008     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14009     return D;
14010   }
14011 
14012   FunctionDecl *FD = nullptr;
14013 
14014   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14015     FD = FunTmpl->getTemplatedDecl();
14016   else
14017     FD = cast<FunctionDecl>(D);
14018 
14019   // Do not push if it is a lambda because one is already pushed when building
14020   // the lambda in ActOnStartOfLambdaDefinition().
14021   if (!isLambdaCallOperator(FD))
14022     PushExpressionEvaluationContext(
14023         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14024                           : ExprEvalContexts.back().Context);
14025 
14026   // Check for defining attributes before the check for redefinition.
14027   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14028     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14029     FD->dropAttr<AliasAttr>();
14030     FD->setInvalidDecl();
14031   }
14032   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14033     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14034     FD->dropAttr<IFuncAttr>();
14035     FD->setInvalidDecl();
14036   }
14037 
14038   // See if this is a redefinition. If 'will have body' is already set, then
14039   // these checks were already performed when it was set.
14040   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
14041     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14042 
14043     // If we're skipping the body, we're done. Don't enter the scope.
14044     if (SkipBody && SkipBody->ShouldSkip)
14045       return D;
14046   }
14047 
14048   // Mark this function as "will have a body eventually".  This lets users to
14049   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14050   // this function.
14051   FD->setWillHaveBody();
14052 
14053   // If we are instantiating a generic lambda call operator, push
14054   // a LambdaScopeInfo onto the function stack.  But use the information
14055   // that's already been calculated (ActOnLambdaExpr) to prime the current
14056   // LambdaScopeInfo.
14057   // When the template operator is being specialized, the LambdaScopeInfo,
14058   // has to be properly restored so that tryCaptureVariable doesn't try
14059   // and capture any new variables. In addition when calculating potential
14060   // captures during transformation of nested lambdas, it is necessary to
14061   // have the LSI properly restored.
14062   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14063     assert(inTemplateInstantiation() &&
14064            "There should be an active template instantiation on the stack "
14065            "when instantiating a generic lambda!");
14066     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14067   } else {
14068     // Enter a new function scope
14069     PushFunctionScope();
14070   }
14071 
14072   // Builtin functions cannot be defined.
14073   if (unsigned BuiltinID = FD->getBuiltinID()) {
14074     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14075         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14076       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14077       FD->setInvalidDecl();
14078     }
14079   }
14080 
14081   // The return type of a function definition must be complete
14082   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14083   QualType ResultType = FD->getReturnType();
14084   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14085       !FD->isInvalidDecl() &&
14086       RequireCompleteType(FD->getLocation(), ResultType,
14087                           diag::err_func_def_incomplete_result))
14088     FD->setInvalidDecl();
14089 
14090   if (FnBodyScope)
14091     PushDeclContext(FnBodyScope, FD);
14092 
14093   // Check the validity of our function parameters
14094   CheckParmsForFunctionDef(FD->parameters(),
14095                            /*CheckParameterNames=*/true);
14096 
14097   // Add non-parameter declarations already in the function to the current
14098   // scope.
14099   if (FnBodyScope) {
14100     for (Decl *NPD : FD->decls()) {
14101       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14102       if (!NonParmDecl)
14103         continue;
14104       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14105              "parameters should not be in newly created FD yet");
14106 
14107       // If the decl has a name, make it accessible in the current scope.
14108       if (NonParmDecl->getDeclName())
14109         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14110 
14111       // Similarly, dive into enums and fish their constants out, making them
14112       // accessible in this scope.
14113       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14114         for (auto *EI : ED->enumerators())
14115           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14116       }
14117     }
14118   }
14119 
14120   // Introduce our parameters into the function scope
14121   for (auto Param : FD->parameters()) {
14122     Param->setOwningFunction(FD);
14123 
14124     // If this has an identifier, add it to the scope stack.
14125     if (Param->getIdentifier() && FnBodyScope) {
14126       CheckShadow(FnBodyScope, Param);
14127 
14128       PushOnScopeChains(Param, FnBodyScope);
14129     }
14130   }
14131 
14132   // Ensure that the function's exception specification is instantiated.
14133   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14134     ResolveExceptionSpec(D->getLocation(), FPT);
14135 
14136   // dllimport cannot be applied to non-inline function definitions.
14137   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14138       !FD->isTemplateInstantiation()) {
14139     assert(!FD->hasAttr<DLLExportAttr>());
14140     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14141     FD->setInvalidDecl();
14142     return D;
14143   }
14144   // We want to attach documentation to original Decl (which might be
14145   // a function template).
14146   ActOnDocumentableDecl(D);
14147   if (getCurLexicalContext()->isObjCContainer() &&
14148       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14149       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14150     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14151 
14152   return D;
14153 }
14154 
14155 /// Given the set of return statements within a function body,
14156 /// compute the variables that are subject to the named return value
14157 /// optimization.
14158 ///
14159 /// Each of the variables that is subject to the named return value
14160 /// optimization will be marked as NRVO variables in the AST, and any
14161 /// return statement that has a marked NRVO variable as its NRVO candidate can
14162 /// use the named return value optimization.
14163 ///
14164 /// This function applies a very simplistic algorithm for NRVO: if every return
14165 /// statement in the scope of a variable has the same NRVO candidate, that
14166 /// candidate is an NRVO variable.
14167 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14168   ReturnStmt **Returns = Scope->Returns.data();
14169 
14170   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14171     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14172       if (!NRVOCandidate->isNRVOVariable())
14173         Returns[I]->setNRVOCandidate(nullptr);
14174     }
14175   }
14176 }
14177 
14178 bool Sema::canDelayFunctionBody(const Declarator &D) {
14179   // We can't delay parsing the body of a constexpr function template (yet).
14180   if (D.getDeclSpec().hasConstexprSpecifier())
14181     return false;
14182 
14183   // We can't delay parsing the body of a function template with a deduced
14184   // return type (yet).
14185   if (D.getDeclSpec().hasAutoTypeSpec()) {
14186     // If the placeholder introduces a non-deduced trailing return type,
14187     // we can still delay parsing it.
14188     if (D.getNumTypeObjects()) {
14189       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14190       if (Outer.Kind == DeclaratorChunk::Function &&
14191           Outer.Fun.hasTrailingReturnType()) {
14192         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14193         return Ty.isNull() || !Ty->isUndeducedType();
14194       }
14195     }
14196     return false;
14197   }
14198 
14199   return true;
14200 }
14201 
14202 bool Sema::canSkipFunctionBody(Decl *D) {
14203   // We cannot skip the body of a function (or function template) which is
14204   // constexpr, since we may need to evaluate its body in order to parse the
14205   // rest of the file.
14206   // We cannot skip the body of a function with an undeduced return type,
14207   // because any callers of that function need to know the type.
14208   if (const FunctionDecl *FD = D->getAsFunction()) {
14209     if (FD->isConstexpr())
14210       return false;
14211     // We can't simply call Type::isUndeducedType here, because inside template
14212     // auto can be deduced to a dependent type, which is not considered
14213     // "undeduced".
14214     if (FD->getReturnType()->getContainedDeducedType())
14215       return false;
14216   }
14217   return Consumer.shouldSkipFunctionBody(D);
14218 }
14219 
14220 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14221   if (!Decl)
14222     return nullptr;
14223   if (FunctionDecl *FD = Decl->getAsFunction())
14224     FD->setHasSkippedBody();
14225   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14226     MD->setHasSkippedBody();
14227   return Decl;
14228 }
14229 
14230 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14231   return ActOnFinishFunctionBody(D, BodyArg, false);
14232 }
14233 
14234 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14235 /// body.
14236 class ExitFunctionBodyRAII {
14237 public:
14238   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14239   ~ExitFunctionBodyRAII() {
14240     if (!IsLambda)
14241       S.PopExpressionEvaluationContext();
14242   }
14243 
14244 private:
14245   Sema &S;
14246   bool IsLambda = false;
14247 };
14248 
14249 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14250   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14251 
14252   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14253     if (EscapeInfo.count(BD))
14254       return EscapeInfo[BD];
14255 
14256     bool R = false;
14257     const BlockDecl *CurBD = BD;
14258 
14259     do {
14260       R = !CurBD->doesNotEscape();
14261       if (R)
14262         break;
14263       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14264     } while (CurBD);
14265 
14266     return EscapeInfo[BD] = R;
14267   };
14268 
14269   // If the location where 'self' is implicitly retained is inside a escaping
14270   // block, emit a diagnostic.
14271   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14272        S.ImplicitlyRetainedSelfLocs)
14273     if (IsOrNestedInEscapingBlock(P.second))
14274       S.Diag(P.first, diag::warn_implicitly_retains_self)
14275           << FixItHint::CreateInsertion(P.first, "self->");
14276 }
14277 
14278 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14279                                     bool IsInstantiation) {
14280   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14281 
14282   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14283   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14284 
14285   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14286     CheckCompletedCoroutineBody(FD, Body);
14287 
14288   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14289   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14290   // meant to pop the context added in ActOnStartOfFunctionDef().
14291   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14292 
14293   if (FD) {
14294     FD->setBody(Body);
14295     FD->setWillHaveBody(false);
14296 
14297     if (getLangOpts().CPlusPlus14) {
14298       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14299           FD->getReturnType()->isUndeducedType()) {
14300         // If the function has a deduced result type but contains no 'return'
14301         // statements, the result type as written must be exactly 'auto', and
14302         // the deduced result type is 'void'.
14303         if (!FD->getReturnType()->getAs<AutoType>()) {
14304           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14305               << FD->getReturnType();
14306           FD->setInvalidDecl();
14307         } else {
14308           // Substitute 'void' for the 'auto' in the type.
14309           TypeLoc ResultType = getReturnTypeLoc(FD);
14310           Context.adjustDeducedFunctionResultType(
14311               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14312         }
14313       }
14314     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14315       // In C++11, we don't use 'auto' deduction rules for lambda call
14316       // operators because we don't support return type deduction.
14317       auto *LSI = getCurLambda();
14318       if (LSI->HasImplicitReturnType) {
14319         deduceClosureReturnType(*LSI);
14320 
14321         // C++11 [expr.prim.lambda]p4:
14322         //   [...] if there are no return statements in the compound-statement
14323         //   [the deduced type is] the type void
14324         QualType RetType =
14325             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14326 
14327         // Update the return type to the deduced type.
14328         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14329         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14330                                             Proto->getExtProtoInfo()));
14331       }
14332     }
14333 
14334     // If the function implicitly returns zero (like 'main') or is naked,
14335     // don't complain about missing return statements.
14336     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14337       WP.disableCheckFallThrough();
14338 
14339     // MSVC permits the use of pure specifier (=0) on function definition,
14340     // defined at class scope, warn about this non-standard construct.
14341     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14342       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14343 
14344     if (!FD->isInvalidDecl()) {
14345       // Don't diagnose unused parameters of defaulted or deleted functions.
14346       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14347         DiagnoseUnusedParameters(FD->parameters());
14348       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14349                                              FD->getReturnType(), FD);
14350 
14351       // If this is a structor, we need a vtable.
14352       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14353         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14354       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14355         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14356 
14357       // Try to apply the named return value optimization. We have to check
14358       // if we can do this here because lambdas keep return statements around
14359       // to deduce an implicit return type.
14360       if (FD->getReturnType()->isRecordType() &&
14361           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14362         computeNRVO(Body, getCurFunction());
14363     }
14364 
14365     // GNU warning -Wmissing-prototypes:
14366     //   Warn if a global function is defined without a previous
14367     //   prototype declaration. This warning is issued even if the
14368     //   definition itself provides a prototype. The aim is to detect
14369     //   global functions that fail to be declared in header files.
14370     const FunctionDecl *PossiblePrototype = nullptr;
14371     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14372       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14373 
14374       if (PossiblePrototype) {
14375         // We found a declaration that is not a prototype,
14376         // but that could be a zero-parameter prototype
14377         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14378           TypeLoc TL = TI->getTypeLoc();
14379           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14380             Diag(PossiblePrototype->getLocation(),
14381                  diag::note_declaration_not_a_prototype)
14382                 << (FD->getNumParams() != 0)
14383                 << (FD->getNumParams() == 0
14384                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14385                         : FixItHint{});
14386         }
14387       } else {
14388         // Returns true if the token beginning at this Loc is `const`.
14389         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14390                                 const LangOptions &LangOpts) {
14391           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14392           if (LocInfo.first.isInvalid())
14393             return false;
14394 
14395           bool Invalid = false;
14396           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14397           if (Invalid)
14398             return false;
14399 
14400           if (LocInfo.second > Buffer.size())
14401             return false;
14402 
14403           const char *LexStart = Buffer.data() + LocInfo.second;
14404           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14405 
14406           return StartTok.consume_front("const") &&
14407                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14408                   StartTok.startswith("/*") || StartTok.startswith("//"));
14409         };
14410 
14411         auto findBeginLoc = [&]() {
14412           // If the return type has `const` qualifier, we want to insert
14413           // `static` before `const` (and not before the typename).
14414           if ((FD->getReturnType()->isAnyPointerType() &&
14415                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14416               FD->getReturnType().isConstQualified()) {
14417             // But only do this if we can determine where the `const` is.
14418 
14419             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14420                              getLangOpts()))
14421 
14422               return FD->getBeginLoc();
14423           }
14424           return FD->getTypeSpecStartLoc();
14425         };
14426         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14427             << /* function */ 1
14428             << (FD->getStorageClass() == SC_None
14429                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14430                     : FixItHint{});
14431       }
14432 
14433       // GNU warning -Wstrict-prototypes
14434       //   Warn if K&R function is defined without a previous declaration.
14435       //   This warning is issued only if the definition itself does not provide
14436       //   a prototype. Only K&R definitions do not provide a prototype.
14437       if (!FD->hasWrittenPrototype()) {
14438         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14439         TypeLoc TL = TI->getTypeLoc();
14440         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14441         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14442       }
14443     }
14444 
14445     // Warn on CPUDispatch with an actual body.
14446     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14447       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14448         if (!CmpndBody->body_empty())
14449           Diag(CmpndBody->body_front()->getBeginLoc(),
14450                diag::warn_dispatch_body_ignored);
14451 
14452     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14453       const CXXMethodDecl *KeyFunction;
14454       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14455           MD->isVirtual() &&
14456           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14457           MD == KeyFunction->getCanonicalDecl()) {
14458         // Update the key-function state if necessary for this ABI.
14459         if (FD->isInlined() &&
14460             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14461           Context.setNonKeyFunction(MD);
14462 
14463           // If the newly-chosen key function is already defined, then we
14464           // need to mark the vtable as used retroactively.
14465           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14466           const FunctionDecl *Definition;
14467           if (KeyFunction && KeyFunction->isDefined(Definition))
14468             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14469         } else {
14470           // We just defined they key function; mark the vtable as used.
14471           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14472         }
14473       }
14474     }
14475 
14476     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14477            "Function parsing confused");
14478   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14479     assert(MD == getCurMethodDecl() && "Method parsing confused");
14480     MD->setBody(Body);
14481     if (!MD->isInvalidDecl()) {
14482       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14483                                              MD->getReturnType(), MD);
14484 
14485       if (Body)
14486         computeNRVO(Body, getCurFunction());
14487     }
14488     if (getCurFunction()->ObjCShouldCallSuper) {
14489       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14490           << MD->getSelector().getAsString();
14491       getCurFunction()->ObjCShouldCallSuper = false;
14492     }
14493     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14494       const ObjCMethodDecl *InitMethod = nullptr;
14495       bool isDesignated =
14496           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14497       assert(isDesignated && InitMethod);
14498       (void)isDesignated;
14499 
14500       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14501         auto IFace = MD->getClassInterface();
14502         if (!IFace)
14503           return false;
14504         auto SuperD = IFace->getSuperClass();
14505         if (!SuperD)
14506           return false;
14507         return SuperD->getIdentifier() ==
14508             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14509       };
14510       // Don't issue this warning for unavailable inits or direct subclasses
14511       // of NSObject.
14512       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14513         Diag(MD->getLocation(),
14514              diag::warn_objc_designated_init_missing_super_call);
14515         Diag(InitMethod->getLocation(),
14516              diag::note_objc_designated_init_marked_here);
14517       }
14518       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14519     }
14520     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14521       // Don't issue this warning for unavaialable inits.
14522       if (!MD->isUnavailable())
14523         Diag(MD->getLocation(),
14524              diag::warn_objc_secondary_init_missing_init_call);
14525       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14526     }
14527 
14528     diagnoseImplicitlyRetainedSelf(*this);
14529   } else {
14530     // Parsing the function declaration failed in some way. Pop the fake scope
14531     // we pushed on.
14532     PopFunctionScopeInfo(ActivePolicy, dcl);
14533     return nullptr;
14534   }
14535 
14536   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14537     DiagnoseUnguardedAvailabilityViolations(dcl);
14538 
14539   assert(!getCurFunction()->ObjCShouldCallSuper &&
14540          "This should only be set for ObjC methods, which should have been "
14541          "handled in the block above.");
14542 
14543   // Verify and clean out per-function state.
14544   if (Body && (!FD || !FD->isDefaulted())) {
14545     // C++ constructors that have function-try-blocks can't have return
14546     // statements in the handlers of that block. (C++ [except.handle]p14)
14547     // Verify this.
14548     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14549       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14550 
14551     // Verify that gotos and switch cases don't jump into scopes illegally.
14552     if (getCurFunction()->NeedsScopeChecking() &&
14553         !PP.isCodeCompletionEnabled())
14554       DiagnoseInvalidJumps(Body);
14555 
14556     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14557       if (!Destructor->getParent()->isDependentType())
14558         CheckDestructor(Destructor);
14559 
14560       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14561                                              Destructor->getParent());
14562     }
14563 
14564     // If any errors have occurred, clear out any temporaries that may have
14565     // been leftover. This ensures that these temporaries won't be picked up for
14566     // deletion in some later function.
14567     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14568         getDiagnostics().getSuppressAllDiagnostics()) {
14569       DiscardCleanupsInEvaluationContext();
14570     }
14571     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14572         !isa<FunctionTemplateDecl>(dcl)) {
14573       // Since the body is valid, issue any analysis-based warnings that are
14574       // enabled.
14575       ActivePolicy = &WP;
14576     }
14577 
14578     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14579         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14580       FD->setInvalidDecl();
14581 
14582     if (FD && FD->hasAttr<NakedAttr>()) {
14583       for (const Stmt *S : Body->children()) {
14584         // Allow local register variables without initializer as they don't
14585         // require prologue.
14586         bool RegisterVariables = false;
14587         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14588           for (const auto *Decl : DS->decls()) {
14589             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14590               RegisterVariables =
14591                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14592               if (!RegisterVariables)
14593                 break;
14594             }
14595           }
14596         }
14597         if (RegisterVariables)
14598           continue;
14599         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14600           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14601           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14602           FD->setInvalidDecl();
14603           break;
14604         }
14605       }
14606     }
14607 
14608     assert(ExprCleanupObjects.size() ==
14609                ExprEvalContexts.back().NumCleanupObjects &&
14610            "Leftover temporaries in function");
14611     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14612     assert(MaybeODRUseExprs.empty() &&
14613            "Leftover expressions for odr-use checking");
14614   }
14615 
14616   if (!IsInstantiation)
14617     PopDeclContext();
14618 
14619   PopFunctionScopeInfo(ActivePolicy, dcl);
14620   // If any errors have occurred, clear out any temporaries that may have
14621   // been leftover. This ensures that these temporaries won't be picked up for
14622   // deletion in some later function.
14623   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14624     DiscardCleanupsInEvaluationContext();
14625   }
14626 
14627   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14628     auto ES = getEmissionStatus(FD);
14629     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14630         ES == Sema::FunctionEmissionStatus::Unknown)
14631       DeclsToCheckForDeferredDiags.push_back(FD);
14632   }
14633 
14634   return dcl;
14635 }
14636 
14637 /// When we finish delayed parsing of an attribute, we must attach it to the
14638 /// relevant Decl.
14639 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14640                                        ParsedAttributes &Attrs) {
14641   // Always attach attributes to the underlying decl.
14642   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14643     D = TD->getTemplatedDecl();
14644   ProcessDeclAttributeList(S, D, Attrs);
14645 
14646   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14647     if (Method->isStatic())
14648       checkThisInStaticMemberFunctionAttributes(Method);
14649 }
14650 
14651 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14652 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14653 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14654                                           IdentifierInfo &II, Scope *S) {
14655   // Find the scope in which the identifier is injected and the corresponding
14656   // DeclContext.
14657   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14658   // In that case, we inject the declaration into the translation unit scope
14659   // instead.
14660   Scope *BlockScope = S;
14661   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14662     BlockScope = BlockScope->getParent();
14663 
14664   Scope *ContextScope = BlockScope;
14665   while (!ContextScope->getEntity())
14666     ContextScope = ContextScope->getParent();
14667   ContextRAII SavedContext(*this, ContextScope->getEntity());
14668 
14669   // Before we produce a declaration for an implicitly defined
14670   // function, see whether there was a locally-scoped declaration of
14671   // this name as a function or variable. If so, use that
14672   // (non-visible) declaration, and complain about it.
14673   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14674   if (ExternCPrev) {
14675     // We still need to inject the function into the enclosing block scope so
14676     // that later (non-call) uses can see it.
14677     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14678 
14679     // C89 footnote 38:
14680     //   If in fact it is not defined as having type "function returning int",
14681     //   the behavior is undefined.
14682     if (!isa<FunctionDecl>(ExternCPrev) ||
14683         !Context.typesAreCompatible(
14684             cast<FunctionDecl>(ExternCPrev)->getType(),
14685             Context.getFunctionNoProtoType(Context.IntTy))) {
14686       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14687           << ExternCPrev << !getLangOpts().C99;
14688       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14689       return ExternCPrev;
14690     }
14691   }
14692 
14693   // Extension in C99.  Legal in C90, but warn about it.
14694   unsigned diag_id;
14695   if (II.getName().startswith("__builtin_"))
14696     diag_id = diag::warn_builtin_unknown;
14697   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14698   else if (getLangOpts().OpenCL)
14699     diag_id = diag::err_opencl_implicit_function_decl;
14700   else if (getLangOpts().C99)
14701     diag_id = diag::ext_implicit_function_decl;
14702   else
14703     diag_id = diag::warn_implicit_function_decl;
14704   Diag(Loc, diag_id) << &II;
14705 
14706   // If we found a prior declaration of this function, don't bother building
14707   // another one. We've already pushed that one into scope, so there's nothing
14708   // more to do.
14709   if (ExternCPrev)
14710     return ExternCPrev;
14711 
14712   // Because typo correction is expensive, only do it if the implicit
14713   // function declaration is going to be treated as an error.
14714   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14715     TypoCorrection Corrected;
14716     DeclFilterCCC<FunctionDecl> CCC{};
14717     if (S && (Corrected =
14718                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14719                               S, nullptr, CCC, CTK_NonError)))
14720       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14721                    /*ErrorRecovery*/false);
14722   }
14723 
14724   // Set a Declarator for the implicit definition: int foo();
14725   const char *Dummy;
14726   AttributeFactory attrFactory;
14727   DeclSpec DS(attrFactory);
14728   unsigned DiagID;
14729   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14730                                   Context.getPrintingPolicy());
14731   (void)Error; // Silence warning.
14732   assert(!Error && "Error setting up implicit decl!");
14733   SourceLocation NoLoc;
14734   Declarator D(DS, DeclaratorContext::BlockContext);
14735   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14736                                              /*IsAmbiguous=*/false,
14737                                              /*LParenLoc=*/NoLoc,
14738                                              /*Params=*/nullptr,
14739                                              /*NumParams=*/0,
14740                                              /*EllipsisLoc=*/NoLoc,
14741                                              /*RParenLoc=*/NoLoc,
14742                                              /*RefQualifierIsLvalueRef=*/true,
14743                                              /*RefQualifierLoc=*/NoLoc,
14744                                              /*MutableLoc=*/NoLoc, EST_None,
14745                                              /*ESpecRange=*/SourceRange(),
14746                                              /*Exceptions=*/nullptr,
14747                                              /*ExceptionRanges=*/nullptr,
14748                                              /*NumExceptions=*/0,
14749                                              /*NoexceptExpr=*/nullptr,
14750                                              /*ExceptionSpecTokens=*/nullptr,
14751                                              /*DeclsInPrototype=*/None, Loc,
14752                                              Loc, D),
14753                 std::move(DS.getAttributes()), SourceLocation());
14754   D.SetIdentifier(&II, Loc);
14755 
14756   // Insert this function into the enclosing block scope.
14757   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14758   FD->setImplicit();
14759 
14760   AddKnownFunctionAttributes(FD);
14761 
14762   return FD;
14763 }
14764 
14765 /// If this function is a C++ replaceable global allocation function
14766 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14767 /// adds any function attributes that we know a priori based on the standard.
14768 ///
14769 /// We need to check for duplicate attributes both here and where user-written
14770 /// attributes are applied to declarations.
14771 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14772     FunctionDecl *FD) {
14773   if (FD->isInvalidDecl())
14774     return;
14775 
14776   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14777       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14778     return;
14779 
14780   Optional<unsigned> AlignmentParam;
14781   bool IsNothrow = false;
14782   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14783     return;
14784 
14785   // C++2a [basic.stc.dynamic.allocation]p4:
14786   //   An allocation function that has a non-throwing exception specification
14787   //   indicates failure by returning a null pointer value. Any other allocation
14788   //   function never returns a null pointer value and indicates failure only by
14789   //   throwing an exception [...]
14790   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14791     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14792 
14793   // C++2a [basic.stc.dynamic.allocation]p2:
14794   //   An allocation function attempts to allocate the requested amount of
14795   //   storage. [...] If the request succeeds, the value returned by a
14796   //   replaceable allocation function is a [...] pointer value p0 different
14797   //   from any previously returned value p1 [...]
14798   //
14799   // However, this particular information is being added in codegen,
14800   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14801 
14802   // C++2a [basic.stc.dynamic.allocation]p2:
14803   //   An allocation function attempts to allocate the requested amount of
14804   //   storage. If it is successful, it returns the address of the start of a
14805   //   block of storage whose length in bytes is at least as large as the
14806   //   requested size.
14807   if (!FD->hasAttr<AllocSizeAttr>()) {
14808     FD->addAttr(AllocSizeAttr::CreateImplicit(
14809         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14810         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14811   }
14812 
14813   // C++2a [basic.stc.dynamic.allocation]p3:
14814   //   For an allocation function [...], the pointer returned on a successful
14815   //   call shall represent the address of storage that is aligned as follows:
14816   //   (3.1) If the allocation function takes an argument of type
14817   //         std​::​align_­val_­t, the storage will have the alignment
14818   //         specified by the value of this argument.
14819   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14820     FD->addAttr(AllocAlignAttr::CreateImplicit(
14821         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14822   }
14823 
14824   // FIXME:
14825   // C++2a [basic.stc.dynamic.allocation]p3:
14826   //   For an allocation function [...], the pointer returned on a successful
14827   //   call shall represent the address of storage that is aligned as follows:
14828   //   (3.2) Otherwise, if the allocation function is named operator new[],
14829   //         the storage is aligned for any object that does not have
14830   //         new-extended alignment ([basic.align]) and is no larger than the
14831   //         requested size.
14832   //   (3.3) Otherwise, the storage is aligned for any object that does not
14833   //         have new-extended alignment and is of the requested size.
14834 }
14835 
14836 /// Adds any function attributes that we know a priori based on
14837 /// the declaration of this function.
14838 ///
14839 /// These attributes can apply both to implicitly-declared builtins
14840 /// (like __builtin___printf_chk) or to library-declared functions
14841 /// like NSLog or printf.
14842 ///
14843 /// We need to check for duplicate attributes both here and where user-written
14844 /// attributes are applied to declarations.
14845 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14846   if (FD->isInvalidDecl())
14847     return;
14848 
14849   // If this is a built-in function, map its builtin attributes to
14850   // actual attributes.
14851   if (unsigned BuiltinID = FD->getBuiltinID()) {
14852     // Handle printf-formatting attributes.
14853     unsigned FormatIdx;
14854     bool HasVAListArg;
14855     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14856       if (!FD->hasAttr<FormatAttr>()) {
14857         const char *fmt = "printf";
14858         unsigned int NumParams = FD->getNumParams();
14859         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14860             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14861           fmt = "NSString";
14862         FD->addAttr(FormatAttr::CreateImplicit(Context,
14863                                                &Context.Idents.get(fmt),
14864                                                FormatIdx+1,
14865                                                HasVAListArg ? 0 : FormatIdx+2,
14866                                                FD->getLocation()));
14867       }
14868     }
14869     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14870                                              HasVAListArg)) {
14871      if (!FD->hasAttr<FormatAttr>())
14872        FD->addAttr(FormatAttr::CreateImplicit(Context,
14873                                               &Context.Idents.get("scanf"),
14874                                               FormatIdx+1,
14875                                               HasVAListArg ? 0 : FormatIdx+2,
14876                                               FD->getLocation()));
14877     }
14878 
14879     // Handle automatically recognized callbacks.
14880     SmallVector<int, 4> Encoding;
14881     if (!FD->hasAttr<CallbackAttr>() &&
14882         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14883       FD->addAttr(CallbackAttr::CreateImplicit(
14884           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14885 
14886     // Mark const if we don't care about errno and that is the only thing
14887     // preventing the function from being const. This allows IRgen to use LLVM
14888     // intrinsics for such functions.
14889     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14890         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14891       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14892 
14893     // We make "fma" on some platforms const because we know it does not set
14894     // errno in those environments even though it could set errno based on the
14895     // C standard.
14896     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14897     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14898         !FD->hasAttr<ConstAttr>()) {
14899       switch (BuiltinID) {
14900       case Builtin::BI__builtin_fma:
14901       case Builtin::BI__builtin_fmaf:
14902       case Builtin::BI__builtin_fmal:
14903       case Builtin::BIfma:
14904       case Builtin::BIfmaf:
14905       case Builtin::BIfmal:
14906         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14907         break;
14908       default:
14909         break;
14910       }
14911     }
14912 
14913     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14914         !FD->hasAttr<ReturnsTwiceAttr>())
14915       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14916                                          FD->getLocation()));
14917     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14918       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14919     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14920       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14921     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14922       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14923     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14924         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14925       // Add the appropriate attribute, depending on the CUDA compilation mode
14926       // and which target the builtin belongs to. For example, during host
14927       // compilation, aux builtins are __device__, while the rest are __host__.
14928       if (getLangOpts().CUDAIsDevice !=
14929           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14930         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14931       else
14932         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14933     }
14934   }
14935 
14936   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14937 
14938   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14939   // throw, add an implicit nothrow attribute to any extern "C" function we come
14940   // across.
14941   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14942       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14943     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14944     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14945       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14946   }
14947 
14948   IdentifierInfo *Name = FD->getIdentifier();
14949   if (!Name)
14950     return;
14951   if ((!getLangOpts().CPlusPlus &&
14952        FD->getDeclContext()->isTranslationUnit()) ||
14953       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14954        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14955        LinkageSpecDecl::lang_c)) {
14956     // Okay: this could be a libc/libm/Objective-C function we know
14957     // about.
14958   } else
14959     return;
14960 
14961   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14962     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14963     // target-specific builtins, perhaps?
14964     if (!FD->hasAttr<FormatAttr>())
14965       FD->addAttr(FormatAttr::CreateImplicit(Context,
14966                                              &Context.Idents.get("printf"), 2,
14967                                              Name->isStr("vasprintf") ? 0 : 3,
14968                                              FD->getLocation()));
14969   }
14970 
14971   if (Name->isStr("__CFStringMakeConstantString")) {
14972     // We already have a __builtin___CFStringMakeConstantString,
14973     // but builds that use -fno-constant-cfstrings don't go through that.
14974     if (!FD->hasAttr<FormatArgAttr>())
14975       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14976                                                 FD->getLocation()));
14977   }
14978 }
14979 
14980 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14981                                     TypeSourceInfo *TInfo) {
14982   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14983   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14984 
14985   if (!TInfo) {
14986     assert(D.isInvalidType() && "no declarator info for valid type");
14987     TInfo = Context.getTrivialTypeSourceInfo(T);
14988   }
14989 
14990   // Scope manipulation handled by caller.
14991   TypedefDecl *NewTD =
14992       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14993                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14994 
14995   // Bail out immediately if we have an invalid declaration.
14996   if (D.isInvalidType()) {
14997     NewTD->setInvalidDecl();
14998     return NewTD;
14999   }
15000 
15001   if (D.getDeclSpec().isModulePrivateSpecified()) {
15002     if (CurContext->isFunctionOrMethod())
15003       Diag(NewTD->getLocation(), diag::err_module_private_local)
15004           << 2 << NewTD
15005           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15006           << FixItHint::CreateRemoval(
15007                  D.getDeclSpec().getModulePrivateSpecLoc());
15008     else
15009       NewTD->setModulePrivate();
15010   }
15011 
15012   // C++ [dcl.typedef]p8:
15013   //   If the typedef declaration defines an unnamed class (or
15014   //   enum), the first typedef-name declared by the declaration
15015   //   to be that class type (or enum type) is used to denote the
15016   //   class type (or enum type) for linkage purposes only.
15017   // We need to check whether the type was declared in the declaration.
15018   switch (D.getDeclSpec().getTypeSpecType()) {
15019   case TST_enum:
15020   case TST_struct:
15021   case TST_interface:
15022   case TST_union:
15023   case TST_class: {
15024     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15025     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15026     break;
15027   }
15028 
15029   default:
15030     break;
15031   }
15032 
15033   return NewTD;
15034 }
15035 
15036 /// Check that this is a valid underlying type for an enum declaration.
15037 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15038   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15039   QualType T = TI->getType();
15040 
15041   if (T->isDependentType())
15042     return false;
15043 
15044   // This doesn't use 'isIntegralType' despite the error message mentioning
15045   // integral type because isIntegralType would also allow enum types in C.
15046   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15047     if (BT->isInteger())
15048       return false;
15049 
15050   if (T->isExtIntType())
15051     return false;
15052 
15053   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15054 }
15055 
15056 /// Check whether this is a valid redeclaration of a previous enumeration.
15057 /// \return true if the redeclaration was invalid.
15058 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15059                                   QualType EnumUnderlyingTy, bool IsFixed,
15060                                   const EnumDecl *Prev) {
15061   if (IsScoped != Prev->isScoped()) {
15062     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15063       << Prev->isScoped();
15064     Diag(Prev->getLocation(), diag::note_previous_declaration);
15065     return true;
15066   }
15067 
15068   if (IsFixed && Prev->isFixed()) {
15069     if (!EnumUnderlyingTy->isDependentType() &&
15070         !Prev->getIntegerType()->isDependentType() &&
15071         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15072                                         Prev->getIntegerType())) {
15073       // TODO: Highlight the underlying type of the redeclaration.
15074       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15075         << EnumUnderlyingTy << Prev->getIntegerType();
15076       Diag(Prev->getLocation(), diag::note_previous_declaration)
15077           << Prev->getIntegerTypeRange();
15078       return true;
15079     }
15080   } else if (IsFixed != Prev->isFixed()) {
15081     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15082       << Prev->isFixed();
15083     Diag(Prev->getLocation(), diag::note_previous_declaration);
15084     return true;
15085   }
15086 
15087   return false;
15088 }
15089 
15090 /// Get diagnostic %select index for tag kind for
15091 /// redeclaration diagnostic message.
15092 /// WARNING: Indexes apply to particular diagnostics only!
15093 ///
15094 /// \returns diagnostic %select index.
15095 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15096   switch (Tag) {
15097   case TTK_Struct: return 0;
15098   case TTK_Interface: return 1;
15099   case TTK_Class:  return 2;
15100   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15101   }
15102 }
15103 
15104 /// Determine if tag kind is a class-key compatible with
15105 /// class for redeclaration (class, struct, or __interface).
15106 ///
15107 /// \returns true iff the tag kind is compatible.
15108 static bool isClassCompatTagKind(TagTypeKind Tag)
15109 {
15110   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15111 }
15112 
15113 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15114                                              TagTypeKind TTK) {
15115   if (isa<TypedefDecl>(PrevDecl))
15116     return NTK_Typedef;
15117   else if (isa<TypeAliasDecl>(PrevDecl))
15118     return NTK_TypeAlias;
15119   else if (isa<ClassTemplateDecl>(PrevDecl))
15120     return NTK_Template;
15121   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15122     return NTK_TypeAliasTemplate;
15123   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15124     return NTK_TemplateTemplateArgument;
15125   switch (TTK) {
15126   case TTK_Struct:
15127   case TTK_Interface:
15128   case TTK_Class:
15129     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15130   case TTK_Union:
15131     return NTK_NonUnion;
15132   case TTK_Enum:
15133     return NTK_NonEnum;
15134   }
15135   llvm_unreachable("invalid TTK");
15136 }
15137 
15138 /// Determine whether a tag with a given kind is acceptable
15139 /// as a redeclaration of the given tag declaration.
15140 ///
15141 /// \returns true if the new tag kind is acceptable, false otherwise.
15142 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15143                                         TagTypeKind NewTag, bool isDefinition,
15144                                         SourceLocation NewTagLoc,
15145                                         const IdentifierInfo *Name) {
15146   // C++ [dcl.type.elab]p3:
15147   //   The class-key or enum keyword present in the
15148   //   elaborated-type-specifier shall agree in kind with the
15149   //   declaration to which the name in the elaborated-type-specifier
15150   //   refers. This rule also applies to the form of
15151   //   elaborated-type-specifier that declares a class-name or
15152   //   friend class since it can be construed as referring to the
15153   //   definition of the class. Thus, in any
15154   //   elaborated-type-specifier, the enum keyword shall be used to
15155   //   refer to an enumeration (7.2), the union class-key shall be
15156   //   used to refer to a union (clause 9), and either the class or
15157   //   struct class-key shall be used to refer to a class (clause 9)
15158   //   declared using the class or struct class-key.
15159   TagTypeKind OldTag = Previous->getTagKind();
15160   if (OldTag != NewTag &&
15161       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15162     return false;
15163 
15164   // Tags are compatible, but we might still want to warn on mismatched tags.
15165   // Non-class tags can't be mismatched at this point.
15166   if (!isClassCompatTagKind(NewTag))
15167     return true;
15168 
15169   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15170   // by our warning analysis. We don't want to warn about mismatches with (eg)
15171   // declarations in system headers that are designed to be specialized, but if
15172   // a user asks us to warn, we should warn if their code contains mismatched
15173   // declarations.
15174   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15175     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15176                                       Loc);
15177   };
15178   if (IsIgnoredLoc(NewTagLoc))
15179     return true;
15180 
15181   auto IsIgnored = [&](const TagDecl *Tag) {
15182     return IsIgnoredLoc(Tag->getLocation());
15183   };
15184   while (IsIgnored(Previous)) {
15185     Previous = Previous->getPreviousDecl();
15186     if (!Previous)
15187       return true;
15188     OldTag = Previous->getTagKind();
15189   }
15190 
15191   bool isTemplate = false;
15192   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15193     isTemplate = Record->getDescribedClassTemplate();
15194 
15195   if (inTemplateInstantiation()) {
15196     if (OldTag != NewTag) {
15197       // In a template instantiation, do not offer fix-its for tag mismatches
15198       // since they usually mess up the template instead of fixing the problem.
15199       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15200         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15201         << getRedeclDiagFromTagKind(OldTag);
15202       // FIXME: Note previous location?
15203     }
15204     return true;
15205   }
15206 
15207   if (isDefinition) {
15208     // On definitions, check all previous tags and issue a fix-it for each
15209     // one that doesn't match the current tag.
15210     if (Previous->getDefinition()) {
15211       // Don't suggest fix-its for redefinitions.
15212       return true;
15213     }
15214 
15215     bool previousMismatch = false;
15216     for (const TagDecl *I : Previous->redecls()) {
15217       if (I->getTagKind() != NewTag) {
15218         // Ignore previous declarations for which the warning was disabled.
15219         if (IsIgnored(I))
15220           continue;
15221 
15222         if (!previousMismatch) {
15223           previousMismatch = true;
15224           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15225             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15226             << getRedeclDiagFromTagKind(I->getTagKind());
15227         }
15228         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15229           << getRedeclDiagFromTagKind(NewTag)
15230           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15231                TypeWithKeyword::getTagTypeKindName(NewTag));
15232       }
15233     }
15234     return true;
15235   }
15236 
15237   // Identify the prevailing tag kind: this is the kind of the definition (if
15238   // there is a non-ignored definition), or otherwise the kind of the prior
15239   // (non-ignored) declaration.
15240   const TagDecl *PrevDef = Previous->getDefinition();
15241   if (PrevDef && IsIgnored(PrevDef))
15242     PrevDef = nullptr;
15243   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15244   if (Redecl->getTagKind() != NewTag) {
15245     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15246       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15247       << getRedeclDiagFromTagKind(OldTag);
15248     Diag(Redecl->getLocation(), diag::note_previous_use);
15249 
15250     // If there is a previous definition, suggest a fix-it.
15251     if (PrevDef) {
15252       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15253         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15254         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15255              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15256     }
15257   }
15258 
15259   return true;
15260 }
15261 
15262 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15263 /// from an outer enclosing namespace or file scope inside a friend declaration.
15264 /// This should provide the commented out code in the following snippet:
15265 ///   namespace N {
15266 ///     struct X;
15267 ///     namespace M {
15268 ///       struct Y { friend struct /*N::*/ X; };
15269 ///     }
15270 ///   }
15271 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15272                                          SourceLocation NameLoc) {
15273   // While the decl is in a namespace, do repeated lookup of that name and see
15274   // if we get the same namespace back.  If we do not, continue until
15275   // translation unit scope, at which point we have a fully qualified NNS.
15276   SmallVector<IdentifierInfo *, 4> Namespaces;
15277   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15278   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15279     // This tag should be declared in a namespace, which can only be enclosed by
15280     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15281     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15282     if (!Namespace || Namespace->isAnonymousNamespace())
15283       return FixItHint();
15284     IdentifierInfo *II = Namespace->getIdentifier();
15285     Namespaces.push_back(II);
15286     NamedDecl *Lookup = SemaRef.LookupSingleName(
15287         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15288     if (Lookup == Namespace)
15289       break;
15290   }
15291 
15292   // Once we have all the namespaces, reverse them to go outermost first, and
15293   // build an NNS.
15294   SmallString<64> Insertion;
15295   llvm::raw_svector_ostream OS(Insertion);
15296   if (DC->isTranslationUnit())
15297     OS << "::";
15298   std::reverse(Namespaces.begin(), Namespaces.end());
15299   for (auto *II : Namespaces)
15300     OS << II->getName() << "::";
15301   return FixItHint::CreateInsertion(NameLoc, Insertion);
15302 }
15303 
15304 /// Determine whether a tag originally declared in context \p OldDC can
15305 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15306 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15307 /// using-declaration).
15308 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15309                                          DeclContext *NewDC) {
15310   OldDC = OldDC->getRedeclContext();
15311   NewDC = NewDC->getRedeclContext();
15312 
15313   if (OldDC->Equals(NewDC))
15314     return true;
15315 
15316   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15317   // encloses the other).
15318   if (S.getLangOpts().MSVCCompat &&
15319       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15320     return true;
15321 
15322   return false;
15323 }
15324 
15325 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15326 /// former case, Name will be non-null.  In the later case, Name will be null.
15327 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15328 /// reference/declaration/definition of a tag.
15329 ///
15330 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15331 /// trailing-type-specifier) other than one in an alias-declaration.
15332 ///
15333 /// \param SkipBody If non-null, will be set to indicate if the caller should
15334 /// skip the definition of this tag and treat it as if it were a declaration.
15335 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15336                      SourceLocation KWLoc, CXXScopeSpec &SS,
15337                      IdentifierInfo *Name, SourceLocation NameLoc,
15338                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15339                      SourceLocation ModulePrivateLoc,
15340                      MultiTemplateParamsArg TemplateParameterLists,
15341                      bool &OwnedDecl, bool &IsDependent,
15342                      SourceLocation ScopedEnumKWLoc,
15343                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15344                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15345                      SkipBodyInfo *SkipBody) {
15346   // If this is not a definition, it must have a name.
15347   IdentifierInfo *OrigName = Name;
15348   assert((Name != nullptr || TUK == TUK_Definition) &&
15349          "Nameless record must be a definition!");
15350   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15351 
15352   OwnedDecl = false;
15353   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15354   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15355 
15356   // FIXME: Check member specializations more carefully.
15357   bool isMemberSpecialization = false;
15358   bool Invalid = false;
15359 
15360   // We only need to do this matching if we have template parameters
15361   // or a scope specifier, which also conveniently avoids this work
15362   // for non-C++ cases.
15363   if (TemplateParameterLists.size() > 0 ||
15364       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15365     if (TemplateParameterList *TemplateParams =
15366             MatchTemplateParametersToScopeSpecifier(
15367                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15368                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15369       if (Kind == TTK_Enum) {
15370         Diag(KWLoc, diag::err_enum_template);
15371         return nullptr;
15372       }
15373 
15374       if (TemplateParams->size() > 0) {
15375         // This is a declaration or definition of a class template (which may
15376         // be a member of another template).
15377 
15378         if (Invalid)
15379           return nullptr;
15380 
15381         OwnedDecl = false;
15382         DeclResult Result = CheckClassTemplate(
15383             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15384             AS, ModulePrivateLoc,
15385             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15386             TemplateParameterLists.data(), SkipBody);
15387         return Result.get();
15388       } else {
15389         // The "template<>" header is extraneous.
15390         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15391           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15392         isMemberSpecialization = true;
15393       }
15394     }
15395 
15396     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15397         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15398       return nullptr;
15399   }
15400 
15401   // Figure out the underlying type if this a enum declaration. We need to do
15402   // this early, because it's needed to detect if this is an incompatible
15403   // redeclaration.
15404   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15405   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15406 
15407   if (Kind == TTK_Enum) {
15408     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15409       // No underlying type explicitly specified, or we failed to parse the
15410       // type, default to int.
15411       EnumUnderlying = Context.IntTy.getTypePtr();
15412     } else if (UnderlyingType.get()) {
15413       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15414       // integral type; any cv-qualification is ignored.
15415       TypeSourceInfo *TI = nullptr;
15416       GetTypeFromParser(UnderlyingType.get(), &TI);
15417       EnumUnderlying = TI;
15418 
15419       if (CheckEnumUnderlyingType(TI))
15420         // Recover by falling back to int.
15421         EnumUnderlying = Context.IntTy.getTypePtr();
15422 
15423       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15424                                           UPPC_FixedUnderlyingType))
15425         EnumUnderlying = Context.IntTy.getTypePtr();
15426 
15427     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15428       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15429       // of 'int'. However, if this is an unfixed forward declaration, don't set
15430       // the underlying type unless the user enables -fms-compatibility. This
15431       // makes unfixed forward declared enums incomplete and is more conforming.
15432       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15433         EnumUnderlying = Context.IntTy.getTypePtr();
15434     }
15435   }
15436 
15437   DeclContext *SearchDC = CurContext;
15438   DeclContext *DC = CurContext;
15439   bool isStdBadAlloc = false;
15440   bool isStdAlignValT = false;
15441 
15442   RedeclarationKind Redecl = forRedeclarationInCurContext();
15443   if (TUK == TUK_Friend || TUK == TUK_Reference)
15444     Redecl = NotForRedeclaration;
15445 
15446   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15447   /// implemented asks for structural equivalence checking, the returned decl
15448   /// here is passed back to the parser, allowing the tag body to be parsed.
15449   auto createTagFromNewDecl = [&]() -> TagDecl * {
15450     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15451     // If there is an identifier, use the location of the identifier as the
15452     // location of the decl, otherwise use the location of the struct/union
15453     // keyword.
15454     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15455     TagDecl *New = nullptr;
15456 
15457     if (Kind == TTK_Enum) {
15458       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15459                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15460       // If this is an undefined enum, bail.
15461       if (TUK != TUK_Definition && !Invalid)
15462         return nullptr;
15463       if (EnumUnderlying) {
15464         EnumDecl *ED = cast<EnumDecl>(New);
15465         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15466           ED->setIntegerTypeSourceInfo(TI);
15467         else
15468           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15469         ED->setPromotionType(ED->getIntegerType());
15470       }
15471     } else { // struct/union
15472       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15473                                nullptr);
15474     }
15475 
15476     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15477       // Add alignment attributes if necessary; these attributes are checked
15478       // when the ASTContext lays out the structure.
15479       //
15480       // It is important for implementing the correct semantics that this
15481       // happen here (in ActOnTag). The #pragma pack stack is
15482       // maintained as a result of parser callbacks which can occur at
15483       // many points during the parsing of a struct declaration (because
15484       // the #pragma tokens are effectively skipped over during the
15485       // parsing of the struct).
15486       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15487         AddAlignmentAttributesForRecord(RD);
15488         AddMsStructLayoutForRecord(RD);
15489       }
15490     }
15491     New->setLexicalDeclContext(CurContext);
15492     return New;
15493   };
15494 
15495   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15496   if (Name && SS.isNotEmpty()) {
15497     // We have a nested-name tag ('struct foo::bar').
15498 
15499     // Check for invalid 'foo::'.
15500     if (SS.isInvalid()) {
15501       Name = nullptr;
15502       goto CreateNewDecl;
15503     }
15504 
15505     // If this is a friend or a reference to a class in a dependent
15506     // context, don't try to make a decl for it.
15507     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15508       DC = computeDeclContext(SS, false);
15509       if (!DC) {
15510         IsDependent = true;
15511         return nullptr;
15512       }
15513     } else {
15514       DC = computeDeclContext(SS, true);
15515       if (!DC) {
15516         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15517           << SS.getRange();
15518         return nullptr;
15519       }
15520     }
15521 
15522     if (RequireCompleteDeclContext(SS, DC))
15523       return nullptr;
15524 
15525     SearchDC = DC;
15526     // Look-up name inside 'foo::'.
15527     LookupQualifiedName(Previous, DC);
15528 
15529     if (Previous.isAmbiguous())
15530       return nullptr;
15531 
15532     if (Previous.empty()) {
15533       // Name lookup did not find anything. However, if the
15534       // nested-name-specifier refers to the current instantiation,
15535       // and that current instantiation has any dependent base
15536       // classes, we might find something at instantiation time: treat
15537       // this as a dependent elaborated-type-specifier.
15538       // But this only makes any sense for reference-like lookups.
15539       if (Previous.wasNotFoundInCurrentInstantiation() &&
15540           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15541         IsDependent = true;
15542         return nullptr;
15543       }
15544 
15545       // A tag 'foo::bar' must already exist.
15546       Diag(NameLoc, diag::err_not_tag_in_scope)
15547         << Kind << Name << DC << SS.getRange();
15548       Name = nullptr;
15549       Invalid = true;
15550       goto CreateNewDecl;
15551     }
15552   } else if (Name) {
15553     // C++14 [class.mem]p14:
15554     //   If T is the name of a class, then each of the following shall have a
15555     //   name different from T:
15556     //    -- every member of class T that is itself a type
15557     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15558         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15559       return nullptr;
15560 
15561     // If this is a named struct, check to see if there was a previous forward
15562     // declaration or definition.
15563     // FIXME: We're looking into outer scopes here, even when we
15564     // shouldn't be. Doing so can result in ambiguities that we
15565     // shouldn't be diagnosing.
15566     LookupName(Previous, S);
15567 
15568     // When declaring or defining a tag, ignore ambiguities introduced
15569     // by types using'ed into this scope.
15570     if (Previous.isAmbiguous() &&
15571         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15572       LookupResult::Filter F = Previous.makeFilter();
15573       while (F.hasNext()) {
15574         NamedDecl *ND = F.next();
15575         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15576                 SearchDC->getRedeclContext()))
15577           F.erase();
15578       }
15579       F.done();
15580     }
15581 
15582     // C++11 [namespace.memdef]p3:
15583     //   If the name in a friend declaration is neither qualified nor
15584     //   a template-id and the declaration is a function or an
15585     //   elaborated-type-specifier, the lookup to determine whether
15586     //   the entity has been previously declared shall not consider
15587     //   any scopes outside the innermost enclosing namespace.
15588     //
15589     // MSVC doesn't implement the above rule for types, so a friend tag
15590     // declaration may be a redeclaration of a type declared in an enclosing
15591     // scope.  They do implement this rule for friend functions.
15592     //
15593     // Does it matter that this should be by scope instead of by
15594     // semantic context?
15595     if (!Previous.empty() && TUK == TUK_Friend) {
15596       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15597       LookupResult::Filter F = Previous.makeFilter();
15598       bool FriendSawTagOutsideEnclosingNamespace = false;
15599       while (F.hasNext()) {
15600         NamedDecl *ND = F.next();
15601         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15602         if (DC->isFileContext() &&
15603             !EnclosingNS->Encloses(ND->getDeclContext())) {
15604           if (getLangOpts().MSVCCompat)
15605             FriendSawTagOutsideEnclosingNamespace = true;
15606           else
15607             F.erase();
15608         }
15609       }
15610       F.done();
15611 
15612       // Diagnose this MSVC extension in the easy case where lookup would have
15613       // unambiguously found something outside the enclosing namespace.
15614       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15615         NamedDecl *ND = Previous.getFoundDecl();
15616         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15617             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15618       }
15619     }
15620 
15621     // Note:  there used to be some attempt at recovery here.
15622     if (Previous.isAmbiguous())
15623       return nullptr;
15624 
15625     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15626       // FIXME: This makes sure that we ignore the contexts associated
15627       // with C structs, unions, and enums when looking for a matching
15628       // tag declaration or definition. See the similar lookup tweak
15629       // in Sema::LookupName; is there a better way to deal with this?
15630       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15631         SearchDC = SearchDC->getParent();
15632     }
15633   }
15634 
15635   if (Previous.isSingleResult() &&
15636       Previous.getFoundDecl()->isTemplateParameter()) {
15637     // Maybe we will complain about the shadowed template parameter.
15638     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15639     // Just pretend that we didn't see the previous declaration.
15640     Previous.clear();
15641   }
15642 
15643   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15644       DC->Equals(getStdNamespace())) {
15645     if (Name->isStr("bad_alloc")) {
15646       // This is a declaration of or a reference to "std::bad_alloc".
15647       isStdBadAlloc = true;
15648 
15649       // If std::bad_alloc has been implicitly declared (but made invisible to
15650       // name lookup), fill in this implicit declaration as the previous
15651       // declaration, so that the declarations get chained appropriately.
15652       if (Previous.empty() && StdBadAlloc)
15653         Previous.addDecl(getStdBadAlloc());
15654     } else if (Name->isStr("align_val_t")) {
15655       isStdAlignValT = true;
15656       if (Previous.empty() && StdAlignValT)
15657         Previous.addDecl(getStdAlignValT());
15658     }
15659   }
15660 
15661   // If we didn't find a previous declaration, and this is a reference
15662   // (or friend reference), move to the correct scope.  In C++, we
15663   // also need to do a redeclaration lookup there, just in case
15664   // there's a shadow friend decl.
15665   if (Name && Previous.empty() &&
15666       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15667     if (Invalid) goto CreateNewDecl;
15668     assert(SS.isEmpty());
15669 
15670     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15671       // C++ [basic.scope.pdecl]p5:
15672       //   -- for an elaborated-type-specifier of the form
15673       //
15674       //          class-key identifier
15675       //
15676       //      if the elaborated-type-specifier is used in the
15677       //      decl-specifier-seq or parameter-declaration-clause of a
15678       //      function defined in namespace scope, the identifier is
15679       //      declared as a class-name in the namespace that contains
15680       //      the declaration; otherwise, except as a friend
15681       //      declaration, the identifier is declared in the smallest
15682       //      non-class, non-function-prototype scope that contains the
15683       //      declaration.
15684       //
15685       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15686       // C structs and unions.
15687       //
15688       // It is an error in C++ to declare (rather than define) an enum
15689       // type, including via an elaborated type specifier.  We'll
15690       // diagnose that later; for now, declare the enum in the same
15691       // scope as we would have picked for any other tag type.
15692       //
15693       // GNU C also supports this behavior as part of its incomplete
15694       // enum types extension, while GNU C++ does not.
15695       //
15696       // Find the context where we'll be declaring the tag.
15697       // FIXME: We would like to maintain the current DeclContext as the
15698       // lexical context,
15699       SearchDC = getTagInjectionContext(SearchDC);
15700 
15701       // Find the scope where we'll be declaring the tag.
15702       S = getTagInjectionScope(S, getLangOpts());
15703     } else {
15704       assert(TUK == TUK_Friend);
15705       // C++ [namespace.memdef]p3:
15706       //   If a friend declaration in a non-local class first declares a
15707       //   class or function, the friend class or function is a member of
15708       //   the innermost enclosing namespace.
15709       SearchDC = SearchDC->getEnclosingNamespaceContext();
15710     }
15711 
15712     // In C++, we need to do a redeclaration lookup to properly
15713     // diagnose some problems.
15714     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15715     // hidden declaration so that we don't get ambiguity errors when using a
15716     // type declared by an elaborated-type-specifier.  In C that is not correct
15717     // and we should instead merge compatible types found by lookup.
15718     if (getLangOpts().CPlusPlus) {
15719       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15720       LookupQualifiedName(Previous, SearchDC);
15721     } else {
15722       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15723       LookupName(Previous, S);
15724     }
15725   }
15726 
15727   // If we have a known previous declaration to use, then use it.
15728   if (Previous.empty() && SkipBody && SkipBody->Previous)
15729     Previous.addDecl(SkipBody->Previous);
15730 
15731   if (!Previous.empty()) {
15732     NamedDecl *PrevDecl = Previous.getFoundDecl();
15733     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15734 
15735     // It's okay to have a tag decl in the same scope as a typedef
15736     // which hides a tag decl in the same scope.  Finding this
15737     // insanity with a redeclaration lookup can only actually happen
15738     // in C++.
15739     //
15740     // This is also okay for elaborated-type-specifiers, which is
15741     // technically forbidden by the current standard but which is
15742     // okay according to the likely resolution of an open issue;
15743     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15744     if (getLangOpts().CPlusPlus) {
15745       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15746         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15747           TagDecl *Tag = TT->getDecl();
15748           if (Tag->getDeclName() == Name &&
15749               Tag->getDeclContext()->getRedeclContext()
15750                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15751             PrevDecl = Tag;
15752             Previous.clear();
15753             Previous.addDecl(Tag);
15754             Previous.resolveKind();
15755           }
15756         }
15757       }
15758     }
15759 
15760     // If this is a redeclaration of a using shadow declaration, it must
15761     // declare a tag in the same context. In MSVC mode, we allow a
15762     // redefinition if either context is within the other.
15763     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15764       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15765       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15766           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15767           !(OldTag && isAcceptableTagRedeclContext(
15768                           *this, OldTag->getDeclContext(), SearchDC))) {
15769         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15770         Diag(Shadow->getTargetDecl()->getLocation(),
15771              diag::note_using_decl_target);
15772         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15773             << 0;
15774         // Recover by ignoring the old declaration.
15775         Previous.clear();
15776         goto CreateNewDecl;
15777       }
15778     }
15779 
15780     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15781       // If this is a use of a previous tag, or if the tag is already declared
15782       // in the same scope (so that the definition/declaration completes or
15783       // rementions the tag), reuse the decl.
15784       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15785           isDeclInScope(DirectPrevDecl, SearchDC, S,
15786                         SS.isNotEmpty() || isMemberSpecialization)) {
15787         // Make sure that this wasn't declared as an enum and now used as a
15788         // struct or something similar.
15789         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15790                                           TUK == TUK_Definition, KWLoc,
15791                                           Name)) {
15792           bool SafeToContinue
15793             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15794                Kind != TTK_Enum);
15795           if (SafeToContinue)
15796             Diag(KWLoc, diag::err_use_with_wrong_tag)
15797               << Name
15798               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15799                                               PrevTagDecl->getKindName());
15800           else
15801             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15802           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15803 
15804           if (SafeToContinue)
15805             Kind = PrevTagDecl->getTagKind();
15806           else {
15807             // Recover by making this an anonymous redefinition.
15808             Name = nullptr;
15809             Previous.clear();
15810             Invalid = true;
15811           }
15812         }
15813 
15814         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15815           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15816           if (TUK == TUK_Reference || TUK == TUK_Friend)
15817             return PrevTagDecl;
15818 
15819           QualType EnumUnderlyingTy;
15820           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15821             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15822           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15823             EnumUnderlyingTy = QualType(T, 0);
15824 
15825           // All conflicts with previous declarations are recovered by
15826           // returning the previous declaration, unless this is a definition,
15827           // in which case we want the caller to bail out.
15828           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15829                                      ScopedEnum, EnumUnderlyingTy,
15830                                      IsFixed, PrevEnum))
15831             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15832         }
15833 
15834         // C++11 [class.mem]p1:
15835         //   A member shall not be declared twice in the member-specification,
15836         //   except that a nested class or member class template can be declared
15837         //   and then later defined.
15838         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15839             S->isDeclScope(PrevDecl)) {
15840           Diag(NameLoc, diag::ext_member_redeclared);
15841           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15842         }
15843 
15844         if (!Invalid) {
15845           // If this is a use, just return the declaration we found, unless
15846           // we have attributes.
15847           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15848             if (!Attrs.empty()) {
15849               // FIXME: Diagnose these attributes. For now, we create a new
15850               // declaration to hold them.
15851             } else if (TUK == TUK_Reference &&
15852                        (PrevTagDecl->getFriendObjectKind() ==
15853                             Decl::FOK_Undeclared ||
15854                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15855                        SS.isEmpty()) {
15856               // This declaration is a reference to an existing entity, but
15857               // has different visibility from that entity: it either makes
15858               // a friend visible or it makes a type visible in a new module.
15859               // In either case, create a new declaration. We only do this if
15860               // the declaration would have meant the same thing if no prior
15861               // declaration were found, that is, if it was found in the same
15862               // scope where we would have injected a declaration.
15863               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15864                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15865                 return PrevTagDecl;
15866               // This is in the injected scope, create a new declaration in
15867               // that scope.
15868               S = getTagInjectionScope(S, getLangOpts());
15869             } else {
15870               return PrevTagDecl;
15871             }
15872           }
15873 
15874           // Diagnose attempts to redefine a tag.
15875           if (TUK == TUK_Definition) {
15876             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15877               // If we're defining a specialization and the previous definition
15878               // is from an implicit instantiation, don't emit an error
15879               // here; we'll catch this in the general case below.
15880               bool IsExplicitSpecializationAfterInstantiation = false;
15881               if (isMemberSpecialization) {
15882                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15883                   IsExplicitSpecializationAfterInstantiation =
15884                     RD->getTemplateSpecializationKind() !=
15885                     TSK_ExplicitSpecialization;
15886                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15887                   IsExplicitSpecializationAfterInstantiation =
15888                     ED->getTemplateSpecializationKind() !=
15889                     TSK_ExplicitSpecialization;
15890               }
15891 
15892               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15893               // not keep more that one definition around (merge them). However,
15894               // ensure the decl passes the structural compatibility check in
15895               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15896               NamedDecl *Hidden = nullptr;
15897               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15898                 // There is a definition of this tag, but it is not visible. We
15899                 // explicitly make use of C++'s one definition rule here, and
15900                 // assume that this definition is identical to the hidden one
15901                 // we already have. Make the existing definition visible and
15902                 // use it in place of this one.
15903                 if (!getLangOpts().CPlusPlus) {
15904                   // Postpone making the old definition visible until after we
15905                   // complete parsing the new one and do the structural
15906                   // comparison.
15907                   SkipBody->CheckSameAsPrevious = true;
15908                   SkipBody->New = createTagFromNewDecl();
15909                   SkipBody->Previous = Def;
15910                   return Def;
15911                 } else {
15912                   SkipBody->ShouldSkip = true;
15913                   SkipBody->Previous = Def;
15914                   makeMergedDefinitionVisible(Hidden);
15915                   // Carry on and handle it like a normal definition. We'll
15916                   // skip starting the definitiion later.
15917                 }
15918               } else if (!IsExplicitSpecializationAfterInstantiation) {
15919                 // A redeclaration in function prototype scope in C isn't
15920                 // visible elsewhere, so merely issue a warning.
15921                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15922                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15923                 else
15924                   Diag(NameLoc, diag::err_redefinition) << Name;
15925                 notePreviousDefinition(Def,
15926                                        NameLoc.isValid() ? NameLoc : KWLoc);
15927                 // If this is a redefinition, recover by making this
15928                 // struct be anonymous, which will make any later
15929                 // references get the previous definition.
15930                 Name = nullptr;
15931                 Previous.clear();
15932                 Invalid = true;
15933               }
15934             } else {
15935               // If the type is currently being defined, complain
15936               // about a nested redefinition.
15937               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15938               if (TD->isBeingDefined()) {
15939                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15940                 Diag(PrevTagDecl->getLocation(),
15941                      diag::note_previous_definition);
15942                 Name = nullptr;
15943                 Previous.clear();
15944                 Invalid = true;
15945               }
15946             }
15947 
15948             // Okay, this is definition of a previously declared or referenced
15949             // tag. We're going to create a new Decl for it.
15950           }
15951 
15952           // Okay, we're going to make a redeclaration.  If this is some kind
15953           // of reference, make sure we build the redeclaration in the same DC
15954           // as the original, and ignore the current access specifier.
15955           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15956             SearchDC = PrevTagDecl->getDeclContext();
15957             AS = AS_none;
15958           }
15959         }
15960         // If we get here we have (another) forward declaration or we
15961         // have a definition.  Just create a new decl.
15962 
15963       } else {
15964         // If we get here, this is a definition of a new tag type in a nested
15965         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15966         // new decl/type.  We set PrevDecl to NULL so that the entities
15967         // have distinct types.
15968         Previous.clear();
15969       }
15970       // If we get here, we're going to create a new Decl. If PrevDecl
15971       // is non-NULL, it's a definition of the tag declared by
15972       // PrevDecl. If it's NULL, we have a new definition.
15973 
15974     // Otherwise, PrevDecl is not a tag, but was found with tag
15975     // lookup.  This is only actually possible in C++, where a few
15976     // things like templates still live in the tag namespace.
15977     } else {
15978       // Use a better diagnostic if an elaborated-type-specifier
15979       // found the wrong kind of type on the first
15980       // (non-redeclaration) lookup.
15981       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15982           !Previous.isForRedeclaration()) {
15983         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15984         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15985                                                        << Kind;
15986         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15987         Invalid = true;
15988 
15989       // Otherwise, only diagnose if the declaration is in scope.
15990       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15991                                 SS.isNotEmpty() || isMemberSpecialization)) {
15992         // do nothing
15993 
15994       // Diagnose implicit declarations introduced by elaborated types.
15995       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15996         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15997         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15998         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15999         Invalid = true;
16000 
16001       // Otherwise it's a declaration.  Call out a particularly common
16002       // case here.
16003       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16004         unsigned Kind = 0;
16005         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16006         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16007           << Name << Kind << TND->getUnderlyingType();
16008         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16009         Invalid = true;
16010 
16011       // Otherwise, diagnose.
16012       } else {
16013         // The tag name clashes with something else in the target scope,
16014         // issue an error and recover by making this tag be anonymous.
16015         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16016         notePreviousDefinition(PrevDecl, NameLoc);
16017         Name = nullptr;
16018         Invalid = true;
16019       }
16020 
16021       // The existing declaration isn't relevant to us; we're in a
16022       // new scope, so clear out the previous declaration.
16023       Previous.clear();
16024     }
16025   }
16026 
16027 CreateNewDecl:
16028 
16029   TagDecl *PrevDecl = nullptr;
16030   if (Previous.isSingleResult())
16031     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16032 
16033   // If there is an identifier, use the location of the identifier as the
16034   // location of the decl, otherwise use the location of the struct/union
16035   // keyword.
16036   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16037 
16038   // Otherwise, create a new declaration. If there is a previous
16039   // declaration of the same entity, the two will be linked via
16040   // PrevDecl.
16041   TagDecl *New;
16042 
16043   if (Kind == TTK_Enum) {
16044     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16045     // enum X { A, B, C } D;    D should chain to X.
16046     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16047                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16048                            ScopedEnumUsesClassTag, IsFixed);
16049 
16050     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16051       StdAlignValT = cast<EnumDecl>(New);
16052 
16053     // If this is an undefined enum, warn.
16054     if (TUK != TUK_Definition && !Invalid) {
16055       TagDecl *Def;
16056       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16057         // C++0x: 7.2p2: opaque-enum-declaration.
16058         // Conflicts are diagnosed above. Do nothing.
16059       }
16060       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16061         Diag(Loc, diag::ext_forward_ref_enum_def)
16062           << New;
16063         Diag(Def->getLocation(), diag::note_previous_definition);
16064       } else {
16065         unsigned DiagID = diag::ext_forward_ref_enum;
16066         if (getLangOpts().MSVCCompat)
16067           DiagID = diag::ext_ms_forward_ref_enum;
16068         else if (getLangOpts().CPlusPlus)
16069           DiagID = diag::err_forward_ref_enum;
16070         Diag(Loc, DiagID);
16071       }
16072     }
16073 
16074     if (EnumUnderlying) {
16075       EnumDecl *ED = cast<EnumDecl>(New);
16076       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16077         ED->setIntegerTypeSourceInfo(TI);
16078       else
16079         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16080       ED->setPromotionType(ED->getIntegerType());
16081       assert(ED->isComplete() && "enum with type should be complete");
16082     }
16083   } else {
16084     // struct/union/class
16085 
16086     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16087     // struct X { int A; } D;    D should chain to X.
16088     if (getLangOpts().CPlusPlus) {
16089       // FIXME: Look for a way to use RecordDecl for simple structs.
16090       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16091                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16092 
16093       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16094         StdBadAlloc = cast<CXXRecordDecl>(New);
16095     } else
16096       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16097                                cast_or_null<RecordDecl>(PrevDecl));
16098   }
16099 
16100   // C++11 [dcl.type]p3:
16101   //   A type-specifier-seq shall not define a class or enumeration [...].
16102   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16103       TUK == TUK_Definition) {
16104     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16105       << Context.getTagDeclType(New);
16106     Invalid = true;
16107   }
16108 
16109   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16110       DC->getDeclKind() == Decl::Enum) {
16111     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16112       << Context.getTagDeclType(New);
16113     Invalid = true;
16114   }
16115 
16116   // Maybe add qualifier info.
16117   if (SS.isNotEmpty()) {
16118     if (SS.isSet()) {
16119       // If this is either a declaration or a definition, check the
16120       // nested-name-specifier against the current context.
16121       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16122           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16123                                        isMemberSpecialization))
16124         Invalid = true;
16125 
16126       New->setQualifierInfo(SS.getWithLocInContext(Context));
16127       if (TemplateParameterLists.size() > 0) {
16128         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16129       }
16130     }
16131     else
16132       Invalid = true;
16133   }
16134 
16135   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16136     // Add alignment attributes if necessary; these attributes are checked when
16137     // the ASTContext lays out the structure.
16138     //
16139     // It is important for implementing the correct semantics that this
16140     // happen here (in ActOnTag). The #pragma pack stack is
16141     // maintained as a result of parser callbacks which can occur at
16142     // many points during the parsing of a struct declaration (because
16143     // the #pragma tokens are effectively skipped over during the
16144     // parsing of the struct).
16145     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16146       AddAlignmentAttributesForRecord(RD);
16147       AddMsStructLayoutForRecord(RD);
16148     }
16149   }
16150 
16151   if (ModulePrivateLoc.isValid()) {
16152     if (isMemberSpecialization)
16153       Diag(New->getLocation(), diag::err_module_private_specialization)
16154         << 2
16155         << FixItHint::CreateRemoval(ModulePrivateLoc);
16156     // __module_private__ does not apply to local classes. However, we only
16157     // diagnose this as an error when the declaration specifiers are
16158     // freestanding. Here, we just ignore the __module_private__.
16159     else if (!SearchDC->isFunctionOrMethod())
16160       New->setModulePrivate();
16161   }
16162 
16163   // If this is a specialization of a member class (of a class template),
16164   // check the specialization.
16165   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16166     Invalid = true;
16167 
16168   // If we're declaring or defining a tag in function prototype scope in C,
16169   // note that this type can only be used within the function and add it to
16170   // the list of decls to inject into the function definition scope.
16171   if ((Name || Kind == TTK_Enum) &&
16172       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16173     if (getLangOpts().CPlusPlus) {
16174       // C++ [dcl.fct]p6:
16175       //   Types shall not be defined in return or parameter types.
16176       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16177         Diag(Loc, diag::err_type_defined_in_param_type)
16178             << Name;
16179         Invalid = true;
16180       }
16181     } else if (!PrevDecl) {
16182       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16183     }
16184   }
16185 
16186   if (Invalid)
16187     New->setInvalidDecl();
16188 
16189   // Set the lexical context. If the tag has a C++ scope specifier, the
16190   // lexical context will be different from the semantic context.
16191   New->setLexicalDeclContext(CurContext);
16192 
16193   // Mark this as a friend decl if applicable.
16194   // In Microsoft mode, a friend declaration also acts as a forward
16195   // declaration so we always pass true to setObjectOfFriendDecl to make
16196   // the tag name visible.
16197   if (TUK == TUK_Friend)
16198     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16199 
16200   // Set the access specifier.
16201   if (!Invalid && SearchDC->isRecord())
16202     SetMemberAccessSpecifier(New, PrevDecl, AS);
16203 
16204   if (PrevDecl)
16205     CheckRedeclarationModuleOwnership(New, PrevDecl);
16206 
16207   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16208     New->startDefinition();
16209 
16210   ProcessDeclAttributeList(S, New, Attrs);
16211   AddPragmaAttributes(S, New);
16212 
16213   // If this has an identifier, add it to the scope stack.
16214   if (TUK == TUK_Friend) {
16215     // We might be replacing an existing declaration in the lookup tables;
16216     // if so, borrow its access specifier.
16217     if (PrevDecl)
16218       New->setAccess(PrevDecl->getAccess());
16219 
16220     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16221     DC->makeDeclVisibleInContext(New);
16222     if (Name) // can be null along some error paths
16223       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16224         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16225   } else if (Name) {
16226     S = getNonFieldDeclScope(S);
16227     PushOnScopeChains(New, S, true);
16228   } else {
16229     CurContext->addDecl(New);
16230   }
16231 
16232   // If this is the C FILE type, notify the AST context.
16233   if (IdentifierInfo *II = New->getIdentifier())
16234     if (!New->isInvalidDecl() &&
16235         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16236         II->isStr("FILE"))
16237       Context.setFILEDecl(New);
16238 
16239   if (PrevDecl)
16240     mergeDeclAttributes(New, PrevDecl);
16241 
16242   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16243     inferGslOwnerPointerAttribute(CXXRD);
16244 
16245   // If there's a #pragma GCC visibility in scope, set the visibility of this
16246   // record.
16247   AddPushedVisibilityAttribute(New);
16248 
16249   if (isMemberSpecialization && !New->isInvalidDecl())
16250     CompleteMemberSpecialization(New, Previous);
16251 
16252   OwnedDecl = true;
16253   // In C++, don't return an invalid declaration. We can't recover well from
16254   // the cases where we make the type anonymous.
16255   if (Invalid && getLangOpts().CPlusPlus) {
16256     if (New->isBeingDefined())
16257       if (auto RD = dyn_cast<RecordDecl>(New))
16258         RD->completeDefinition();
16259     return nullptr;
16260   } else if (SkipBody && SkipBody->ShouldSkip) {
16261     return SkipBody->Previous;
16262   } else {
16263     return New;
16264   }
16265 }
16266 
16267 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16268   AdjustDeclIfTemplate(TagD);
16269   TagDecl *Tag = cast<TagDecl>(TagD);
16270 
16271   // Enter the tag context.
16272   PushDeclContext(S, Tag);
16273 
16274   ActOnDocumentableDecl(TagD);
16275 
16276   // If there's a #pragma GCC visibility in scope, set the visibility of this
16277   // record.
16278   AddPushedVisibilityAttribute(Tag);
16279 }
16280 
16281 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16282                                     SkipBodyInfo &SkipBody) {
16283   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16284     return false;
16285 
16286   // Make the previous decl visible.
16287   makeMergedDefinitionVisible(SkipBody.Previous);
16288   return true;
16289 }
16290 
16291 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16292   assert(isa<ObjCContainerDecl>(IDecl) &&
16293          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16294   DeclContext *OCD = cast<DeclContext>(IDecl);
16295   assert(OCD->getLexicalParent() == CurContext &&
16296       "The next DeclContext should be lexically contained in the current one.");
16297   CurContext = OCD;
16298   return IDecl;
16299 }
16300 
16301 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16302                                            SourceLocation FinalLoc,
16303                                            bool IsFinalSpelledSealed,
16304                                            SourceLocation LBraceLoc) {
16305   AdjustDeclIfTemplate(TagD);
16306   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16307 
16308   FieldCollector->StartClass();
16309 
16310   if (!Record->getIdentifier())
16311     return;
16312 
16313   if (FinalLoc.isValid())
16314     Record->addAttr(FinalAttr::Create(
16315         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16316         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16317 
16318   // C++ [class]p2:
16319   //   [...] The class-name is also inserted into the scope of the
16320   //   class itself; this is known as the injected-class-name. For
16321   //   purposes of access checking, the injected-class-name is treated
16322   //   as if it were a public member name.
16323   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16324       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16325       Record->getLocation(), Record->getIdentifier(),
16326       /*PrevDecl=*/nullptr,
16327       /*DelayTypeCreation=*/true);
16328   Context.getTypeDeclType(InjectedClassName, Record);
16329   InjectedClassName->setImplicit();
16330   InjectedClassName->setAccess(AS_public);
16331   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16332       InjectedClassName->setDescribedClassTemplate(Template);
16333   PushOnScopeChains(InjectedClassName, S);
16334   assert(InjectedClassName->isInjectedClassName() &&
16335          "Broken injected-class-name");
16336 }
16337 
16338 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16339                                     SourceRange BraceRange) {
16340   AdjustDeclIfTemplate(TagD);
16341   TagDecl *Tag = cast<TagDecl>(TagD);
16342   Tag->setBraceRange(BraceRange);
16343 
16344   // Make sure we "complete" the definition even it is invalid.
16345   if (Tag->isBeingDefined()) {
16346     assert(Tag->isInvalidDecl() && "We should already have completed it");
16347     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16348       RD->completeDefinition();
16349   }
16350 
16351   if (isa<CXXRecordDecl>(Tag)) {
16352     FieldCollector->FinishClass();
16353   }
16354 
16355   // Exit this scope of this tag's definition.
16356   PopDeclContext();
16357 
16358   if (getCurLexicalContext()->isObjCContainer() &&
16359       Tag->getDeclContext()->isFileContext())
16360     Tag->setTopLevelDeclInObjCContainer();
16361 
16362   // Notify the consumer that we've defined a tag.
16363   if (!Tag->isInvalidDecl())
16364     Consumer.HandleTagDeclDefinition(Tag);
16365 }
16366 
16367 void Sema::ActOnObjCContainerFinishDefinition() {
16368   // Exit this scope of this interface definition.
16369   PopDeclContext();
16370 }
16371 
16372 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16373   assert(DC == CurContext && "Mismatch of container contexts");
16374   OriginalLexicalContext = DC;
16375   ActOnObjCContainerFinishDefinition();
16376 }
16377 
16378 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16379   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16380   OriginalLexicalContext = nullptr;
16381 }
16382 
16383 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16384   AdjustDeclIfTemplate(TagD);
16385   TagDecl *Tag = cast<TagDecl>(TagD);
16386   Tag->setInvalidDecl();
16387 
16388   // Make sure we "complete" the definition even it is invalid.
16389   if (Tag->isBeingDefined()) {
16390     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16391       RD->completeDefinition();
16392   }
16393 
16394   // We're undoing ActOnTagStartDefinition here, not
16395   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16396   // the FieldCollector.
16397 
16398   PopDeclContext();
16399 }
16400 
16401 // Note that FieldName may be null for anonymous bitfields.
16402 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16403                                 IdentifierInfo *FieldName,
16404                                 QualType FieldTy, bool IsMsStruct,
16405                                 Expr *BitWidth, bool *ZeroWidth) {
16406   assert(BitWidth);
16407   if (BitWidth->containsErrors())
16408     return ExprError();
16409 
16410   // Default to true; that shouldn't confuse checks for emptiness
16411   if (ZeroWidth)
16412     *ZeroWidth = true;
16413 
16414   // C99 6.7.2.1p4 - verify the field type.
16415   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16416   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16417     // Handle incomplete and sizeless types with a specific error.
16418     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16419                                  diag::err_field_incomplete_or_sizeless))
16420       return ExprError();
16421     if (FieldName)
16422       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16423         << FieldName << FieldTy << BitWidth->getSourceRange();
16424     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16425       << FieldTy << BitWidth->getSourceRange();
16426   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16427                                              UPPC_BitFieldWidth))
16428     return ExprError();
16429 
16430   // If the bit-width is type- or value-dependent, don't try to check
16431   // it now.
16432   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16433     return BitWidth;
16434 
16435   llvm::APSInt Value;
16436   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16437   if (ICE.isInvalid())
16438     return ICE;
16439   BitWidth = ICE.get();
16440 
16441   if (Value != 0 && ZeroWidth)
16442     *ZeroWidth = false;
16443 
16444   // Zero-width bitfield is ok for anonymous field.
16445   if (Value == 0 && FieldName)
16446     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16447 
16448   if (Value.isSigned() && Value.isNegative()) {
16449     if (FieldName)
16450       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16451                << FieldName << Value.toString(10);
16452     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16453       << Value.toString(10);
16454   }
16455 
16456   if (!FieldTy->isDependentType()) {
16457     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16458     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16459     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16460 
16461     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16462     // ABI.
16463     bool CStdConstraintViolation =
16464         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16465     bool MSBitfieldViolation =
16466         Value.ugt(TypeStorageSize) &&
16467         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16468     if (CStdConstraintViolation || MSBitfieldViolation) {
16469       unsigned DiagWidth =
16470           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16471       if (FieldName)
16472         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16473                << FieldName << (unsigned)Value.getZExtValue()
16474                << !CStdConstraintViolation << DiagWidth;
16475 
16476       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16477              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16478              << DiagWidth;
16479     }
16480 
16481     // Warn on types where the user might conceivably expect to get all
16482     // specified bits as value bits: that's all integral types other than
16483     // 'bool'.
16484     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16485       if (FieldName)
16486         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16487             << FieldName << (unsigned)Value.getZExtValue()
16488             << (unsigned)TypeWidth;
16489       else
16490         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16491             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16492     }
16493   }
16494 
16495   return BitWidth;
16496 }
16497 
16498 /// ActOnField - Each field of a C struct/union is passed into this in order
16499 /// to create a FieldDecl object for it.
16500 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16501                        Declarator &D, Expr *BitfieldWidth) {
16502   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16503                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16504                                /*InitStyle=*/ICIS_NoInit, AS_public);
16505   return Res;
16506 }
16507 
16508 /// HandleField - Analyze a field of a C struct or a C++ data member.
16509 ///
16510 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16511                              SourceLocation DeclStart,
16512                              Declarator &D, Expr *BitWidth,
16513                              InClassInitStyle InitStyle,
16514                              AccessSpecifier AS) {
16515   if (D.isDecompositionDeclarator()) {
16516     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16517     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16518       << Decomp.getSourceRange();
16519     return nullptr;
16520   }
16521 
16522   IdentifierInfo *II = D.getIdentifier();
16523   SourceLocation Loc = DeclStart;
16524   if (II) Loc = D.getIdentifierLoc();
16525 
16526   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16527   QualType T = TInfo->getType();
16528   if (getLangOpts().CPlusPlus) {
16529     CheckExtraCXXDefaultArguments(D);
16530 
16531     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16532                                         UPPC_DataMemberType)) {
16533       D.setInvalidType();
16534       T = Context.IntTy;
16535       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16536     }
16537   }
16538 
16539   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16540 
16541   if (D.getDeclSpec().isInlineSpecified())
16542     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16543         << getLangOpts().CPlusPlus17;
16544   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16545     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16546          diag::err_invalid_thread)
16547       << DeclSpec::getSpecifierName(TSCS);
16548 
16549   // Check to see if this name was declared as a member previously
16550   NamedDecl *PrevDecl = nullptr;
16551   LookupResult Previous(*this, II, Loc, LookupMemberName,
16552                         ForVisibleRedeclaration);
16553   LookupName(Previous, S);
16554   switch (Previous.getResultKind()) {
16555     case LookupResult::Found:
16556     case LookupResult::FoundUnresolvedValue:
16557       PrevDecl = Previous.getAsSingle<NamedDecl>();
16558       break;
16559 
16560     case LookupResult::FoundOverloaded:
16561       PrevDecl = Previous.getRepresentativeDecl();
16562       break;
16563 
16564     case LookupResult::NotFound:
16565     case LookupResult::NotFoundInCurrentInstantiation:
16566     case LookupResult::Ambiguous:
16567       break;
16568   }
16569   Previous.suppressDiagnostics();
16570 
16571   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16572     // Maybe we will complain about the shadowed template parameter.
16573     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16574     // Just pretend that we didn't see the previous declaration.
16575     PrevDecl = nullptr;
16576   }
16577 
16578   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16579     PrevDecl = nullptr;
16580 
16581   bool Mutable
16582     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16583   SourceLocation TSSL = D.getBeginLoc();
16584   FieldDecl *NewFD
16585     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16586                      TSSL, AS, PrevDecl, &D);
16587 
16588   if (NewFD->isInvalidDecl())
16589     Record->setInvalidDecl();
16590 
16591   if (D.getDeclSpec().isModulePrivateSpecified())
16592     NewFD->setModulePrivate();
16593 
16594   if (NewFD->isInvalidDecl() && PrevDecl) {
16595     // Don't introduce NewFD into scope; there's already something
16596     // with the same name in the same scope.
16597   } else if (II) {
16598     PushOnScopeChains(NewFD, S);
16599   } else
16600     Record->addDecl(NewFD);
16601 
16602   return NewFD;
16603 }
16604 
16605 /// Build a new FieldDecl and check its well-formedness.
16606 ///
16607 /// This routine builds a new FieldDecl given the fields name, type,
16608 /// record, etc. \p PrevDecl should refer to any previous declaration
16609 /// with the same name and in the same scope as the field to be
16610 /// created.
16611 ///
16612 /// \returns a new FieldDecl.
16613 ///
16614 /// \todo The Declarator argument is a hack. It will be removed once
16615 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16616                                 TypeSourceInfo *TInfo,
16617                                 RecordDecl *Record, SourceLocation Loc,
16618                                 bool Mutable, Expr *BitWidth,
16619                                 InClassInitStyle InitStyle,
16620                                 SourceLocation TSSL,
16621                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16622                                 Declarator *D) {
16623   IdentifierInfo *II = Name.getAsIdentifierInfo();
16624   bool InvalidDecl = false;
16625   if (D) InvalidDecl = D->isInvalidType();
16626 
16627   // If we receive a broken type, recover by assuming 'int' and
16628   // marking this declaration as invalid.
16629   if (T.isNull() || T->containsErrors()) {
16630     InvalidDecl = true;
16631     T = Context.IntTy;
16632   }
16633 
16634   QualType EltTy = Context.getBaseElementType(T);
16635   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16636     if (RequireCompleteSizedType(Loc, EltTy,
16637                                  diag::err_field_incomplete_or_sizeless)) {
16638       // Fields of incomplete type force their record to be invalid.
16639       Record->setInvalidDecl();
16640       InvalidDecl = true;
16641     } else {
16642       NamedDecl *Def;
16643       EltTy->isIncompleteType(&Def);
16644       if (Def && Def->isInvalidDecl()) {
16645         Record->setInvalidDecl();
16646         InvalidDecl = true;
16647       }
16648     }
16649   }
16650 
16651   // TR 18037 does not allow fields to be declared with address space
16652   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16653       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16654     Diag(Loc, diag::err_field_with_address_space);
16655     Record->setInvalidDecl();
16656     InvalidDecl = true;
16657   }
16658 
16659   if (LangOpts.OpenCL) {
16660     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16661     // used as structure or union field: image, sampler, event or block types.
16662     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16663         T->isBlockPointerType()) {
16664       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16665       Record->setInvalidDecl();
16666       InvalidDecl = true;
16667     }
16668     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16669     if (BitWidth) {
16670       Diag(Loc, diag::err_opencl_bitfields);
16671       InvalidDecl = true;
16672     }
16673   }
16674 
16675   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16676   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16677       T.hasQualifiers()) {
16678     InvalidDecl = true;
16679     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16680   }
16681 
16682   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16683   // than a variably modified type.
16684   if (!InvalidDecl && T->isVariablyModifiedType()) {
16685     bool SizeIsNegative;
16686     llvm::APSInt Oversized;
16687 
16688     TypeSourceInfo *FixedTInfo =
16689       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16690                                                     SizeIsNegative,
16691                                                     Oversized);
16692     if (FixedTInfo) {
16693       Diag(Loc, diag::warn_illegal_constant_array_size);
16694       TInfo = FixedTInfo;
16695       T = FixedTInfo->getType();
16696     } else {
16697       if (SizeIsNegative)
16698         Diag(Loc, diag::err_typecheck_negative_array_size);
16699       else if (Oversized.getBoolValue())
16700         Diag(Loc, diag::err_array_too_large)
16701           << Oversized.toString(10);
16702       else
16703         Diag(Loc, diag::err_typecheck_field_variable_size);
16704       InvalidDecl = true;
16705     }
16706   }
16707 
16708   // Fields can not have abstract class types
16709   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16710                                              diag::err_abstract_type_in_decl,
16711                                              AbstractFieldType))
16712     InvalidDecl = true;
16713 
16714   bool ZeroWidth = false;
16715   if (InvalidDecl)
16716     BitWidth = nullptr;
16717   // If this is declared as a bit-field, check the bit-field.
16718   if (BitWidth) {
16719     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16720                               &ZeroWidth).get();
16721     if (!BitWidth) {
16722       InvalidDecl = true;
16723       BitWidth = nullptr;
16724       ZeroWidth = false;
16725     }
16726 
16727     // Only data members can have in-class initializers.
16728     if (BitWidth && !II && InitStyle) {
16729       Diag(Loc, diag::err_anon_bitfield_init);
16730       InvalidDecl = true;
16731       BitWidth = nullptr;
16732       ZeroWidth = false;
16733     }
16734   }
16735 
16736   // Check that 'mutable' is consistent with the type of the declaration.
16737   if (!InvalidDecl && Mutable) {
16738     unsigned DiagID = 0;
16739     if (T->isReferenceType())
16740       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16741                                         : diag::err_mutable_reference;
16742     else if (T.isConstQualified())
16743       DiagID = diag::err_mutable_const;
16744 
16745     if (DiagID) {
16746       SourceLocation ErrLoc = Loc;
16747       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16748         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16749       Diag(ErrLoc, DiagID);
16750       if (DiagID != diag::ext_mutable_reference) {
16751         Mutable = false;
16752         InvalidDecl = true;
16753       }
16754     }
16755   }
16756 
16757   // C++11 [class.union]p8 (DR1460):
16758   //   At most one variant member of a union may have a
16759   //   brace-or-equal-initializer.
16760   if (InitStyle != ICIS_NoInit)
16761     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16762 
16763   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16764                                        BitWidth, Mutable, InitStyle);
16765   if (InvalidDecl)
16766     NewFD->setInvalidDecl();
16767 
16768   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16769     Diag(Loc, diag::err_duplicate_member) << II;
16770     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16771     NewFD->setInvalidDecl();
16772   }
16773 
16774   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16775     if (Record->isUnion()) {
16776       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16777         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16778         if (RDecl->getDefinition()) {
16779           // C++ [class.union]p1: An object of a class with a non-trivial
16780           // constructor, a non-trivial copy constructor, a non-trivial
16781           // destructor, or a non-trivial copy assignment operator
16782           // cannot be a member of a union, nor can an array of such
16783           // objects.
16784           if (CheckNontrivialField(NewFD))
16785             NewFD->setInvalidDecl();
16786         }
16787       }
16788 
16789       // C++ [class.union]p1: If a union contains a member of reference type,
16790       // the program is ill-formed, except when compiling with MSVC extensions
16791       // enabled.
16792       if (EltTy->isReferenceType()) {
16793         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16794                                     diag::ext_union_member_of_reference_type :
16795                                     diag::err_union_member_of_reference_type)
16796           << NewFD->getDeclName() << EltTy;
16797         if (!getLangOpts().MicrosoftExt)
16798           NewFD->setInvalidDecl();
16799       }
16800     }
16801   }
16802 
16803   // FIXME: We need to pass in the attributes given an AST
16804   // representation, not a parser representation.
16805   if (D) {
16806     // FIXME: The current scope is almost... but not entirely... correct here.
16807     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16808 
16809     if (NewFD->hasAttrs())
16810       CheckAlignasUnderalignment(NewFD);
16811   }
16812 
16813   // In auto-retain/release, infer strong retension for fields of
16814   // retainable type.
16815   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16816     NewFD->setInvalidDecl();
16817 
16818   if (T.isObjCGCWeak())
16819     Diag(Loc, diag::warn_attribute_weak_on_field);
16820 
16821   NewFD->setAccess(AS);
16822   return NewFD;
16823 }
16824 
16825 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16826   assert(FD);
16827   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16828 
16829   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16830     return false;
16831 
16832   QualType EltTy = Context.getBaseElementType(FD->getType());
16833   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16834     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16835     if (RDecl->getDefinition()) {
16836       // We check for copy constructors before constructors
16837       // because otherwise we'll never get complaints about
16838       // copy constructors.
16839 
16840       CXXSpecialMember member = CXXInvalid;
16841       // We're required to check for any non-trivial constructors. Since the
16842       // implicit default constructor is suppressed if there are any
16843       // user-declared constructors, we just need to check that there is a
16844       // trivial default constructor and a trivial copy constructor. (We don't
16845       // worry about move constructors here, since this is a C++98 check.)
16846       if (RDecl->hasNonTrivialCopyConstructor())
16847         member = CXXCopyConstructor;
16848       else if (!RDecl->hasTrivialDefaultConstructor())
16849         member = CXXDefaultConstructor;
16850       else if (RDecl->hasNonTrivialCopyAssignment())
16851         member = CXXCopyAssignment;
16852       else if (RDecl->hasNonTrivialDestructor())
16853         member = CXXDestructor;
16854 
16855       if (member != CXXInvalid) {
16856         if (!getLangOpts().CPlusPlus11 &&
16857             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16858           // Objective-C++ ARC: it is an error to have a non-trivial field of
16859           // a union. However, system headers in Objective-C programs
16860           // occasionally have Objective-C lifetime objects within unions,
16861           // and rather than cause the program to fail, we make those
16862           // members unavailable.
16863           SourceLocation Loc = FD->getLocation();
16864           if (getSourceManager().isInSystemHeader(Loc)) {
16865             if (!FD->hasAttr<UnavailableAttr>())
16866               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16867                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16868             return false;
16869           }
16870         }
16871 
16872         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16873                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16874                diag::err_illegal_union_or_anon_struct_member)
16875           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16876         DiagnoseNontrivial(RDecl, member);
16877         return !getLangOpts().CPlusPlus11;
16878       }
16879     }
16880   }
16881 
16882   return false;
16883 }
16884 
16885 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16886 ///  AST enum value.
16887 static ObjCIvarDecl::AccessControl
16888 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16889   switch (ivarVisibility) {
16890   default: llvm_unreachable("Unknown visitibility kind");
16891   case tok::objc_private: return ObjCIvarDecl::Private;
16892   case tok::objc_public: return ObjCIvarDecl::Public;
16893   case tok::objc_protected: return ObjCIvarDecl::Protected;
16894   case tok::objc_package: return ObjCIvarDecl::Package;
16895   }
16896 }
16897 
16898 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16899 /// in order to create an IvarDecl object for it.
16900 Decl *Sema::ActOnIvar(Scope *S,
16901                                 SourceLocation DeclStart,
16902                                 Declarator &D, Expr *BitfieldWidth,
16903                                 tok::ObjCKeywordKind Visibility) {
16904 
16905   IdentifierInfo *II = D.getIdentifier();
16906   Expr *BitWidth = (Expr*)BitfieldWidth;
16907   SourceLocation Loc = DeclStart;
16908   if (II) Loc = D.getIdentifierLoc();
16909 
16910   // FIXME: Unnamed fields can be handled in various different ways, for
16911   // example, unnamed unions inject all members into the struct namespace!
16912 
16913   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16914   QualType T = TInfo->getType();
16915 
16916   if (BitWidth) {
16917     // 6.7.2.1p3, 6.7.2.1p4
16918     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16919     if (!BitWidth)
16920       D.setInvalidType();
16921   } else {
16922     // Not a bitfield.
16923 
16924     // validate II.
16925 
16926   }
16927   if (T->isReferenceType()) {
16928     Diag(Loc, diag::err_ivar_reference_type);
16929     D.setInvalidType();
16930   }
16931   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16932   // than a variably modified type.
16933   else if (T->isVariablyModifiedType()) {
16934     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16935     D.setInvalidType();
16936   }
16937 
16938   // Get the visibility (access control) for this ivar.
16939   ObjCIvarDecl::AccessControl ac =
16940     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16941                                         : ObjCIvarDecl::None;
16942   // Must set ivar's DeclContext to its enclosing interface.
16943   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16944   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16945     return nullptr;
16946   ObjCContainerDecl *EnclosingContext;
16947   if (ObjCImplementationDecl *IMPDecl =
16948       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16949     if (LangOpts.ObjCRuntime.isFragile()) {
16950     // Case of ivar declared in an implementation. Context is that of its class.
16951       EnclosingContext = IMPDecl->getClassInterface();
16952       assert(EnclosingContext && "Implementation has no class interface!");
16953     }
16954     else
16955       EnclosingContext = EnclosingDecl;
16956   } else {
16957     if (ObjCCategoryDecl *CDecl =
16958         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16959       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16960         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16961         return nullptr;
16962       }
16963     }
16964     EnclosingContext = EnclosingDecl;
16965   }
16966 
16967   // Construct the decl.
16968   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16969                                              DeclStart, Loc, II, T,
16970                                              TInfo, ac, (Expr *)BitfieldWidth);
16971 
16972   if (II) {
16973     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16974                                            ForVisibleRedeclaration);
16975     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16976         && !isa<TagDecl>(PrevDecl)) {
16977       Diag(Loc, diag::err_duplicate_member) << II;
16978       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16979       NewID->setInvalidDecl();
16980     }
16981   }
16982 
16983   // Process attributes attached to the ivar.
16984   ProcessDeclAttributes(S, NewID, D);
16985 
16986   if (D.isInvalidType())
16987     NewID->setInvalidDecl();
16988 
16989   // In ARC, infer 'retaining' for ivars of retainable type.
16990   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16991     NewID->setInvalidDecl();
16992 
16993   if (D.getDeclSpec().isModulePrivateSpecified())
16994     NewID->setModulePrivate();
16995 
16996   if (II) {
16997     // FIXME: When interfaces are DeclContexts, we'll need to add
16998     // these to the interface.
16999     S->AddDecl(NewID);
17000     IdResolver.AddDecl(NewID);
17001   }
17002 
17003   if (LangOpts.ObjCRuntime.isNonFragile() &&
17004       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17005     Diag(Loc, diag::warn_ivars_in_interface);
17006 
17007   return NewID;
17008 }
17009 
17010 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17011 /// class and class extensions. For every class \@interface and class
17012 /// extension \@interface, if the last ivar is a bitfield of any type,
17013 /// then add an implicit `char :0` ivar to the end of that interface.
17014 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17015                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17016   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17017     return;
17018 
17019   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17020   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17021 
17022   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17023     return;
17024   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17025   if (!ID) {
17026     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17027       if (!CD->IsClassExtension())
17028         return;
17029     }
17030     // No need to add this to end of @implementation.
17031     else
17032       return;
17033   }
17034   // All conditions are met. Add a new bitfield to the tail end of ivars.
17035   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17036   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17037 
17038   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17039                               DeclLoc, DeclLoc, nullptr,
17040                               Context.CharTy,
17041                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17042                                                                DeclLoc),
17043                               ObjCIvarDecl::Private, BW,
17044                               true);
17045   AllIvarDecls.push_back(Ivar);
17046 }
17047 
17048 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17049                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17050                        SourceLocation RBrac,
17051                        const ParsedAttributesView &Attrs) {
17052   assert(EnclosingDecl && "missing record or interface decl");
17053 
17054   // If this is an Objective-C @implementation or category and we have
17055   // new fields here we should reset the layout of the interface since
17056   // it will now change.
17057   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17058     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17059     switch (DC->getKind()) {
17060     default: break;
17061     case Decl::ObjCCategory:
17062       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17063       break;
17064     case Decl::ObjCImplementation:
17065       Context.
17066         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17067       break;
17068     }
17069   }
17070 
17071   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17072   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17073 
17074   // Start counting up the number of named members; make sure to include
17075   // members of anonymous structs and unions in the total.
17076   unsigned NumNamedMembers = 0;
17077   if (Record) {
17078     for (const auto *I : Record->decls()) {
17079       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17080         if (IFD->getDeclName())
17081           ++NumNamedMembers;
17082     }
17083   }
17084 
17085   // Verify that all the fields are okay.
17086   SmallVector<FieldDecl*, 32> RecFields;
17087 
17088   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17089        i != end; ++i) {
17090     FieldDecl *FD = cast<FieldDecl>(*i);
17091 
17092     // Get the type for the field.
17093     const Type *FDTy = FD->getType().getTypePtr();
17094 
17095     if (!FD->isAnonymousStructOrUnion()) {
17096       // Remember all fields written by the user.
17097       RecFields.push_back(FD);
17098     }
17099 
17100     // If the field is already invalid for some reason, don't emit more
17101     // diagnostics about it.
17102     if (FD->isInvalidDecl()) {
17103       EnclosingDecl->setInvalidDecl();
17104       continue;
17105     }
17106 
17107     // C99 6.7.2.1p2:
17108     //   A structure or union shall not contain a member with
17109     //   incomplete or function type (hence, a structure shall not
17110     //   contain an instance of itself, but may contain a pointer to
17111     //   an instance of itself), except that the last member of a
17112     //   structure with more than one named member may have incomplete
17113     //   array type; such a structure (and any union containing,
17114     //   possibly recursively, a member that is such a structure)
17115     //   shall not be a member of a structure or an element of an
17116     //   array.
17117     bool IsLastField = (i + 1 == Fields.end());
17118     if (FDTy->isFunctionType()) {
17119       // Field declared as a function.
17120       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17121         << FD->getDeclName();
17122       FD->setInvalidDecl();
17123       EnclosingDecl->setInvalidDecl();
17124       continue;
17125     } else if (FDTy->isIncompleteArrayType() &&
17126                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17127       if (Record) {
17128         // Flexible array member.
17129         // Microsoft and g++ is more permissive regarding flexible array.
17130         // It will accept flexible array in union and also
17131         // as the sole element of a struct/class.
17132         unsigned DiagID = 0;
17133         if (!Record->isUnion() && !IsLastField) {
17134           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17135             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17136           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17137           FD->setInvalidDecl();
17138           EnclosingDecl->setInvalidDecl();
17139           continue;
17140         } else if (Record->isUnion())
17141           DiagID = getLangOpts().MicrosoftExt
17142                        ? diag::ext_flexible_array_union_ms
17143                        : getLangOpts().CPlusPlus
17144                              ? diag::ext_flexible_array_union_gnu
17145                              : diag::err_flexible_array_union;
17146         else if (NumNamedMembers < 1)
17147           DiagID = getLangOpts().MicrosoftExt
17148                        ? diag::ext_flexible_array_empty_aggregate_ms
17149                        : getLangOpts().CPlusPlus
17150                              ? diag::ext_flexible_array_empty_aggregate_gnu
17151                              : diag::err_flexible_array_empty_aggregate;
17152 
17153         if (DiagID)
17154           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17155                                           << Record->getTagKind();
17156         // While the layout of types that contain virtual bases is not specified
17157         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17158         // virtual bases after the derived members.  This would make a flexible
17159         // array member declared at the end of an object not adjacent to the end
17160         // of the type.
17161         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17162           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17163               << FD->getDeclName() << Record->getTagKind();
17164         if (!getLangOpts().C99)
17165           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17166             << FD->getDeclName() << Record->getTagKind();
17167 
17168         // If the element type has a non-trivial destructor, we would not
17169         // implicitly destroy the elements, so disallow it for now.
17170         //
17171         // FIXME: GCC allows this. We should probably either implicitly delete
17172         // the destructor of the containing class, or just allow this.
17173         QualType BaseElem = Context.getBaseElementType(FD->getType());
17174         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17175           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17176             << FD->getDeclName() << FD->getType();
17177           FD->setInvalidDecl();
17178           EnclosingDecl->setInvalidDecl();
17179           continue;
17180         }
17181         // Okay, we have a legal flexible array member at the end of the struct.
17182         Record->setHasFlexibleArrayMember(true);
17183       } else {
17184         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17185         // unless they are followed by another ivar. That check is done
17186         // elsewhere, after synthesized ivars are known.
17187       }
17188     } else if (!FDTy->isDependentType() &&
17189                RequireCompleteSizedType(
17190                    FD->getLocation(), FD->getType(),
17191                    diag::err_field_incomplete_or_sizeless)) {
17192       // Incomplete type
17193       FD->setInvalidDecl();
17194       EnclosingDecl->setInvalidDecl();
17195       continue;
17196     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17197       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17198         // A type which contains a flexible array member is considered to be a
17199         // flexible array member.
17200         Record->setHasFlexibleArrayMember(true);
17201         if (!Record->isUnion()) {
17202           // If this is a struct/class and this is not the last element, reject
17203           // it.  Note that GCC supports variable sized arrays in the middle of
17204           // structures.
17205           if (!IsLastField)
17206             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17207               << FD->getDeclName() << FD->getType();
17208           else {
17209             // We support flexible arrays at the end of structs in
17210             // other structs as an extension.
17211             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17212               << FD->getDeclName();
17213           }
17214         }
17215       }
17216       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17217           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17218                                  diag::err_abstract_type_in_decl,
17219                                  AbstractIvarType)) {
17220         // Ivars can not have abstract class types
17221         FD->setInvalidDecl();
17222       }
17223       if (Record && FDTTy->getDecl()->hasObjectMember())
17224         Record->setHasObjectMember(true);
17225       if (Record && FDTTy->getDecl()->hasVolatileMember())
17226         Record->setHasVolatileMember(true);
17227     } else if (FDTy->isObjCObjectType()) {
17228       /// A field cannot be an Objective-c object
17229       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17230         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17231       QualType T = Context.getObjCObjectPointerType(FD->getType());
17232       FD->setType(T);
17233     } else if (Record && Record->isUnion() &&
17234                FD->getType().hasNonTrivialObjCLifetime() &&
17235                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17236                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17237                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17238                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17239       // For backward compatibility, fields of C unions declared in system
17240       // headers that have non-trivial ObjC ownership qualifications are marked
17241       // as unavailable unless the qualifier is explicit and __strong. This can
17242       // break ABI compatibility between programs compiled with ARC and MRR, but
17243       // is a better option than rejecting programs using those unions under
17244       // ARC.
17245       FD->addAttr(UnavailableAttr::CreateImplicit(
17246           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17247           FD->getLocation()));
17248     } else if (getLangOpts().ObjC &&
17249                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17250                !Record->hasObjectMember()) {
17251       if (FD->getType()->isObjCObjectPointerType() ||
17252           FD->getType().isObjCGCStrong())
17253         Record->setHasObjectMember(true);
17254       else if (Context.getAsArrayType(FD->getType())) {
17255         QualType BaseType = Context.getBaseElementType(FD->getType());
17256         if (BaseType->isRecordType() &&
17257             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17258           Record->setHasObjectMember(true);
17259         else if (BaseType->isObjCObjectPointerType() ||
17260                  BaseType.isObjCGCStrong())
17261                Record->setHasObjectMember(true);
17262       }
17263     }
17264 
17265     if (Record && !getLangOpts().CPlusPlus &&
17266         !shouldIgnoreForRecordTriviality(FD)) {
17267       QualType FT = FD->getType();
17268       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17269         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17270         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17271             Record->isUnion())
17272           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17273       }
17274       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17275       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17276         Record->setNonTrivialToPrimitiveCopy(true);
17277         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17278           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17279       }
17280       if (FT.isDestructedType()) {
17281         Record->setNonTrivialToPrimitiveDestroy(true);
17282         Record->setParamDestroyedInCallee(true);
17283         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17284           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17285       }
17286 
17287       if (const auto *RT = FT->getAs<RecordType>()) {
17288         if (RT->getDecl()->getArgPassingRestrictions() ==
17289             RecordDecl::APK_CanNeverPassInRegs)
17290           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17291       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17292         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17293     }
17294 
17295     if (Record && FD->getType().isVolatileQualified())
17296       Record->setHasVolatileMember(true);
17297     // Keep track of the number of named members.
17298     if (FD->getIdentifier())
17299       ++NumNamedMembers;
17300   }
17301 
17302   // Okay, we successfully defined 'Record'.
17303   if (Record) {
17304     bool Completed = false;
17305     if (CXXRecord) {
17306       if (!CXXRecord->isInvalidDecl()) {
17307         // Set access bits correctly on the directly-declared conversions.
17308         for (CXXRecordDecl::conversion_iterator
17309                I = CXXRecord->conversion_begin(),
17310                E = CXXRecord->conversion_end(); I != E; ++I)
17311           I.setAccess((*I)->getAccess());
17312       }
17313 
17314       // Add any implicitly-declared members to this class.
17315       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17316 
17317       if (!CXXRecord->isDependentType()) {
17318         if (!CXXRecord->isInvalidDecl()) {
17319           // If we have virtual base classes, we may end up finding multiple
17320           // final overriders for a given virtual function. Check for this
17321           // problem now.
17322           if (CXXRecord->getNumVBases()) {
17323             CXXFinalOverriderMap FinalOverriders;
17324             CXXRecord->getFinalOverriders(FinalOverriders);
17325 
17326             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17327                                              MEnd = FinalOverriders.end();
17328                  M != MEnd; ++M) {
17329               for (OverridingMethods::iterator SO = M->second.begin(),
17330                                             SOEnd = M->second.end();
17331                    SO != SOEnd; ++SO) {
17332                 assert(SO->second.size() > 0 &&
17333                        "Virtual function without overriding functions?");
17334                 if (SO->second.size() == 1)
17335                   continue;
17336 
17337                 // C++ [class.virtual]p2:
17338                 //   In a derived class, if a virtual member function of a base
17339                 //   class subobject has more than one final overrider the
17340                 //   program is ill-formed.
17341                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17342                   << (const NamedDecl *)M->first << Record;
17343                 Diag(M->first->getLocation(),
17344                      diag::note_overridden_virtual_function);
17345                 for (OverridingMethods::overriding_iterator
17346                           OM = SO->second.begin(),
17347                        OMEnd = SO->second.end();
17348                      OM != OMEnd; ++OM)
17349                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17350                     << (const NamedDecl *)M->first << OM->Method->getParent();
17351 
17352                 Record->setInvalidDecl();
17353               }
17354             }
17355             CXXRecord->completeDefinition(&FinalOverriders);
17356             Completed = true;
17357           }
17358         }
17359       }
17360     }
17361 
17362     if (!Completed)
17363       Record->completeDefinition();
17364 
17365     // Handle attributes before checking the layout.
17366     ProcessDeclAttributeList(S, Record, Attrs);
17367 
17368     // We may have deferred checking for a deleted destructor. Check now.
17369     if (CXXRecord) {
17370       auto *Dtor = CXXRecord->getDestructor();
17371       if (Dtor && Dtor->isImplicit() &&
17372           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17373         CXXRecord->setImplicitDestructorIsDeleted();
17374         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17375       }
17376     }
17377 
17378     if (Record->hasAttrs()) {
17379       CheckAlignasUnderalignment(Record);
17380 
17381       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17382         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17383                                            IA->getRange(), IA->getBestCase(),
17384                                            IA->getInheritanceModel());
17385     }
17386 
17387     // Check if the structure/union declaration is a type that can have zero
17388     // size in C. For C this is a language extension, for C++ it may cause
17389     // compatibility problems.
17390     bool CheckForZeroSize;
17391     if (!getLangOpts().CPlusPlus) {
17392       CheckForZeroSize = true;
17393     } else {
17394       // For C++ filter out types that cannot be referenced in C code.
17395       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17396       CheckForZeroSize =
17397           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17398           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17399           CXXRecord->isCLike();
17400     }
17401     if (CheckForZeroSize) {
17402       bool ZeroSize = true;
17403       bool IsEmpty = true;
17404       unsigned NonBitFields = 0;
17405       for (RecordDecl::field_iterator I = Record->field_begin(),
17406                                       E = Record->field_end();
17407            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17408         IsEmpty = false;
17409         if (I->isUnnamedBitfield()) {
17410           if (!I->isZeroLengthBitField(Context))
17411             ZeroSize = false;
17412         } else {
17413           ++NonBitFields;
17414           QualType FieldType = I->getType();
17415           if (FieldType->isIncompleteType() ||
17416               !Context.getTypeSizeInChars(FieldType).isZero())
17417             ZeroSize = false;
17418         }
17419       }
17420 
17421       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17422       // allowed in C++, but warn if its declaration is inside
17423       // extern "C" block.
17424       if (ZeroSize) {
17425         Diag(RecLoc, getLangOpts().CPlusPlus ?
17426                          diag::warn_zero_size_struct_union_in_extern_c :
17427                          diag::warn_zero_size_struct_union_compat)
17428           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17429       }
17430 
17431       // Structs without named members are extension in C (C99 6.7.2.1p7),
17432       // but are accepted by GCC.
17433       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17434         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17435                                diag::ext_no_named_members_in_struct_union)
17436           << Record->isUnion();
17437       }
17438     }
17439   } else {
17440     ObjCIvarDecl **ClsFields =
17441       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17442     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17443       ID->setEndOfDefinitionLoc(RBrac);
17444       // Add ivar's to class's DeclContext.
17445       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17446         ClsFields[i]->setLexicalDeclContext(ID);
17447         ID->addDecl(ClsFields[i]);
17448       }
17449       // Must enforce the rule that ivars in the base classes may not be
17450       // duplicates.
17451       if (ID->getSuperClass())
17452         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17453     } else if (ObjCImplementationDecl *IMPDecl =
17454                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17455       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17456       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17457         // Ivar declared in @implementation never belongs to the implementation.
17458         // Only it is in implementation's lexical context.
17459         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17460       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17461       IMPDecl->setIvarLBraceLoc(LBrac);
17462       IMPDecl->setIvarRBraceLoc(RBrac);
17463     } else if (ObjCCategoryDecl *CDecl =
17464                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17465       // case of ivars in class extension; all other cases have been
17466       // reported as errors elsewhere.
17467       // FIXME. Class extension does not have a LocEnd field.
17468       // CDecl->setLocEnd(RBrac);
17469       // Add ivar's to class extension's DeclContext.
17470       // Diagnose redeclaration of private ivars.
17471       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17472       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17473         if (IDecl) {
17474           if (const ObjCIvarDecl *ClsIvar =
17475               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17476             Diag(ClsFields[i]->getLocation(),
17477                  diag::err_duplicate_ivar_declaration);
17478             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17479             continue;
17480           }
17481           for (const auto *Ext : IDecl->known_extensions()) {
17482             if (const ObjCIvarDecl *ClsExtIvar
17483                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17484               Diag(ClsFields[i]->getLocation(),
17485                    diag::err_duplicate_ivar_declaration);
17486               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17487               continue;
17488             }
17489           }
17490         }
17491         ClsFields[i]->setLexicalDeclContext(CDecl);
17492         CDecl->addDecl(ClsFields[i]);
17493       }
17494       CDecl->setIvarLBraceLoc(LBrac);
17495       CDecl->setIvarRBraceLoc(RBrac);
17496     }
17497   }
17498 }
17499 
17500 /// Determine whether the given integral value is representable within
17501 /// the given type T.
17502 static bool isRepresentableIntegerValue(ASTContext &Context,
17503                                         llvm::APSInt &Value,
17504                                         QualType T) {
17505   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17506          "Integral type required!");
17507   unsigned BitWidth = Context.getIntWidth(T);
17508 
17509   if (Value.isUnsigned() || Value.isNonNegative()) {
17510     if (T->isSignedIntegerOrEnumerationType())
17511       --BitWidth;
17512     return Value.getActiveBits() <= BitWidth;
17513   }
17514   return Value.getMinSignedBits() <= BitWidth;
17515 }
17516 
17517 // Given an integral type, return the next larger integral type
17518 // (or a NULL type of no such type exists).
17519 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17520   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17521   // enum checking below.
17522   assert((T->isIntegralType(Context) ||
17523          T->isEnumeralType()) && "Integral type required!");
17524   const unsigned NumTypes = 4;
17525   QualType SignedIntegralTypes[NumTypes] = {
17526     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17527   };
17528   QualType UnsignedIntegralTypes[NumTypes] = {
17529     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17530     Context.UnsignedLongLongTy
17531   };
17532 
17533   unsigned BitWidth = Context.getTypeSize(T);
17534   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17535                                                         : UnsignedIntegralTypes;
17536   for (unsigned I = 0; I != NumTypes; ++I)
17537     if (Context.getTypeSize(Types[I]) > BitWidth)
17538       return Types[I];
17539 
17540   return QualType();
17541 }
17542 
17543 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17544                                           EnumConstantDecl *LastEnumConst,
17545                                           SourceLocation IdLoc,
17546                                           IdentifierInfo *Id,
17547                                           Expr *Val) {
17548   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17549   llvm::APSInt EnumVal(IntWidth);
17550   QualType EltTy;
17551 
17552   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17553     Val = nullptr;
17554 
17555   if (Val)
17556     Val = DefaultLvalueConversion(Val).get();
17557 
17558   if (Val) {
17559     if (Enum->isDependentType() || Val->isTypeDependent())
17560       EltTy = Context.DependentTy;
17561     else {
17562       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17563         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17564         // constant-expression in the enumerator-definition shall be a converted
17565         // constant expression of the underlying type.
17566         EltTy = Enum->getIntegerType();
17567         ExprResult Converted =
17568           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17569                                            CCEK_Enumerator);
17570         if (Converted.isInvalid())
17571           Val = nullptr;
17572         else
17573           Val = Converted.get();
17574       } else if (!Val->isValueDependent() &&
17575                  !(Val = VerifyIntegerConstantExpression(Val,
17576                                                          &EnumVal).get())) {
17577         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17578       } else {
17579         if (Enum->isComplete()) {
17580           EltTy = Enum->getIntegerType();
17581 
17582           // In Obj-C and Microsoft mode, require the enumeration value to be
17583           // representable in the underlying type of the enumeration. In C++11,
17584           // we perform a non-narrowing conversion as part of converted constant
17585           // expression checking.
17586           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17587             if (Context.getTargetInfo()
17588                     .getTriple()
17589                     .isWindowsMSVCEnvironment()) {
17590               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17591             } else {
17592               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17593             }
17594           }
17595 
17596           // Cast to the underlying type.
17597           Val = ImpCastExprToType(Val, EltTy,
17598                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17599                                                          : CK_IntegralCast)
17600                     .get();
17601         } else if (getLangOpts().CPlusPlus) {
17602           // C++11 [dcl.enum]p5:
17603           //   If the underlying type is not fixed, the type of each enumerator
17604           //   is the type of its initializing value:
17605           //     - If an initializer is specified for an enumerator, the
17606           //       initializing value has the same type as the expression.
17607           EltTy = Val->getType();
17608         } else {
17609           // C99 6.7.2.2p2:
17610           //   The expression that defines the value of an enumeration constant
17611           //   shall be an integer constant expression that has a value
17612           //   representable as an int.
17613 
17614           // Complain if the value is not representable in an int.
17615           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17616             Diag(IdLoc, diag::ext_enum_value_not_int)
17617               << EnumVal.toString(10) << Val->getSourceRange()
17618               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17619           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17620             // Force the type of the expression to 'int'.
17621             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17622           }
17623           EltTy = Val->getType();
17624         }
17625       }
17626     }
17627   }
17628 
17629   if (!Val) {
17630     if (Enum->isDependentType())
17631       EltTy = Context.DependentTy;
17632     else if (!LastEnumConst) {
17633       // C++0x [dcl.enum]p5:
17634       //   If the underlying type is not fixed, the type of each enumerator
17635       //   is the type of its initializing value:
17636       //     - If no initializer is specified for the first enumerator, the
17637       //       initializing value has an unspecified integral type.
17638       //
17639       // GCC uses 'int' for its unspecified integral type, as does
17640       // C99 6.7.2.2p3.
17641       if (Enum->isFixed()) {
17642         EltTy = Enum->getIntegerType();
17643       }
17644       else {
17645         EltTy = Context.IntTy;
17646       }
17647     } else {
17648       // Assign the last value + 1.
17649       EnumVal = LastEnumConst->getInitVal();
17650       ++EnumVal;
17651       EltTy = LastEnumConst->getType();
17652 
17653       // Check for overflow on increment.
17654       if (EnumVal < LastEnumConst->getInitVal()) {
17655         // C++0x [dcl.enum]p5:
17656         //   If the underlying type is not fixed, the type of each enumerator
17657         //   is the type of its initializing value:
17658         //
17659         //     - Otherwise the type of the initializing value is the same as
17660         //       the type of the initializing value of the preceding enumerator
17661         //       unless the incremented value is not representable in that type,
17662         //       in which case the type is an unspecified integral type
17663         //       sufficient to contain the incremented value. If no such type
17664         //       exists, the program is ill-formed.
17665         QualType T = getNextLargerIntegralType(Context, EltTy);
17666         if (T.isNull() || Enum->isFixed()) {
17667           // There is no integral type larger enough to represent this
17668           // value. Complain, then allow the value to wrap around.
17669           EnumVal = LastEnumConst->getInitVal();
17670           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17671           ++EnumVal;
17672           if (Enum->isFixed())
17673             // When the underlying type is fixed, this is ill-formed.
17674             Diag(IdLoc, diag::err_enumerator_wrapped)
17675               << EnumVal.toString(10)
17676               << EltTy;
17677           else
17678             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17679               << EnumVal.toString(10);
17680         } else {
17681           EltTy = T;
17682         }
17683 
17684         // Retrieve the last enumerator's value, extent that type to the
17685         // type that is supposed to be large enough to represent the incremented
17686         // value, then increment.
17687         EnumVal = LastEnumConst->getInitVal();
17688         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17689         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17690         ++EnumVal;
17691 
17692         // If we're not in C++, diagnose the overflow of enumerator values,
17693         // which in C99 means that the enumerator value is not representable in
17694         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17695         // permits enumerator values that are representable in some larger
17696         // integral type.
17697         if (!getLangOpts().CPlusPlus && !T.isNull())
17698           Diag(IdLoc, diag::warn_enum_value_overflow);
17699       } else if (!getLangOpts().CPlusPlus &&
17700                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17701         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17702         Diag(IdLoc, diag::ext_enum_value_not_int)
17703           << EnumVal.toString(10) << 1;
17704       }
17705     }
17706   }
17707 
17708   if (!EltTy->isDependentType()) {
17709     // Make the enumerator value match the signedness and size of the
17710     // enumerator's type.
17711     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17712     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17713   }
17714 
17715   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17716                                   Val, EnumVal);
17717 }
17718 
17719 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17720                                                 SourceLocation IILoc) {
17721   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17722       !getLangOpts().CPlusPlus)
17723     return SkipBodyInfo();
17724 
17725   // We have an anonymous enum definition. Look up the first enumerator to
17726   // determine if we should merge the definition with an existing one and
17727   // skip the body.
17728   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17729                                          forRedeclarationInCurContext());
17730   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17731   if (!PrevECD)
17732     return SkipBodyInfo();
17733 
17734   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17735   NamedDecl *Hidden;
17736   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17737     SkipBodyInfo Skip;
17738     Skip.Previous = Hidden;
17739     return Skip;
17740   }
17741 
17742   return SkipBodyInfo();
17743 }
17744 
17745 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17746                               SourceLocation IdLoc, IdentifierInfo *Id,
17747                               const ParsedAttributesView &Attrs,
17748                               SourceLocation EqualLoc, Expr *Val) {
17749   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17750   EnumConstantDecl *LastEnumConst =
17751     cast_or_null<EnumConstantDecl>(lastEnumConst);
17752 
17753   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17754   // we find one that is.
17755   S = getNonFieldDeclScope(S);
17756 
17757   // Verify that there isn't already something declared with this name in this
17758   // scope.
17759   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17760   LookupName(R, S);
17761   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17762 
17763   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17764     // Maybe we will complain about the shadowed template parameter.
17765     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17766     // Just pretend that we didn't see the previous declaration.
17767     PrevDecl = nullptr;
17768   }
17769 
17770   // C++ [class.mem]p15:
17771   // If T is the name of a class, then each of the following shall have a name
17772   // different from T:
17773   // - every enumerator of every member of class T that is an unscoped
17774   // enumerated type
17775   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17776     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17777                             DeclarationNameInfo(Id, IdLoc));
17778 
17779   EnumConstantDecl *New =
17780     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17781   if (!New)
17782     return nullptr;
17783 
17784   if (PrevDecl) {
17785     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17786       // Check for other kinds of shadowing not already handled.
17787       CheckShadow(New, PrevDecl, R);
17788     }
17789 
17790     // When in C++, we may get a TagDecl with the same name; in this case the
17791     // enum constant will 'hide' the tag.
17792     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17793            "Received TagDecl when not in C++!");
17794     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17795       if (isa<EnumConstantDecl>(PrevDecl))
17796         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17797       else
17798         Diag(IdLoc, diag::err_redefinition) << Id;
17799       notePreviousDefinition(PrevDecl, IdLoc);
17800       return nullptr;
17801     }
17802   }
17803 
17804   // Process attributes.
17805   ProcessDeclAttributeList(S, New, Attrs);
17806   AddPragmaAttributes(S, New);
17807 
17808   // Register this decl in the current scope stack.
17809   New->setAccess(TheEnumDecl->getAccess());
17810   PushOnScopeChains(New, S);
17811 
17812   ActOnDocumentableDecl(New);
17813 
17814   return New;
17815 }
17816 
17817 // Returns true when the enum initial expression does not trigger the
17818 // duplicate enum warning.  A few common cases are exempted as follows:
17819 // Element2 = Element1
17820 // Element2 = Element1 + 1
17821 // Element2 = Element1 - 1
17822 // Where Element2 and Element1 are from the same enum.
17823 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17824   Expr *InitExpr = ECD->getInitExpr();
17825   if (!InitExpr)
17826     return true;
17827   InitExpr = InitExpr->IgnoreImpCasts();
17828 
17829   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17830     if (!BO->isAdditiveOp())
17831       return true;
17832     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17833     if (!IL)
17834       return true;
17835     if (IL->getValue() != 1)
17836       return true;
17837 
17838     InitExpr = BO->getLHS();
17839   }
17840 
17841   // This checks if the elements are from the same enum.
17842   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17843   if (!DRE)
17844     return true;
17845 
17846   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17847   if (!EnumConstant)
17848     return true;
17849 
17850   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17851       Enum)
17852     return true;
17853 
17854   return false;
17855 }
17856 
17857 // Emits a warning when an element is implicitly set a value that
17858 // a previous element has already been set to.
17859 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17860                                         EnumDecl *Enum, QualType EnumType) {
17861   // Avoid anonymous enums
17862   if (!Enum->getIdentifier())
17863     return;
17864 
17865   // Only check for small enums.
17866   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17867     return;
17868 
17869   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17870     return;
17871 
17872   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17873   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17874 
17875   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17876 
17877   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17878   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17879 
17880   // Use int64_t as a key to avoid needing special handling for map keys.
17881   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17882     llvm::APSInt Val = D->getInitVal();
17883     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17884   };
17885 
17886   DuplicatesVector DupVector;
17887   ValueToVectorMap EnumMap;
17888 
17889   // Populate the EnumMap with all values represented by enum constants without
17890   // an initializer.
17891   for (auto *Element : Elements) {
17892     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17893 
17894     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17895     // this constant.  Skip this enum since it may be ill-formed.
17896     if (!ECD) {
17897       return;
17898     }
17899 
17900     // Constants with initalizers are handled in the next loop.
17901     if (ECD->getInitExpr())
17902       continue;
17903 
17904     // Duplicate values are handled in the next loop.
17905     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17906   }
17907 
17908   if (EnumMap.size() == 0)
17909     return;
17910 
17911   // Create vectors for any values that has duplicates.
17912   for (auto *Element : Elements) {
17913     // The last loop returned if any constant was null.
17914     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17915     if (!ValidDuplicateEnum(ECD, Enum))
17916       continue;
17917 
17918     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17919     if (Iter == EnumMap.end())
17920       continue;
17921 
17922     DeclOrVector& Entry = Iter->second;
17923     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17924       // Ensure constants are different.
17925       if (D == ECD)
17926         continue;
17927 
17928       // Create new vector and push values onto it.
17929       auto Vec = std::make_unique<ECDVector>();
17930       Vec->push_back(D);
17931       Vec->push_back(ECD);
17932 
17933       // Update entry to point to the duplicates vector.
17934       Entry = Vec.get();
17935 
17936       // Store the vector somewhere we can consult later for quick emission of
17937       // diagnostics.
17938       DupVector.emplace_back(std::move(Vec));
17939       continue;
17940     }
17941 
17942     ECDVector *Vec = Entry.get<ECDVector*>();
17943     // Make sure constants are not added more than once.
17944     if (*Vec->begin() == ECD)
17945       continue;
17946 
17947     Vec->push_back(ECD);
17948   }
17949 
17950   // Emit diagnostics.
17951   for (const auto &Vec : DupVector) {
17952     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17953 
17954     // Emit warning for one enum constant.
17955     auto *FirstECD = Vec->front();
17956     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17957       << FirstECD << FirstECD->getInitVal().toString(10)
17958       << FirstECD->getSourceRange();
17959 
17960     // Emit one note for each of the remaining enum constants with
17961     // the same value.
17962     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17963       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17964         << ECD << ECD->getInitVal().toString(10)
17965         << ECD->getSourceRange();
17966   }
17967 }
17968 
17969 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17970                              bool AllowMask) const {
17971   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17972   assert(ED->isCompleteDefinition() && "expected enum definition");
17973 
17974   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17975   llvm::APInt &FlagBits = R.first->second;
17976 
17977   if (R.second) {
17978     for (auto *E : ED->enumerators()) {
17979       const auto &EVal = E->getInitVal();
17980       // Only single-bit enumerators introduce new flag values.
17981       if (EVal.isPowerOf2())
17982         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17983     }
17984   }
17985 
17986   // A value is in a flag enum if either its bits are a subset of the enum's
17987   // flag bits (the first condition) or we are allowing masks and the same is
17988   // true of its complement (the second condition). When masks are allowed, we
17989   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17990   //
17991   // While it's true that any value could be used as a mask, the assumption is
17992   // that a mask will have all of the insignificant bits set. Anything else is
17993   // likely a logic error.
17994   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17995   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17996 }
17997 
17998 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17999                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18000                          const ParsedAttributesView &Attrs) {
18001   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18002   QualType EnumType = Context.getTypeDeclType(Enum);
18003 
18004   ProcessDeclAttributeList(S, Enum, Attrs);
18005 
18006   if (Enum->isDependentType()) {
18007     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18008       EnumConstantDecl *ECD =
18009         cast_or_null<EnumConstantDecl>(Elements[i]);
18010       if (!ECD) continue;
18011 
18012       ECD->setType(EnumType);
18013     }
18014 
18015     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18016     return;
18017   }
18018 
18019   // TODO: If the result value doesn't fit in an int, it must be a long or long
18020   // long value.  ISO C does not support this, but GCC does as an extension,
18021   // emit a warning.
18022   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18023   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18024   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18025 
18026   // Verify that all the values are okay, compute the size of the values, and
18027   // reverse the list.
18028   unsigned NumNegativeBits = 0;
18029   unsigned NumPositiveBits = 0;
18030 
18031   // Keep track of whether all elements have type int.
18032   bool AllElementsInt = true;
18033 
18034   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18035     EnumConstantDecl *ECD =
18036       cast_or_null<EnumConstantDecl>(Elements[i]);
18037     if (!ECD) continue;  // Already issued a diagnostic.
18038 
18039     const llvm::APSInt &InitVal = ECD->getInitVal();
18040 
18041     // Keep track of the size of positive and negative values.
18042     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18043       NumPositiveBits = std::max(NumPositiveBits,
18044                                  (unsigned)InitVal.getActiveBits());
18045     else
18046       NumNegativeBits = std::max(NumNegativeBits,
18047                                  (unsigned)InitVal.getMinSignedBits());
18048 
18049     // Keep track of whether every enum element has type int (very common).
18050     if (AllElementsInt)
18051       AllElementsInt = ECD->getType() == Context.IntTy;
18052   }
18053 
18054   // Figure out the type that should be used for this enum.
18055   QualType BestType;
18056   unsigned BestWidth;
18057 
18058   // C++0x N3000 [conv.prom]p3:
18059   //   An rvalue of an unscoped enumeration type whose underlying
18060   //   type is not fixed can be converted to an rvalue of the first
18061   //   of the following types that can represent all the values of
18062   //   the enumeration: int, unsigned int, long int, unsigned long
18063   //   int, long long int, or unsigned long long int.
18064   // C99 6.4.4.3p2:
18065   //   An identifier declared as an enumeration constant has type int.
18066   // The C99 rule is modified by a gcc extension
18067   QualType BestPromotionType;
18068 
18069   bool Packed = Enum->hasAttr<PackedAttr>();
18070   // -fshort-enums is the equivalent to specifying the packed attribute on all
18071   // enum definitions.
18072   if (LangOpts.ShortEnums)
18073     Packed = true;
18074 
18075   // If the enum already has a type because it is fixed or dictated by the
18076   // target, promote that type instead of analyzing the enumerators.
18077   if (Enum->isComplete()) {
18078     BestType = Enum->getIntegerType();
18079     if (BestType->isPromotableIntegerType())
18080       BestPromotionType = Context.getPromotedIntegerType(BestType);
18081     else
18082       BestPromotionType = BestType;
18083 
18084     BestWidth = Context.getIntWidth(BestType);
18085   }
18086   else if (NumNegativeBits) {
18087     // If there is a negative value, figure out the smallest integer type (of
18088     // int/long/longlong) that fits.
18089     // If it's packed, check also if it fits a char or a short.
18090     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18091       BestType = Context.SignedCharTy;
18092       BestWidth = CharWidth;
18093     } else if (Packed && NumNegativeBits <= ShortWidth &&
18094                NumPositiveBits < ShortWidth) {
18095       BestType = Context.ShortTy;
18096       BestWidth = ShortWidth;
18097     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18098       BestType = Context.IntTy;
18099       BestWidth = IntWidth;
18100     } else {
18101       BestWidth = Context.getTargetInfo().getLongWidth();
18102 
18103       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18104         BestType = Context.LongTy;
18105       } else {
18106         BestWidth = Context.getTargetInfo().getLongLongWidth();
18107 
18108         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18109           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18110         BestType = Context.LongLongTy;
18111       }
18112     }
18113     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18114   } else {
18115     // If there is no negative value, figure out the smallest type that fits
18116     // all of the enumerator values.
18117     // If it's packed, check also if it fits a char or a short.
18118     if (Packed && NumPositiveBits <= CharWidth) {
18119       BestType = Context.UnsignedCharTy;
18120       BestPromotionType = Context.IntTy;
18121       BestWidth = CharWidth;
18122     } else if (Packed && NumPositiveBits <= ShortWidth) {
18123       BestType = Context.UnsignedShortTy;
18124       BestPromotionType = Context.IntTy;
18125       BestWidth = ShortWidth;
18126     } else if (NumPositiveBits <= IntWidth) {
18127       BestType = Context.UnsignedIntTy;
18128       BestWidth = IntWidth;
18129       BestPromotionType
18130         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18131                            ? Context.UnsignedIntTy : Context.IntTy;
18132     } else if (NumPositiveBits <=
18133                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18134       BestType = Context.UnsignedLongTy;
18135       BestPromotionType
18136         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18137                            ? Context.UnsignedLongTy : Context.LongTy;
18138     } else {
18139       BestWidth = Context.getTargetInfo().getLongLongWidth();
18140       assert(NumPositiveBits <= BestWidth &&
18141              "How could an initializer get larger than ULL?");
18142       BestType = Context.UnsignedLongLongTy;
18143       BestPromotionType
18144         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18145                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18146     }
18147   }
18148 
18149   // Loop over all of the enumerator constants, changing their types to match
18150   // the type of the enum if needed.
18151   for (auto *D : Elements) {
18152     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18153     if (!ECD) continue;  // Already issued a diagnostic.
18154 
18155     // Standard C says the enumerators have int type, but we allow, as an
18156     // extension, the enumerators to be larger than int size.  If each
18157     // enumerator value fits in an int, type it as an int, otherwise type it the
18158     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18159     // that X has type 'int', not 'unsigned'.
18160 
18161     // Determine whether the value fits into an int.
18162     llvm::APSInt InitVal = ECD->getInitVal();
18163 
18164     // If it fits into an integer type, force it.  Otherwise force it to match
18165     // the enum decl type.
18166     QualType NewTy;
18167     unsigned NewWidth;
18168     bool NewSign;
18169     if (!getLangOpts().CPlusPlus &&
18170         !Enum->isFixed() &&
18171         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18172       NewTy = Context.IntTy;
18173       NewWidth = IntWidth;
18174       NewSign = true;
18175     } else if (ECD->getType() == BestType) {
18176       // Already the right type!
18177       if (getLangOpts().CPlusPlus)
18178         // C++ [dcl.enum]p4: Following the closing brace of an
18179         // enum-specifier, each enumerator has the type of its
18180         // enumeration.
18181         ECD->setType(EnumType);
18182       continue;
18183     } else {
18184       NewTy = BestType;
18185       NewWidth = BestWidth;
18186       NewSign = BestType->isSignedIntegerOrEnumerationType();
18187     }
18188 
18189     // Adjust the APSInt value.
18190     InitVal = InitVal.extOrTrunc(NewWidth);
18191     InitVal.setIsSigned(NewSign);
18192     ECD->setInitVal(InitVal);
18193 
18194     // Adjust the Expr initializer and type.
18195     if (ECD->getInitExpr() &&
18196         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18197       ECD->setInitExpr(ImplicitCastExpr::Create(
18198           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18199           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18200     if (getLangOpts().CPlusPlus)
18201       // C++ [dcl.enum]p4: Following the closing brace of an
18202       // enum-specifier, each enumerator has the type of its
18203       // enumeration.
18204       ECD->setType(EnumType);
18205     else
18206       ECD->setType(NewTy);
18207   }
18208 
18209   Enum->completeDefinition(BestType, BestPromotionType,
18210                            NumPositiveBits, NumNegativeBits);
18211 
18212   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18213 
18214   if (Enum->isClosedFlag()) {
18215     for (Decl *D : Elements) {
18216       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18217       if (!ECD) continue;  // Already issued a diagnostic.
18218 
18219       llvm::APSInt InitVal = ECD->getInitVal();
18220       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18221           !IsValueInFlagEnum(Enum, InitVal, true))
18222         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18223           << ECD << Enum;
18224     }
18225   }
18226 
18227   // Now that the enum type is defined, ensure it's not been underaligned.
18228   if (Enum->hasAttrs())
18229     CheckAlignasUnderalignment(Enum);
18230 }
18231 
18232 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18233                                   SourceLocation StartLoc,
18234                                   SourceLocation EndLoc) {
18235   StringLiteral *AsmString = cast<StringLiteral>(expr);
18236 
18237   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18238                                                    AsmString, StartLoc,
18239                                                    EndLoc);
18240   CurContext->addDecl(New);
18241   return New;
18242 }
18243 
18244 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18245                                       IdentifierInfo* AliasName,
18246                                       SourceLocation PragmaLoc,
18247                                       SourceLocation NameLoc,
18248                                       SourceLocation AliasNameLoc) {
18249   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18250                                          LookupOrdinaryName);
18251   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18252                            AttributeCommonInfo::AS_Pragma);
18253   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18254       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18255 
18256   // If a declaration that:
18257   // 1) declares a function or a variable
18258   // 2) has external linkage
18259   // already exists, add a label attribute to it.
18260   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18261     if (isDeclExternC(PrevDecl))
18262       PrevDecl->addAttr(Attr);
18263     else
18264       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18265           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18266   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18267   } else
18268     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18269 }
18270 
18271 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18272                              SourceLocation PragmaLoc,
18273                              SourceLocation NameLoc) {
18274   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18275 
18276   if (PrevDecl) {
18277     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18278   } else {
18279     (void)WeakUndeclaredIdentifiers.insert(
18280       std::pair<IdentifierInfo*,WeakInfo>
18281         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18282   }
18283 }
18284 
18285 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18286                                 IdentifierInfo* AliasName,
18287                                 SourceLocation PragmaLoc,
18288                                 SourceLocation NameLoc,
18289                                 SourceLocation AliasNameLoc) {
18290   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18291                                     LookupOrdinaryName);
18292   WeakInfo W = WeakInfo(Name, NameLoc);
18293 
18294   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18295     if (!PrevDecl->hasAttr<AliasAttr>())
18296       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18297         DeclApplyPragmaWeak(TUScope, ND, W);
18298   } else {
18299     (void)WeakUndeclaredIdentifiers.insert(
18300       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18301   }
18302 }
18303 
18304 Decl *Sema::getObjCDeclContext() const {
18305   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18306 }
18307 
18308 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18309                                                      bool Final) {
18310   // SYCL functions can be template, so we check if they have appropriate
18311   // attribute prior to checking if it is a template.
18312   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18313     return FunctionEmissionStatus::Emitted;
18314 
18315   // Templates are emitted when they're instantiated.
18316   if (FD->isDependentContext())
18317     return FunctionEmissionStatus::TemplateDiscarded;
18318 
18319   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18320   if (LangOpts.OpenMPIsDevice) {
18321     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18322         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18323     if (DevTy.hasValue()) {
18324       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18325         OMPES = FunctionEmissionStatus::OMPDiscarded;
18326       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18327                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18328         OMPES = FunctionEmissionStatus::Emitted;
18329       }
18330     }
18331   } else if (LangOpts.OpenMP) {
18332     // In OpenMP 4.5 all the functions are host functions.
18333     if (LangOpts.OpenMP <= 45) {
18334       OMPES = FunctionEmissionStatus::Emitted;
18335     } else {
18336       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18337           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18338       // In OpenMP 5.0 or above, DevTy may be changed later by
18339       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18340       // having no value does not imply host. The emission status will be
18341       // checked again at the end of compilation unit.
18342       if (DevTy.hasValue()) {
18343         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18344           OMPES = FunctionEmissionStatus::OMPDiscarded;
18345         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18346                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18347           OMPES = FunctionEmissionStatus::Emitted;
18348       } else if (Final)
18349         OMPES = FunctionEmissionStatus::Emitted;
18350     }
18351   }
18352   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18353       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18354     return OMPES;
18355 
18356   if (LangOpts.CUDA) {
18357     // When compiling for device, host functions are never emitted.  Similarly,
18358     // when compiling for host, device and global functions are never emitted.
18359     // (Technically, we do emit a host-side stub for global functions, but this
18360     // doesn't count for our purposes here.)
18361     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18362     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18363       return FunctionEmissionStatus::CUDADiscarded;
18364     if (!LangOpts.CUDAIsDevice &&
18365         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18366       return FunctionEmissionStatus::CUDADiscarded;
18367 
18368     // Check whether this function is externally visible -- if so, it's
18369     // known-emitted.
18370     //
18371     // We have to check the GVA linkage of the function's *definition* -- if we
18372     // only have a declaration, we don't know whether or not the function will
18373     // be emitted, because (say) the definition could include "inline".
18374     FunctionDecl *Def = FD->getDefinition();
18375 
18376     if (Def &&
18377         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18378         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18379       return FunctionEmissionStatus::Emitted;
18380   }
18381 
18382   // Otherwise, the function is known-emitted if it's in our set of
18383   // known-emitted functions.
18384   return FunctionEmissionStatus::Unknown;
18385 }
18386 
18387 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18388   // Host-side references to a __global__ function refer to the stub, so the
18389   // function itself is never emitted and therefore should not be marked.
18390   // If we have host fn calls kernel fn calls host+device, the HD function
18391   // does not get instantiated on the host. We model this by omitting at the
18392   // call to the kernel from the callgraph. This ensures that, when compiling
18393   // for host, only HD functions actually called from the host get marked as
18394   // known-emitted.
18395   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18396          IdentifyCUDATarget(Callee) == CFT_Global;
18397 }
18398