1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <functional>
52 #include <unordered_map>
53 
54 using namespace clang;
55 using namespace sema;
56 
57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58   if (OwnedType) {
59     Decl *Group[2] = { OwnedType, Ptr };
60     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61   }
62 
63   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 }
65 
66 namespace {
67 
68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69  public:
70    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71                         bool AllowTemplates = false,
72                         bool AllowNonTemplates = true)
73        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75      WantExpressionKeywords = false;
76      WantCXXNamedCasts = false;
77      WantRemainingKeywords = false;
78   }
79 
80   bool ValidateCandidate(const TypoCorrection &candidate) override {
81     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82       if (!AllowInvalidDecl && ND->isInvalidDecl())
83         return false;
84 
85       if (getAsTypeTemplateDecl(ND))
86         return AllowTemplates;
87 
88       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89       if (!IsType)
90         return false;
91 
92       if (AllowNonTemplates)
93         return true;
94 
95       // An injected-class-name of a class template (specialization) is valid
96       // as a template or as a non-template.
97       if (AllowTemplates) {
98         auto *RD = dyn_cast<CXXRecordDecl>(ND);
99         if (!RD || !RD->isInjectedClassName())
100           return false;
101         RD = cast<CXXRecordDecl>(RD->getDeclContext());
102         return RD->getDescribedClassTemplate() ||
103                isa<ClassTemplateSpecializationDecl>(RD);
104       }
105 
106       return false;
107     }
108 
109     return !WantClassName && candidate.isKeyword();
110   }
111 
112   std::unique_ptr<CorrectionCandidateCallback> clone() override {
113     return std::make_unique<TypeNameValidatorCCC>(*this);
114   }
115 
116  private:
117   bool AllowInvalidDecl;
118   bool WantClassName;
119   bool AllowTemplates;
120   bool AllowNonTemplates;
121 };
122 
123 } // end anonymous namespace
124 
125 /// Determine whether the token kind starts a simple-type-specifier.
126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127   switch (Kind) {
128   // FIXME: Take into account the current language when deciding whether a
129   // token kind is a valid type specifier
130   case tok::kw_short:
131   case tok::kw_long:
132   case tok::kw___int64:
133   case tok::kw___int128:
134   case tok::kw_signed:
135   case tok::kw_unsigned:
136   case tok::kw_void:
137   case tok::kw_char:
138   case tok::kw_int:
139   case tok::kw_half:
140   case tok::kw_float:
141   case tok::kw_double:
142   case tok::kw___bf16:
143   case tok::kw__Float16:
144   case tok::kw___float128:
145   case tok::kw___ibm128:
146   case tok::kw_wchar_t:
147   case tok::kw_bool:
148   case tok::kw___underlying_type:
149   case tok::kw___auto_type:
150     return true;
151 
152   case tok::annot_typename:
153   case tok::kw_char16_t:
154   case tok::kw_char32_t:
155   case tok::kw_typeof:
156   case tok::annot_decltype:
157   case tok::kw_decltype:
158     return getLangOpts().CPlusPlus;
159 
160   case tok::kw_char8_t:
161     return getLangOpts().Char8;
162 
163   default:
164     break;
165   }
166 
167   return false;
168 }
169 
170 namespace {
171 enum class UnqualifiedTypeNameLookupResult {
172   NotFound,
173   FoundNonType,
174   FoundType
175 };
176 } // end anonymous namespace
177 
178 /// Tries to perform unqualified lookup of the type decls in bases for
179 /// dependent class.
180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
181 /// type decl, \a FoundType if only type decls are found.
182 static UnqualifiedTypeNameLookupResult
183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
184                                 SourceLocation NameLoc,
185                                 const CXXRecordDecl *RD) {
186   if (!RD->hasDefinition())
187     return UnqualifiedTypeNameLookupResult::NotFound;
188   // Look for type decls in base classes.
189   UnqualifiedTypeNameLookupResult FoundTypeDecl =
190       UnqualifiedTypeNameLookupResult::NotFound;
191   for (const auto &Base : RD->bases()) {
192     const CXXRecordDecl *BaseRD = nullptr;
193     if (auto *BaseTT = Base.getType()->getAs<TagType>())
194       BaseRD = BaseTT->getAsCXXRecordDecl();
195     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
196       // Look for type decls in dependent base classes that have known primary
197       // templates.
198       if (!TST || !TST->isDependentType())
199         continue;
200       auto *TD = TST->getTemplateName().getAsTemplateDecl();
201       if (!TD)
202         continue;
203       if (auto *BasePrimaryTemplate =
204           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
205         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
206           BaseRD = BasePrimaryTemplate;
207         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208           if (const ClassTemplatePartialSpecializationDecl *PS =
209                   CTD->findPartialSpecialization(Base.getType()))
210             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
211               BaseRD = PS;
212         }
213       }
214     }
215     if (BaseRD) {
216       for (NamedDecl *ND : BaseRD->lookup(&II)) {
217         if (!isa<TypeDecl>(ND))
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220       }
221       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
223         case UnqualifiedTypeNameLookupResult::FoundNonType:
224           return UnqualifiedTypeNameLookupResult::FoundNonType;
225         case UnqualifiedTypeNameLookupResult::FoundType:
226           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227           break;
228         case UnqualifiedTypeNameLookupResult::NotFound:
229           break;
230         }
231       }
232     }
233   }
234 
235   return FoundTypeDecl;
236 }
237 
238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
239                                                       const IdentifierInfo &II,
240                                                       SourceLocation NameLoc) {
241   // Lookup in the parent class template context, if any.
242   const CXXRecordDecl *RD = nullptr;
243   UnqualifiedTypeNameLookupResult FoundTypeDecl =
244       UnqualifiedTypeNameLookupResult::NotFound;
245   for (DeclContext *DC = S.CurContext;
246        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
247        DC = DC->getParent()) {
248     // Look for type decls in dependent base classes that have known primary
249     // templates.
250     RD = dyn_cast<CXXRecordDecl>(DC);
251     if (RD && RD->getDescribedClassTemplate())
252       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
253   }
254   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
255     return nullptr;
256 
257   // We found some types in dependent base classes.  Recover as if the user
258   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
259   // lookup during template instantiation.
260   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
261 
262   ASTContext &Context = S.Context;
263   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
264                                           cast<Type>(Context.getRecordType(RD)));
265   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
266 
267   CXXScopeSpec SS;
268   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
269 
270   TypeLocBuilder Builder;
271   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
272   DepTL.setNameLoc(NameLoc);
273   DepTL.setElaboratedKeywordLoc(SourceLocation());
274   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
275   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
276 }
277 
278 /// If the identifier refers to a type name within this scope,
279 /// return the declaration of that type.
280 ///
281 /// This routine performs ordinary name lookup of the identifier II
282 /// within the given scope, with optional C++ scope specifier SS, to
283 /// determine whether the name refers to a type. If so, returns an
284 /// opaque pointer (actually a QualType) corresponding to that
285 /// type. Otherwise, returns NULL.
286 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
287                              Scope *S, CXXScopeSpec *SS,
288                              bool isClassName, bool HasTrailingDot,
289                              ParsedType ObjectTypePtr,
290                              bool IsCtorOrDtorName,
291                              bool WantNontrivialTypeSourceInfo,
292                              bool IsClassTemplateDeductionContext,
293                              IdentifierInfo **CorrectedII) {
294   // FIXME: Consider allowing this outside C++1z mode as an extension.
295   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297                               !isClassName && !HasTrailingDot;
298 
299   // Determine where we will perform name lookup.
300   DeclContext *LookupCtx = nullptr;
301   if (ObjectTypePtr) {
302     QualType ObjectType = ObjectTypePtr.get();
303     if (ObjectType->isRecordType())
304       LookupCtx = computeDeclContext(ObjectType);
305   } else if (SS && SS->isNotEmpty()) {
306     LookupCtx = computeDeclContext(*SS, false);
307 
308     if (!LookupCtx) {
309       if (isDependentScopeSpecifier(*SS)) {
310         // C++ [temp.res]p3:
311         //   A qualified-id that refers to a type and in which the
312         //   nested-name-specifier depends on a template-parameter (14.6.2)
313         //   shall be prefixed by the keyword typename to indicate that the
314         //   qualified-id denotes a type, forming an
315         //   elaborated-type-specifier (7.1.5.3).
316         //
317         // We therefore do not perform any name lookup if the result would
318         // refer to a member of an unknown specialization.
319         if (!isClassName && !IsCtorOrDtorName)
320           return nullptr;
321 
322         // We know from the grammar that this name refers to a type,
323         // so build a dependent node to describe the type.
324         if (WantNontrivialTypeSourceInfo)
325           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
326 
327         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
328         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
329                                        II, NameLoc);
330         return ParsedType::make(T);
331       }
332 
333       return nullptr;
334     }
335 
336     if (!LookupCtx->isDependentContext() &&
337         RequireCompleteDeclContext(*SS, LookupCtx))
338       return nullptr;
339   }
340 
341   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
342   // lookup for class-names.
343   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
344                                       LookupOrdinaryName;
345   LookupResult Result(*this, &II, NameLoc, Kind);
346   if (LookupCtx) {
347     // Perform "qualified" name lookup into the declaration context we
348     // computed, which is either the type of the base of a member access
349     // expression or the declaration context associated with a prior
350     // nested-name-specifier.
351     LookupQualifiedName(Result, LookupCtx);
352 
353     if (ObjectTypePtr && Result.empty()) {
354       // C++ [basic.lookup.classref]p3:
355       //   If the unqualified-id is ~type-name, the type-name is looked up
356       //   in the context of the entire postfix-expression. If the type T of
357       //   the object expression is of a class type C, the type-name is also
358       //   looked up in the scope of class C. At least one of the lookups shall
359       //   find a name that refers to (possibly cv-qualified) T.
360       LookupName(Result, S);
361     }
362   } else {
363     // Perform unqualified name lookup.
364     LookupName(Result, S);
365 
366     // For unqualified lookup in a class template in MSVC mode, look into
367     // dependent base classes where the primary class template is known.
368     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
369       if (ParsedType TypeInBase =
370               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
371         return TypeInBase;
372     }
373   }
374 
375   NamedDecl *IIDecl = nullptr;
376   UsingShadowDecl *FoundUsingShadow = nullptr;
377   switch (Result.getResultKind()) {
378   case LookupResult::NotFound:
379   case LookupResult::NotFoundInCurrentInstantiation:
380     if (CorrectedII) {
381       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
382                                AllowDeducedTemplate);
383       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
384                                               S, SS, CCC, CTK_ErrorRecovery);
385       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
386       TemplateTy Template;
387       bool MemberOfUnknownSpecialization;
388       UnqualifiedId TemplateName;
389       TemplateName.setIdentifier(NewII, NameLoc);
390       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
391       CXXScopeSpec NewSS, *NewSSPtr = SS;
392       if (SS && NNS) {
393         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
394         NewSSPtr = &NewSS;
395       }
396       if (Correction && (NNS || NewII != &II) &&
397           // Ignore a correction to a template type as the to-be-corrected
398           // identifier is not a template (typo correction for template names
399           // is handled elsewhere).
400           !(getLangOpts().CPlusPlus && NewSSPtr &&
401             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
402                            Template, MemberOfUnknownSpecialization))) {
403         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
404                                     isClassName, HasTrailingDot, ObjectTypePtr,
405                                     IsCtorOrDtorName,
406                                     WantNontrivialTypeSourceInfo,
407                                     IsClassTemplateDeductionContext);
408         if (Ty) {
409           diagnoseTypo(Correction,
410                        PDiag(diag::err_unknown_type_or_class_name_suggest)
411                          << Result.getLookupName() << isClassName);
412           if (SS && NNS)
413             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
414           *CorrectedII = NewII;
415           return Ty;
416         }
417       }
418     }
419     // If typo correction failed or was not performed, fall through
420     LLVM_FALLTHROUGH;
421   case LookupResult::FoundOverloaded:
422   case LookupResult::FoundUnresolvedValue:
423     Result.suppressDiagnostics();
424     return nullptr;
425 
426   case LookupResult::Ambiguous:
427     // Recover from type-hiding ambiguities by hiding the type.  We'll
428     // do the lookup again when looking for an object, and we can
429     // diagnose the error then.  If we don't do this, then the error
430     // about hiding the type will be immediately followed by an error
431     // that only makes sense if the identifier was treated like a type.
432     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
433       Result.suppressDiagnostics();
434       return nullptr;
435     }
436 
437     // Look to see if we have a type anywhere in the list of results.
438     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
439          Res != ResEnd; ++Res) {
440       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
441       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
442               RealRes) ||
443           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
444         if (!IIDecl ||
445             // Make the selection of the recovery decl deterministic.
446             RealRes->getLocation() < IIDecl->getLocation()) {
447           IIDecl = RealRes;
448           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
449         }
450       }
451     }
452 
453     if (!IIDecl) {
454       // None of the entities we found is a type, so there is no way
455       // to even assume that the result is a type. In this case, don't
456       // complain about the ambiguity. The parser will either try to
457       // perform this lookup again (e.g., as an object name), which
458       // will produce the ambiguity, or will complain that it expected
459       // a type name.
460       Result.suppressDiagnostics();
461       return nullptr;
462     }
463 
464     // We found a type within the ambiguous lookup; diagnose the
465     // ambiguity and then return that type. This might be the right
466     // answer, or it might not be, but it suppresses any attempt to
467     // perform the name lookup again.
468     break;
469 
470   case LookupResult::Found:
471     IIDecl = Result.getFoundDecl();
472     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
473     break;
474   }
475 
476   assert(IIDecl && "Didn't find decl");
477 
478   QualType T;
479   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
480     // C++ [class.qual]p2: A lookup that would find the injected-class-name
481     // instead names the constructors of the class, except when naming a class.
482     // This is ill-formed when we're not actually forming a ctor or dtor name.
483     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
484     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
485     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
486         FoundRD->isInjectedClassName() &&
487         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
488       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
489           << &II << /*Type*/1;
490 
491     DiagnoseUseOfDecl(IIDecl, NameLoc);
492 
493     T = Context.getTypeDeclType(TD);
494     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
495   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
496     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
497     if (!HasTrailingDot)
498       T = Context.getObjCInterfaceType(IDecl);
499     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
500   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
501     (void)DiagnoseUseOfDecl(UD, NameLoc);
502     // Recover with 'int'
503     T = Context.IntTy;
504     FoundUsingShadow = nullptr;
505   } else if (AllowDeducedTemplate) {
506     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
507       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
508       TemplateName Template =
509           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
510       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
511                                                        false);
512       // Don't wrap in a further UsingType.
513       FoundUsingShadow = nullptr;
514     }
515   }
516 
517   if (T.isNull()) {
518     // If it's not plausibly a type, suppress diagnostics.
519     Result.suppressDiagnostics();
520     return nullptr;
521   }
522 
523   if (FoundUsingShadow)
524     T = Context.getUsingType(FoundUsingShadow, T);
525 
526   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
527   // constructor or destructor name (in such a case, the scope specifier
528   // will be attached to the enclosing Expr or Decl node).
529   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
530       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
531     if (WantNontrivialTypeSourceInfo) {
532       // Construct a type with type-source information.
533       TypeLocBuilder Builder;
534       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
535 
536       T = getElaboratedType(ETK_None, *SS, T);
537       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
538       ElabTL.setElaboratedKeywordLoc(SourceLocation());
539       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
540       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
541     } else {
542       T = getElaboratedType(ETK_None, *SS, T);
543     }
544   }
545 
546   return ParsedType::make(T);
547 }
548 
549 // Builds a fake NNS for the given decl context.
550 static NestedNameSpecifier *
551 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
552   for (;; DC = DC->getLookupParent()) {
553     DC = DC->getPrimaryContext();
554     auto *ND = dyn_cast<NamespaceDecl>(DC);
555     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
556       return NestedNameSpecifier::Create(Context, nullptr, ND);
557     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
558       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
559                                          RD->getTypeForDecl());
560     else if (isa<TranslationUnitDecl>(DC))
561       return NestedNameSpecifier::GlobalSpecifier(Context);
562   }
563   llvm_unreachable("something isn't in TU scope?");
564 }
565 
566 /// Find the parent class with dependent bases of the innermost enclosing method
567 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
568 /// up allowing unqualified dependent type names at class-level, which MSVC
569 /// correctly rejects.
570 static const CXXRecordDecl *
571 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
572   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
573     DC = DC->getPrimaryContext();
574     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
575       if (MD->getParent()->hasAnyDependentBases())
576         return MD->getParent();
577   }
578   return nullptr;
579 }
580 
581 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
582                                           SourceLocation NameLoc,
583                                           bool IsTemplateTypeArg) {
584   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
585 
586   NestedNameSpecifier *NNS = nullptr;
587   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
588     // If we weren't able to parse a default template argument, delay lookup
589     // until instantiation time by making a non-dependent DependentTypeName. We
590     // pretend we saw a NestedNameSpecifier referring to the current scope, and
591     // lookup is retried.
592     // FIXME: This hurts our diagnostic quality, since we get errors like "no
593     // type named 'Foo' in 'current_namespace'" when the user didn't write any
594     // name specifiers.
595     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
596     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
597   } else if (const CXXRecordDecl *RD =
598                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
599     // Build a DependentNameType that will perform lookup into RD at
600     // instantiation time.
601     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
602                                       RD->getTypeForDecl());
603 
604     // Diagnose that this identifier was undeclared, and retry the lookup during
605     // template instantiation.
606     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
607                                                                       << RD;
608   } else {
609     // This is not a situation that we should recover from.
610     return ParsedType();
611   }
612 
613   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
614 
615   // Build type location information.  We synthesized the qualifier, so we have
616   // to build a fake NestedNameSpecifierLoc.
617   NestedNameSpecifierLocBuilder NNSLocBuilder;
618   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
619   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
620 
621   TypeLocBuilder Builder;
622   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
623   DepTL.setNameLoc(NameLoc);
624   DepTL.setElaboratedKeywordLoc(SourceLocation());
625   DepTL.setQualifierLoc(QualifierLoc);
626   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
627 }
628 
629 /// isTagName() - This method is called *for error recovery purposes only*
630 /// to determine if the specified name is a valid tag name ("struct foo").  If
631 /// so, this returns the TST for the tag corresponding to it (TST_enum,
632 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
633 /// cases in C where the user forgot to specify the tag.
634 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
635   // Do a tag name lookup in this scope.
636   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
637   LookupName(R, S, false);
638   R.suppressDiagnostics();
639   if (R.getResultKind() == LookupResult::Found)
640     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
641       switch (TD->getTagKind()) {
642       case TTK_Struct: return DeclSpec::TST_struct;
643       case TTK_Interface: return DeclSpec::TST_interface;
644       case TTK_Union:  return DeclSpec::TST_union;
645       case TTK_Class:  return DeclSpec::TST_class;
646       case TTK_Enum:   return DeclSpec::TST_enum;
647       }
648     }
649 
650   return DeclSpec::TST_unspecified;
651 }
652 
653 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
654 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
655 /// then downgrade the missing typename error to a warning.
656 /// This is needed for MSVC compatibility; Example:
657 /// @code
658 /// template<class T> class A {
659 /// public:
660 ///   typedef int TYPE;
661 /// };
662 /// template<class T> class B : public A<T> {
663 /// public:
664 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
665 /// };
666 /// @endcode
667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
668   if (CurContext->isRecord()) {
669     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
670       return true;
671 
672     const Type *Ty = SS->getScopeRep()->getAsType();
673 
674     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675     for (const auto &Base : RD->bases())
676       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677         return true;
678     return S->isFunctionPrototypeScope();
679   }
680   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
681 }
682 
683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
684                                    SourceLocation IILoc,
685                                    Scope *S,
686                                    CXXScopeSpec *SS,
687                                    ParsedType &SuggestedType,
688                                    bool IsTemplateName) {
689   // Don't report typename errors for editor placeholders.
690   if (II->isEditorPlaceholder())
691     return;
692   // We don't have anything to suggest (yet).
693   SuggestedType = nullptr;
694 
695   // There may have been a typo in the name of the type. Look up typo
696   // results, in case we have something that we can suggest.
697   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698                            /*AllowTemplates=*/IsTemplateName,
699                            /*AllowNonTemplates=*/!IsTemplateName);
700   if (TypoCorrection Corrected =
701           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
702                       CCC, CTK_ErrorRecovery)) {
703     // FIXME: Support error recovery for the template-name case.
704     bool CanRecover = !IsTemplateName;
705     if (Corrected.isKeyword()) {
706       // We corrected to a keyword.
707       diagnoseTypo(Corrected,
708                    PDiag(IsTemplateName ? diag::err_no_template_suggest
709                                         : diag::err_unknown_typename_suggest)
710                        << II);
711       II = Corrected.getCorrectionAsIdentifierInfo();
712     } else {
713       // We found a similarly-named type or interface; suggest that.
714       if (!SS || !SS->isSet()) {
715         diagnoseTypo(Corrected,
716                      PDiag(IsTemplateName ? diag::err_no_template_suggest
717                                           : diag::err_unknown_typename_suggest)
718                          << II, CanRecover);
719       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
722                                 II->getName().equals(CorrectedStr);
723         diagnoseTypo(Corrected,
724                      PDiag(IsTemplateName
725                                ? diag::err_no_member_template_suggest
726                                : diag::err_unknown_nested_typename_suggest)
727                          << II << DC << DroppedSpecifier << SS->getRange(),
728                      CanRecover);
729       } else {
730         llvm_unreachable("could not have corrected a typo here");
731       }
732 
733       if (!CanRecover)
734         return;
735 
736       CXXScopeSpec tmpSS;
737       if (Corrected.getCorrectionSpecifier())
738         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739                           SourceRange(IILoc));
740       // FIXME: Support class template argument deduction here.
741       SuggestedType =
742           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744                       /*IsCtorOrDtorName=*/false,
745                       /*WantNontrivialTypeSourceInfo=*/true);
746     }
747     return;
748   }
749 
750   if (getLangOpts().CPlusPlus && !IsTemplateName) {
751     // See if II is a class template that the user forgot to pass arguments to.
752     UnqualifiedId Name;
753     Name.setIdentifier(II, IILoc);
754     CXXScopeSpec EmptySS;
755     TemplateTy TemplateResult;
756     bool MemberOfUnknownSpecialization;
757     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758                        Name, nullptr, true, TemplateResult,
759                        MemberOfUnknownSpecialization) == TNK_Type_template) {
760       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761       return;
762     }
763   }
764 
765   // FIXME: Should we move the logic that tries to recover from a missing tag
766   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
767 
768   if (!SS || (!SS->isSet() && !SS->isInvalid()))
769     Diag(IILoc, IsTemplateName ? diag::err_no_template
770                                : diag::err_unknown_typename)
771         << II;
772   else if (DeclContext *DC = computeDeclContext(*SS, false))
773     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774                                : diag::err_typename_nested_not_found)
775         << II << DC << SS->getRange();
776   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777     SuggestedType =
778         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779   } else if (isDependentScopeSpecifier(*SS)) {
780     unsigned DiagID = diag::err_typename_missing;
781     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782       DiagID = diag::ext_typename_missing;
783 
784     Diag(SS->getRange().getBegin(), DiagID)
785       << SS->getScopeRep() << II->getName()
786       << SourceRange(SS->getRange().getBegin(), IILoc)
787       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788     SuggestedType = ActOnTypenameType(S, SourceLocation(),
789                                       *SS, *II, IILoc).get();
790   } else {
791     assert(SS && SS->isInvalid() &&
792            "Invalid scope specifier has already been diagnosed");
793   }
794 }
795 
796 /// Determine whether the given result set contains either a type name
797 /// or
798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800                        NextToken.is(tok::less);
801 
802   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804       return true;
805 
806     if (CheckTemplate && isa<TemplateDecl>(*I))
807       return true;
808   }
809 
810   return false;
811 }
812 
813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
814                                     Scope *S, CXXScopeSpec &SS,
815                                     IdentifierInfo *&Name,
816                                     SourceLocation NameLoc) {
817   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818   SemaRef.LookupParsedName(R, S, &SS);
819   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820     StringRef FixItTagName;
821     switch (Tag->getTagKind()) {
822       case TTK_Class:
823         FixItTagName = "class ";
824         break;
825 
826       case TTK_Enum:
827         FixItTagName = "enum ";
828         break;
829 
830       case TTK_Struct:
831         FixItTagName = "struct ";
832         break;
833 
834       case TTK_Interface:
835         FixItTagName = "__interface ";
836         break;
837 
838       case TTK_Union:
839         FixItTagName = "union ";
840         break;
841     }
842 
843     StringRef TagName = FixItTagName.drop_back();
844     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
847 
848     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849          I != IEnd; ++I)
850       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851         << Name << TagName;
852 
853     // Replace lookup results with just the tag decl.
854     Result.clear(Sema::LookupTagName);
855     SemaRef.LookupParsedName(Result, S, &SS);
856     return true;
857   }
858 
859   return false;
860 }
861 
862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
863                                             IdentifierInfo *&Name,
864                                             SourceLocation NameLoc,
865                                             const Token &NextToken,
866                                             CorrectionCandidateCallback *CCC) {
867   DeclarationNameInfo NameInfo(Name, NameLoc);
868   ObjCMethodDecl *CurMethod = getCurMethodDecl();
869 
870   assert(NextToken.isNot(tok::coloncolon) &&
871          "parse nested name specifiers before calling ClassifyName");
872   if (getLangOpts().CPlusPlus && SS.isSet() &&
873       isCurrentClassName(*Name, S, &SS)) {
874     // Per [class.qual]p2, this names the constructors of SS, not the
875     // injected-class-name. We don't have a classification for that.
876     // There's not much point caching this result, since the parser
877     // will reject it later.
878     return NameClassification::Unknown();
879   }
880 
881   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882   LookupParsedName(Result, S, &SS, !CurMethod);
883 
884   if (SS.isInvalid())
885     return NameClassification::Error();
886 
887   // For unqualified lookup in a class template in MSVC mode, look into
888   // dependent base classes where the primary class template is known.
889   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
890     if (ParsedType TypeInBase =
891             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
892       return TypeInBase;
893   }
894 
895   // Perform lookup for Objective-C instance variables (including automatically
896   // synthesized instance variables), if we're in an Objective-C method.
897   // FIXME: This lookup really, really needs to be folded in to the normal
898   // unqualified lookup mechanism.
899   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
900     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
901     if (Ivar.isInvalid())
902       return NameClassification::Error();
903     if (Ivar.isUsable())
904       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
905 
906     // We defer builtin creation until after ivar lookup inside ObjC methods.
907     if (Result.empty())
908       LookupBuiltin(Result);
909   }
910 
911   bool SecondTry = false;
912   bool IsFilteredTemplateName = false;
913 
914 Corrected:
915   switch (Result.getResultKind()) {
916   case LookupResult::NotFound:
917     // If an unqualified-id is followed by a '(', then we have a function
918     // call.
919     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
920       // In C++, this is an ADL-only call.
921       // FIXME: Reference?
922       if (getLangOpts().CPlusPlus)
923         return NameClassification::UndeclaredNonType();
924 
925       // C90 6.3.2.2:
926       //   If the expression that precedes the parenthesized argument list in a
927       //   function call consists solely of an identifier, and if no
928       //   declaration is visible for this identifier, the identifier is
929       //   implicitly declared exactly as if, in the innermost block containing
930       //   the function call, the declaration
931       //
932       //     extern int identifier ();
933       //
934       //   appeared.
935       //
936       // We also allow this in C99 as an extension. However, this is not
937       // allowed in C2x as there are no functions without prototypes there.
938       if (!getLangOpts().C2x) {
939         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
940           return NameClassification::NonType(D);
941       }
942     }
943 
944     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
945       // In C++20 onwards, this could be an ADL-only call to a function
946       // template, and we're required to assume that this is a template name.
947       //
948       // FIXME: Find a way to still do typo correction in this case.
949       TemplateName Template =
950           Context.getAssumedTemplateName(NameInfo.getName());
951       return NameClassification::UndeclaredTemplate(Template);
952     }
953 
954     // In C, we first see whether there is a tag type by the same name, in
955     // which case it's likely that the user just forgot to write "enum",
956     // "struct", or "union".
957     if (!getLangOpts().CPlusPlus && !SecondTry &&
958         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
959       break;
960     }
961 
962     // Perform typo correction to determine if there is another name that is
963     // close to this name.
964     if (!SecondTry && CCC) {
965       SecondTry = true;
966       if (TypoCorrection Corrected =
967               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
968                           &SS, *CCC, CTK_ErrorRecovery)) {
969         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
970         unsigned QualifiedDiag = diag::err_no_member_suggest;
971 
972         NamedDecl *FirstDecl = Corrected.getFoundDecl();
973         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
974         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
975             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
976           UnqualifiedDiag = diag::err_no_template_suggest;
977           QualifiedDiag = diag::err_no_member_template_suggest;
978         } else if (UnderlyingFirstDecl &&
979                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
980                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
981                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
982           UnqualifiedDiag = diag::err_unknown_typename_suggest;
983           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
984         }
985 
986         if (SS.isEmpty()) {
987           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
988         } else {// FIXME: is this even reachable? Test it.
989           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
990           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
991                                   Name->getName().equals(CorrectedStr);
992           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
993                                     << Name << computeDeclContext(SS, false)
994                                     << DroppedSpecifier << SS.getRange());
995         }
996 
997         // Update the name, so that the caller has the new name.
998         Name = Corrected.getCorrectionAsIdentifierInfo();
999 
1000         // Typo correction corrected to a keyword.
1001         if (Corrected.isKeyword())
1002           return Name;
1003 
1004         // Also update the LookupResult...
1005         // FIXME: This should probably go away at some point
1006         Result.clear();
1007         Result.setLookupName(Corrected.getCorrection());
1008         if (FirstDecl)
1009           Result.addDecl(FirstDecl);
1010 
1011         // If we found an Objective-C instance variable, let
1012         // LookupInObjCMethod build the appropriate expression to
1013         // reference the ivar.
1014         // FIXME: This is a gross hack.
1015         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1016           DeclResult R =
1017               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1018           if (R.isInvalid())
1019             return NameClassification::Error();
1020           if (R.isUsable())
1021             return NameClassification::NonType(Ivar);
1022         }
1023 
1024         goto Corrected;
1025       }
1026     }
1027 
1028     // We failed to correct; just fall through and let the parser deal with it.
1029     Result.suppressDiagnostics();
1030     return NameClassification::Unknown();
1031 
1032   case LookupResult::NotFoundInCurrentInstantiation: {
1033     // We performed name lookup into the current instantiation, and there were
1034     // dependent bases, so we treat this result the same way as any other
1035     // dependent nested-name-specifier.
1036 
1037     // C++ [temp.res]p2:
1038     //   A name used in a template declaration or definition and that is
1039     //   dependent on a template-parameter is assumed not to name a type
1040     //   unless the applicable name lookup finds a type name or the name is
1041     //   qualified by the keyword typename.
1042     //
1043     // FIXME: If the next token is '<', we might want to ask the parser to
1044     // perform some heroics to see if we actually have a
1045     // template-argument-list, which would indicate a missing 'template'
1046     // keyword here.
1047     return NameClassification::DependentNonType();
1048   }
1049 
1050   case LookupResult::Found:
1051   case LookupResult::FoundOverloaded:
1052   case LookupResult::FoundUnresolvedValue:
1053     break;
1054 
1055   case LookupResult::Ambiguous:
1056     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1057         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1058                                       /*AllowDependent=*/false)) {
1059       // C++ [temp.local]p3:
1060       //   A lookup that finds an injected-class-name (10.2) can result in an
1061       //   ambiguity in certain cases (for example, if it is found in more than
1062       //   one base class). If all of the injected-class-names that are found
1063       //   refer to specializations of the same class template, and if the name
1064       //   is followed by a template-argument-list, the reference refers to the
1065       //   class template itself and not a specialization thereof, and is not
1066       //   ambiguous.
1067       //
1068       // This filtering can make an ambiguous result into an unambiguous one,
1069       // so try again after filtering out template names.
1070       FilterAcceptableTemplateNames(Result);
1071       if (!Result.isAmbiguous()) {
1072         IsFilteredTemplateName = true;
1073         break;
1074       }
1075     }
1076 
1077     // Diagnose the ambiguity and return an error.
1078     return NameClassification::Error();
1079   }
1080 
1081   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1082       (IsFilteredTemplateName ||
1083        hasAnyAcceptableTemplateNames(
1084            Result, /*AllowFunctionTemplates=*/true,
1085            /*AllowDependent=*/false,
1086            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1087                getLangOpts().CPlusPlus20))) {
1088     // C++ [temp.names]p3:
1089     //   After name lookup (3.4) finds that a name is a template-name or that
1090     //   an operator-function-id or a literal- operator-id refers to a set of
1091     //   overloaded functions any member of which is a function template if
1092     //   this is followed by a <, the < is always taken as the delimiter of a
1093     //   template-argument-list and never as the less-than operator.
1094     // C++2a [temp.names]p2:
1095     //   A name is also considered to refer to a template if it is an
1096     //   unqualified-id followed by a < and name lookup finds either one
1097     //   or more functions or finds nothing.
1098     if (!IsFilteredTemplateName)
1099       FilterAcceptableTemplateNames(Result);
1100 
1101     bool IsFunctionTemplate;
1102     bool IsVarTemplate;
1103     TemplateName Template;
1104     if (Result.end() - Result.begin() > 1) {
1105       IsFunctionTemplate = true;
1106       Template = Context.getOverloadedTemplateName(Result.begin(),
1107                                                    Result.end());
1108     } else if (!Result.empty()) {
1109       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1110           *Result.begin(), /*AllowFunctionTemplates=*/true,
1111           /*AllowDependent=*/false));
1112       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1113       IsVarTemplate = isa<VarTemplateDecl>(TD);
1114 
1115       UsingShadowDecl *FoundUsingShadow =
1116           dyn_cast<UsingShadowDecl>(*Result.begin());
1117       assert(!FoundUsingShadow ||
1118              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1119       Template =
1120           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1121       if (SS.isNotEmpty())
1122         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1123                                                     /*TemplateKeyword=*/false,
1124                                                     Template);
1125     } else {
1126       // All results were non-template functions. This is a function template
1127       // name.
1128       IsFunctionTemplate = true;
1129       Template = Context.getAssumedTemplateName(NameInfo.getName());
1130     }
1131 
1132     if (IsFunctionTemplate) {
1133       // Function templates always go through overload resolution, at which
1134       // point we'll perform the various checks (e.g., accessibility) we need
1135       // to based on which function we selected.
1136       Result.suppressDiagnostics();
1137 
1138       return NameClassification::FunctionTemplate(Template);
1139     }
1140 
1141     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1142                          : NameClassification::TypeTemplate(Template);
1143   }
1144 
1145   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1146     QualType T = Context.getTypeDeclType(Type);
1147     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1148       T = Context.getUsingType(USD, T);
1149 
1150     if (SS.isEmpty()) // No elaborated type, trivial location info
1151       return ParsedType::make(T);
1152 
1153     TypeLocBuilder Builder;
1154     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1155     T = getElaboratedType(ETK_None, SS, T);
1156     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1157     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1158     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1159     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1160   };
1161 
1162   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1163   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1164     DiagnoseUseOfDecl(Type, NameLoc);
1165     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1166     return BuildTypeFor(Type, *Result.begin());
1167   }
1168 
1169   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1170   if (!Class) {
1171     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1172     if (ObjCCompatibleAliasDecl *Alias =
1173             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1174       Class = Alias->getClassInterface();
1175   }
1176 
1177   if (Class) {
1178     DiagnoseUseOfDecl(Class, NameLoc);
1179 
1180     if (NextToken.is(tok::period)) {
1181       // Interface. <something> is parsed as a property reference expression.
1182       // Just return "unknown" as a fall-through for now.
1183       Result.suppressDiagnostics();
1184       return NameClassification::Unknown();
1185     }
1186 
1187     QualType T = Context.getObjCInterfaceType(Class);
1188     return ParsedType::make(T);
1189   }
1190 
1191   if (isa<ConceptDecl>(FirstDecl))
1192     return NameClassification::Concept(
1193         TemplateName(cast<TemplateDecl>(FirstDecl)));
1194 
1195   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1196     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1197     return NameClassification::Error();
1198   }
1199 
1200   // We can have a type template here if we're classifying a template argument.
1201   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1202       !isa<VarTemplateDecl>(FirstDecl))
1203     return NameClassification::TypeTemplate(
1204         TemplateName(cast<TemplateDecl>(FirstDecl)));
1205 
1206   // Check for a tag type hidden by a non-type decl in a few cases where it
1207   // seems likely a type is wanted instead of the non-type that was found.
1208   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1209   if ((NextToken.is(tok::identifier) ||
1210        (NextIsOp &&
1211         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1212       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1213     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1214     DiagnoseUseOfDecl(Type, NameLoc);
1215     return BuildTypeFor(Type, *Result.begin());
1216   }
1217 
1218   // If we already know which single declaration is referenced, just annotate
1219   // that declaration directly. Defer resolving even non-overloaded class
1220   // member accesses, as we need to defer certain access checks until we know
1221   // the context.
1222   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1223   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1224     return NameClassification::NonType(Result.getRepresentativeDecl());
1225 
1226   // Otherwise, this is an overload set that we will need to resolve later.
1227   Result.suppressDiagnostics();
1228   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1229       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1230       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1231       Result.begin(), Result.end()));
1232 }
1233 
1234 ExprResult
1235 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1236                                              SourceLocation NameLoc) {
1237   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1238   CXXScopeSpec SS;
1239   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1240   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1241 }
1242 
1243 ExprResult
1244 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1245                                             IdentifierInfo *Name,
1246                                             SourceLocation NameLoc,
1247                                             bool IsAddressOfOperand) {
1248   DeclarationNameInfo NameInfo(Name, NameLoc);
1249   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1250                                     NameInfo, IsAddressOfOperand,
1251                                     /*TemplateArgs=*/nullptr);
1252 }
1253 
1254 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1255                                               NamedDecl *Found,
1256                                               SourceLocation NameLoc,
1257                                               const Token &NextToken) {
1258   if (getCurMethodDecl() && SS.isEmpty())
1259     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1260       return BuildIvarRefExpr(S, NameLoc, Ivar);
1261 
1262   // Reconstruct the lookup result.
1263   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1264   Result.addDecl(Found);
1265   Result.resolveKind();
1266 
1267   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1268   return BuildDeclarationNameExpr(SS, Result, ADL);
1269 }
1270 
1271 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1272   // For an implicit class member access, transform the result into a member
1273   // access expression if necessary.
1274   auto *ULE = cast<UnresolvedLookupExpr>(E);
1275   if ((*ULE->decls_begin())->isCXXClassMember()) {
1276     CXXScopeSpec SS;
1277     SS.Adopt(ULE->getQualifierLoc());
1278 
1279     // Reconstruct the lookup result.
1280     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1281                         LookupOrdinaryName);
1282     Result.setNamingClass(ULE->getNamingClass());
1283     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1284       Result.addDecl(*I, I.getAccess());
1285     Result.resolveKind();
1286     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1287                                            nullptr, S);
1288   }
1289 
1290   // Otherwise, this is already in the form we needed, and no further checks
1291   // are necessary.
1292   return ULE;
1293 }
1294 
1295 Sema::TemplateNameKindForDiagnostics
1296 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1297   auto *TD = Name.getAsTemplateDecl();
1298   if (!TD)
1299     return TemplateNameKindForDiagnostics::DependentTemplate;
1300   if (isa<ClassTemplateDecl>(TD))
1301     return TemplateNameKindForDiagnostics::ClassTemplate;
1302   if (isa<FunctionTemplateDecl>(TD))
1303     return TemplateNameKindForDiagnostics::FunctionTemplate;
1304   if (isa<VarTemplateDecl>(TD))
1305     return TemplateNameKindForDiagnostics::VarTemplate;
1306   if (isa<TypeAliasTemplateDecl>(TD))
1307     return TemplateNameKindForDiagnostics::AliasTemplate;
1308   if (isa<TemplateTemplateParmDecl>(TD))
1309     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1310   if (isa<ConceptDecl>(TD))
1311     return TemplateNameKindForDiagnostics::Concept;
1312   return TemplateNameKindForDiagnostics::DependentTemplate;
1313 }
1314 
1315 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1316   assert(DC->getLexicalParent() == CurContext &&
1317       "The next DeclContext should be lexically contained in the current one.");
1318   CurContext = DC;
1319   S->setEntity(DC);
1320 }
1321 
1322 void Sema::PopDeclContext() {
1323   assert(CurContext && "DeclContext imbalance!");
1324 
1325   CurContext = CurContext->getLexicalParent();
1326   assert(CurContext && "Popped translation unit!");
1327 }
1328 
1329 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1330                                                                     Decl *D) {
1331   // Unlike PushDeclContext, the context to which we return is not necessarily
1332   // the containing DC of TD, because the new context will be some pre-existing
1333   // TagDecl definition instead of a fresh one.
1334   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1335   CurContext = cast<TagDecl>(D)->getDefinition();
1336   assert(CurContext && "skipping definition of undefined tag");
1337   // Start lookups from the parent of the current context; we don't want to look
1338   // into the pre-existing complete definition.
1339   S->setEntity(CurContext->getLookupParent());
1340   return Result;
1341 }
1342 
1343 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1344   CurContext = static_cast<decltype(CurContext)>(Context);
1345 }
1346 
1347 /// EnterDeclaratorContext - Used when we must lookup names in the context
1348 /// of a declarator's nested name specifier.
1349 ///
1350 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1351   // C++0x [basic.lookup.unqual]p13:
1352   //   A name used in the definition of a static data member of class
1353   //   X (after the qualified-id of the static member) is looked up as
1354   //   if the name was used in a member function of X.
1355   // C++0x [basic.lookup.unqual]p14:
1356   //   If a variable member of a namespace is defined outside of the
1357   //   scope of its namespace then any name used in the definition of
1358   //   the variable member (after the declarator-id) is looked up as
1359   //   if the definition of the variable member occurred in its
1360   //   namespace.
1361   // Both of these imply that we should push a scope whose context
1362   // is the semantic context of the declaration.  We can't use
1363   // PushDeclContext here because that context is not necessarily
1364   // lexically contained in the current context.  Fortunately,
1365   // the containing scope should have the appropriate information.
1366 
1367   assert(!S->getEntity() && "scope already has entity");
1368 
1369 #ifndef NDEBUG
1370   Scope *Ancestor = S->getParent();
1371   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1373 #endif
1374 
1375   CurContext = DC;
1376   S->setEntity(DC);
1377 
1378   if (S->getParent()->isTemplateParamScope()) {
1379     // Also set the corresponding entities for all immediately-enclosing
1380     // template parameter scopes.
1381     EnterTemplatedContext(S->getParent(), DC);
1382   }
1383 }
1384 
1385 void Sema::ExitDeclaratorContext(Scope *S) {
1386   assert(S->getEntity() == CurContext && "Context imbalance!");
1387 
1388   // Switch back to the lexical context.  The safety of this is
1389   // enforced by an assert in EnterDeclaratorContext.
1390   Scope *Ancestor = S->getParent();
1391   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1392   CurContext = Ancestor->getEntity();
1393 
1394   // We don't need to do anything with the scope, which is going to
1395   // disappear.
1396 }
1397 
1398 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1399   assert(S->isTemplateParamScope() &&
1400          "expected to be initializing a template parameter scope");
1401 
1402   // C++20 [temp.local]p7:
1403   //   In the definition of a member of a class template that appears outside
1404   //   of the class template definition, the name of a member of the class
1405   //   template hides the name of a template-parameter of any enclosing class
1406   //   templates (but not a template-parameter of the member if the member is a
1407   //   class or function template).
1408   // C++20 [temp.local]p9:
1409   //   In the definition of a class template or in the definition of a member
1410   //   of such a template that appears outside of the template definition, for
1411   //   each non-dependent base class (13.8.2.1), if the name of the base class
1412   //   or the name of a member of the base class is the same as the name of a
1413   //   template-parameter, the base class name or member name hides the
1414   //   template-parameter name (6.4.10).
1415   //
1416   // This means that a template parameter scope should be searched immediately
1417   // after searching the DeclContext for which it is a template parameter
1418   // scope. For example, for
1419   //   template<typename T> template<typename U> template<typename V>
1420   //     void N::A<T>::B<U>::f(...)
1421   // we search V then B<U> (and base classes) then U then A<T> (and base
1422   // classes) then T then N then ::.
1423   unsigned ScopeDepth = getTemplateDepth(S);
1424   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1425     DeclContext *SearchDCAfterScope = DC;
1426     for (; DC; DC = DC->getLookupParent()) {
1427       if (const TemplateParameterList *TPL =
1428               cast<Decl>(DC)->getDescribedTemplateParams()) {
1429         unsigned DCDepth = TPL->getDepth() + 1;
1430         if (DCDepth > ScopeDepth)
1431           continue;
1432         if (ScopeDepth == DCDepth)
1433           SearchDCAfterScope = DC = DC->getLookupParent();
1434         break;
1435       }
1436     }
1437     S->setLookupEntity(SearchDCAfterScope);
1438   }
1439 }
1440 
1441 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1442   // We assume that the caller has already called
1443   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1444   FunctionDecl *FD = D->getAsFunction();
1445   if (!FD)
1446     return;
1447 
1448   // Same implementation as PushDeclContext, but enters the context
1449   // from the lexical parent, rather than the top-level class.
1450   assert(CurContext == FD->getLexicalParent() &&
1451     "The next DeclContext should be lexically contained in the current one.");
1452   CurContext = FD;
1453   S->setEntity(CurContext);
1454 
1455   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1456     ParmVarDecl *Param = FD->getParamDecl(P);
1457     // If the parameter has an identifier, then add it to the scope
1458     if (Param->getIdentifier()) {
1459       S->AddDecl(Param);
1460       IdResolver.AddDecl(Param);
1461     }
1462   }
1463 }
1464 
1465 void Sema::ActOnExitFunctionContext() {
1466   // Same implementation as PopDeclContext, but returns to the lexical parent,
1467   // rather than the top-level class.
1468   assert(CurContext && "DeclContext imbalance!");
1469   CurContext = CurContext->getLexicalParent();
1470   assert(CurContext && "Popped translation unit!");
1471 }
1472 
1473 /// Determine whether overloading is allowed for a new function
1474 /// declaration considering prior declarations of the same name.
1475 ///
1476 /// This routine determines whether overloading is possible, not
1477 /// whether a new declaration actually overloads a previous one.
1478 /// It will return true in C++ (where overloads are alway permitted)
1479 /// or, as a C extension, when either the new declaration or a
1480 /// previous one is declared with the 'overloadable' attribute.
1481 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1482                                        ASTContext &Context,
1483                                        const FunctionDecl *New) {
1484   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1485     return true;
1486 
1487   // Multiversion function declarations are not overloads in the
1488   // usual sense of that term, but lookup will report that an
1489   // overload set was found if more than one multiversion function
1490   // declaration is present for the same name. It is therefore
1491   // inadequate to assume that some prior declaration(s) had
1492   // the overloadable attribute; checking is required. Since one
1493   // declaration is permitted to omit the attribute, it is necessary
1494   // to check at least two; hence the 'any_of' check below. Note that
1495   // the overloadable attribute is implicitly added to declarations
1496   // that were required to have it but did not.
1497   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1498     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1499       return ND->hasAttr<OverloadableAttr>();
1500     });
1501   } else if (Previous.getResultKind() == LookupResult::Found)
1502     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1503 
1504   return false;
1505 }
1506 
1507 /// Add this decl to the scope shadowed decl chains.
1508 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1509   // Move up the scope chain until we find the nearest enclosing
1510   // non-transparent context. The declaration will be introduced into this
1511   // scope.
1512   while (S->getEntity() && S->getEntity()->isTransparentContext())
1513     S = S->getParent();
1514 
1515   // Add scoped declarations into their context, so that they can be
1516   // found later. Declarations without a context won't be inserted
1517   // into any context.
1518   if (AddToContext)
1519     CurContext->addDecl(D);
1520 
1521   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1522   // are function-local declarations.
1523   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1524     return;
1525 
1526   // Template instantiations should also not be pushed into scope.
1527   if (isa<FunctionDecl>(D) &&
1528       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1529     return;
1530 
1531   // If this replaces anything in the current scope,
1532   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1533                                IEnd = IdResolver.end();
1534   for (; I != IEnd; ++I) {
1535     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1536       S->RemoveDecl(*I);
1537       IdResolver.RemoveDecl(*I);
1538 
1539       // Should only need to replace one decl.
1540       break;
1541     }
1542   }
1543 
1544   S->AddDecl(D);
1545 
1546   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1547     // Implicitly-generated labels may end up getting generated in an order that
1548     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1549     // the label at the appropriate place in the identifier chain.
1550     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1551       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1552       if (IDC == CurContext) {
1553         if (!S->isDeclScope(*I))
1554           continue;
1555       } else if (IDC->Encloses(CurContext))
1556         break;
1557     }
1558 
1559     IdResolver.InsertDeclAfter(I, D);
1560   } else {
1561     IdResolver.AddDecl(D);
1562   }
1563   warnOnReservedIdentifier(D);
1564 }
1565 
1566 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1567                          bool AllowInlineNamespace) {
1568   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1569 }
1570 
1571 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1572   DeclContext *TargetDC = DC->getPrimaryContext();
1573   do {
1574     if (DeclContext *ScopeDC = S->getEntity())
1575       if (ScopeDC->getPrimaryContext() == TargetDC)
1576         return S;
1577   } while ((S = S->getParent()));
1578 
1579   return nullptr;
1580 }
1581 
1582 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1583                                             DeclContext*,
1584                                             ASTContext&);
1585 
1586 /// Filters out lookup results that don't fall within the given scope
1587 /// as determined by isDeclInScope.
1588 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1589                                 bool ConsiderLinkage,
1590                                 bool AllowInlineNamespace) {
1591   LookupResult::Filter F = R.makeFilter();
1592   while (F.hasNext()) {
1593     NamedDecl *D = F.next();
1594 
1595     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1596       continue;
1597 
1598     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1599       continue;
1600 
1601     F.erase();
1602   }
1603 
1604   F.done();
1605 }
1606 
1607 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1608 /// have compatible owning modules.
1609 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1610   // [module.interface]p7:
1611   // A declaration is attached to a module as follows:
1612   // - If the declaration is a non-dependent friend declaration that nominates a
1613   // function with a declarator-id that is a qualified-id or template-id or that
1614   // nominates a class other than with an elaborated-type-specifier with neither
1615   // a nested-name-specifier nor a simple-template-id, it is attached to the
1616   // module to which the friend is attached ([basic.link]).
1617   if (New->getFriendObjectKind() &&
1618       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1619     New->setLocalOwningModule(Old->getOwningModule());
1620     makeMergedDefinitionVisible(New);
1621     return false;
1622   }
1623 
1624   Module *NewM = New->getOwningModule();
1625   Module *OldM = Old->getOwningModule();
1626 
1627   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1628     NewM = NewM->Parent;
1629   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1630     OldM = OldM->Parent;
1631 
1632   // If we have a decl in a module partition, it is part of the containing
1633   // module (which is the only thing that can be importing it).
1634   if (NewM && OldM &&
1635       (OldM->Kind == Module::ModulePartitionInterface ||
1636        OldM->Kind == Module::ModulePartitionImplementation)) {
1637     return false;
1638   }
1639 
1640   if (NewM == OldM)
1641     return false;
1642 
1643   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1644   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1645   if (NewIsModuleInterface || OldIsModuleInterface) {
1646     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1647     //   if a declaration of D [...] appears in the purview of a module, all
1648     //   other such declarations shall appear in the purview of the same module
1649     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1650       << New
1651       << NewIsModuleInterface
1652       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1653       << OldIsModuleInterface
1654       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1655     Diag(Old->getLocation(), diag::note_previous_declaration);
1656     New->setInvalidDecl();
1657     return true;
1658   }
1659 
1660   return false;
1661 }
1662 
1663 // [module.interface]p6:
1664 // A redeclaration of an entity X is implicitly exported if X was introduced by
1665 // an exported declaration; otherwise it shall not be exported.
1666 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1667   // [module.interface]p1:
1668   // An export-declaration shall inhabit a namespace scope.
1669   //
1670   // So it is meaningless to talk about redeclaration which is not at namespace
1671   // scope.
1672   if (!New->getLexicalDeclContext()
1673            ->getNonTransparentContext()
1674            ->isFileContext() ||
1675       !Old->getLexicalDeclContext()
1676            ->getNonTransparentContext()
1677            ->isFileContext())
1678     return false;
1679 
1680   bool IsNewExported = New->isInExportDeclContext();
1681   bool IsOldExported = Old->isInExportDeclContext();
1682 
1683   // It should be irrevelant if both of them are not exported.
1684   if (!IsNewExported && !IsOldExported)
1685     return false;
1686 
1687   if (IsOldExported)
1688     return false;
1689 
1690   assert(IsNewExported);
1691 
1692   auto Lk = Old->getFormalLinkage();
1693   int S = 0;
1694   if (Lk == Linkage::InternalLinkage)
1695     S = 1;
1696   else if (Lk == Linkage::ModuleLinkage)
1697     S = 2;
1698   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1699   Diag(Old->getLocation(), diag::note_previous_declaration);
1700   return true;
1701 }
1702 
1703 // A wrapper function for checking the semantic restrictions of
1704 // a redeclaration within a module.
1705 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1706   if (CheckRedeclarationModuleOwnership(New, Old))
1707     return true;
1708 
1709   if (CheckRedeclarationExported(New, Old))
1710     return true;
1711 
1712   return false;
1713 }
1714 
1715 static bool isUsingDecl(NamedDecl *D) {
1716   return isa<UsingShadowDecl>(D) ||
1717          isa<UnresolvedUsingTypenameDecl>(D) ||
1718          isa<UnresolvedUsingValueDecl>(D);
1719 }
1720 
1721 /// Removes using shadow declarations from the lookup results.
1722 static void RemoveUsingDecls(LookupResult &R) {
1723   LookupResult::Filter F = R.makeFilter();
1724   while (F.hasNext())
1725     if (isUsingDecl(F.next()))
1726       F.erase();
1727 
1728   F.done();
1729 }
1730 
1731 /// Check for this common pattern:
1732 /// @code
1733 /// class S {
1734 ///   S(const S&); // DO NOT IMPLEMENT
1735 ///   void operator=(const S&); // DO NOT IMPLEMENT
1736 /// };
1737 /// @endcode
1738 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1739   // FIXME: Should check for private access too but access is set after we get
1740   // the decl here.
1741   if (D->doesThisDeclarationHaveABody())
1742     return false;
1743 
1744   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1745     return CD->isCopyConstructor();
1746   return D->isCopyAssignmentOperator();
1747 }
1748 
1749 // We need this to handle
1750 //
1751 // typedef struct {
1752 //   void *foo() { return 0; }
1753 // } A;
1754 //
1755 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1756 // for example. If 'A', foo will have external linkage. If we have '*A',
1757 // foo will have no linkage. Since we can't know until we get to the end
1758 // of the typedef, this function finds out if D might have non-external linkage.
1759 // Callers should verify at the end of the TU if it D has external linkage or
1760 // not.
1761 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1762   const DeclContext *DC = D->getDeclContext();
1763   while (!DC->isTranslationUnit()) {
1764     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1765       if (!RD->hasNameForLinkage())
1766         return true;
1767     }
1768     DC = DC->getParent();
1769   }
1770 
1771   return !D->isExternallyVisible();
1772 }
1773 
1774 // FIXME: This needs to be refactored; some other isInMainFile users want
1775 // these semantics.
1776 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1777   if (S.TUKind != TU_Complete)
1778     return false;
1779   return S.SourceMgr.isInMainFile(Loc);
1780 }
1781 
1782 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1783   assert(D);
1784 
1785   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1786     return false;
1787 
1788   // Ignore all entities declared within templates, and out-of-line definitions
1789   // of members of class templates.
1790   if (D->getDeclContext()->isDependentContext() ||
1791       D->getLexicalDeclContext()->isDependentContext())
1792     return false;
1793 
1794   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1795     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1796       return false;
1797     // A non-out-of-line declaration of a member specialization was implicitly
1798     // instantiated; it's the out-of-line declaration that we're interested in.
1799     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1800         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1801       return false;
1802 
1803     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1804       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1805         return false;
1806     } else {
1807       // 'static inline' functions are defined in headers; don't warn.
1808       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1809         return false;
1810     }
1811 
1812     if (FD->doesThisDeclarationHaveABody() &&
1813         Context.DeclMustBeEmitted(FD))
1814       return false;
1815   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1816     // Constants and utility variables are defined in headers with internal
1817     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1818     // like "inline".)
1819     if (!isMainFileLoc(*this, VD->getLocation()))
1820       return false;
1821 
1822     if (Context.DeclMustBeEmitted(VD))
1823       return false;
1824 
1825     if (VD->isStaticDataMember() &&
1826         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1827       return false;
1828     if (VD->isStaticDataMember() &&
1829         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1830         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1831       return false;
1832 
1833     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1834       return false;
1835   } else {
1836     return false;
1837   }
1838 
1839   // Only warn for unused decls internal to the translation unit.
1840   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1841   // for inline functions defined in the main source file, for instance.
1842   return mightHaveNonExternalLinkage(D);
1843 }
1844 
1845 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1846   if (!D)
1847     return;
1848 
1849   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1850     const FunctionDecl *First = FD->getFirstDecl();
1851     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1852       return; // First should already be in the vector.
1853   }
1854 
1855   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1856     const VarDecl *First = VD->getFirstDecl();
1857     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1858       return; // First should already be in the vector.
1859   }
1860 
1861   if (ShouldWarnIfUnusedFileScopedDecl(D))
1862     UnusedFileScopedDecls.push_back(D);
1863 }
1864 
1865 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1866   if (D->isInvalidDecl())
1867     return false;
1868 
1869   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1870     // For a decomposition declaration, warn if none of the bindings are
1871     // referenced, instead of if the variable itself is referenced (which
1872     // it is, by the bindings' expressions).
1873     for (auto *BD : DD->bindings())
1874       if (BD->isReferenced())
1875         return false;
1876   } else if (!D->getDeclName()) {
1877     return false;
1878   } else if (D->isReferenced() || D->isUsed()) {
1879     return false;
1880   }
1881 
1882   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1883     return false;
1884 
1885   if (isa<LabelDecl>(D))
1886     return true;
1887 
1888   // Except for labels, we only care about unused decls that are local to
1889   // functions.
1890   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1891   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1892     // For dependent types, the diagnostic is deferred.
1893     WithinFunction =
1894         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1895   if (!WithinFunction)
1896     return false;
1897 
1898   if (isa<TypedefNameDecl>(D))
1899     return true;
1900 
1901   // White-list anything that isn't a local variable.
1902   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1903     return false;
1904 
1905   // Types of valid local variables should be complete, so this should succeed.
1906   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1907 
1908     const Expr *Init = VD->getInit();
1909     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1910       Init = Cleanups->getSubExpr();
1911 
1912     const auto *Ty = VD->getType().getTypePtr();
1913 
1914     // Only look at the outermost level of typedef.
1915     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1916       // Allow anything marked with __attribute__((unused)).
1917       if (TT->getDecl()->hasAttr<UnusedAttr>())
1918         return false;
1919     }
1920 
1921     // Warn for reference variables whose initializtion performs lifetime
1922     // extension.
1923     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1924       if (MTE->getExtendingDecl()) {
1925         Ty = VD->getType().getNonReferenceType().getTypePtr();
1926         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1927       }
1928     }
1929 
1930     // If we failed to complete the type for some reason, or if the type is
1931     // dependent, don't diagnose the variable.
1932     if (Ty->isIncompleteType() || Ty->isDependentType())
1933       return false;
1934 
1935     // Look at the element type to ensure that the warning behaviour is
1936     // consistent for both scalars and arrays.
1937     Ty = Ty->getBaseElementTypeUnsafe();
1938 
1939     if (const TagType *TT = Ty->getAs<TagType>()) {
1940       const TagDecl *Tag = TT->getDecl();
1941       if (Tag->hasAttr<UnusedAttr>())
1942         return false;
1943 
1944       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1945         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1946           return false;
1947 
1948         if (Init) {
1949           const CXXConstructExpr *Construct =
1950             dyn_cast<CXXConstructExpr>(Init);
1951           if (Construct && !Construct->isElidable()) {
1952             CXXConstructorDecl *CD = Construct->getConstructor();
1953             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1954                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1955               return false;
1956           }
1957 
1958           // Suppress the warning if we don't know how this is constructed, and
1959           // it could possibly be non-trivial constructor.
1960           if (Init->isTypeDependent()) {
1961             for (const CXXConstructorDecl *Ctor : RD->ctors())
1962               if (!Ctor->isTrivial())
1963                 return false;
1964           }
1965 
1966           // Suppress the warning if the constructor is unresolved because
1967           // its arguments are dependent.
1968           if (isa<CXXUnresolvedConstructExpr>(Init))
1969             return false;
1970         }
1971       }
1972     }
1973 
1974     // TODO: __attribute__((unused)) templates?
1975   }
1976 
1977   return true;
1978 }
1979 
1980 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1981                                      FixItHint &Hint) {
1982   if (isa<LabelDecl>(D)) {
1983     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1984         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1985         true);
1986     if (AfterColon.isInvalid())
1987       return;
1988     Hint = FixItHint::CreateRemoval(
1989         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1990   }
1991 }
1992 
1993 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1994   if (D->getTypeForDecl()->isDependentType())
1995     return;
1996 
1997   for (auto *TmpD : D->decls()) {
1998     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1999       DiagnoseUnusedDecl(T);
2000     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2001       DiagnoseUnusedNestedTypedefs(R);
2002   }
2003 }
2004 
2005 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2006 /// unless they are marked attr(unused).
2007 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2008   if (!ShouldDiagnoseUnusedDecl(D))
2009     return;
2010 
2011   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2012     // typedefs can be referenced later on, so the diagnostics are emitted
2013     // at end-of-translation-unit.
2014     UnusedLocalTypedefNameCandidates.insert(TD);
2015     return;
2016   }
2017 
2018   FixItHint Hint;
2019   GenerateFixForUnusedDecl(D, Context, Hint);
2020 
2021   unsigned DiagID;
2022   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2023     DiagID = diag::warn_unused_exception_param;
2024   else if (isa<LabelDecl>(D))
2025     DiagID = diag::warn_unused_label;
2026   else
2027     DiagID = diag::warn_unused_variable;
2028 
2029   Diag(D->getLocation(), DiagID) << D << Hint;
2030 }
2031 
2032 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2033   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2034   // it's not really unused.
2035   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2036       VD->hasAttr<CleanupAttr>())
2037     return;
2038 
2039   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2040 
2041   if (Ty->isReferenceType() || Ty->isDependentType())
2042     return;
2043 
2044   if (const TagType *TT = Ty->getAs<TagType>()) {
2045     const TagDecl *Tag = TT->getDecl();
2046     if (Tag->hasAttr<UnusedAttr>())
2047       return;
2048     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2049     // mimic gcc's behavior.
2050     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2051       if (!RD->hasAttr<WarnUnusedAttr>())
2052         return;
2053     }
2054   }
2055 
2056   // Don't warn about __block Objective-C pointer variables, as they might
2057   // be assigned in the block but not used elsewhere for the purpose of lifetime
2058   // extension.
2059   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2060     return;
2061 
2062   // Don't warn about Objective-C pointer variables with precise lifetime
2063   // semantics; they can be used to ensure ARC releases the object at a known
2064   // time, which may mean assignment but no other references.
2065   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2066     return;
2067 
2068   auto iter = RefsMinusAssignments.find(VD);
2069   if (iter == RefsMinusAssignments.end())
2070     return;
2071 
2072   assert(iter->getSecond() >= 0 &&
2073          "Found a negative number of references to a VarDecl");
2074   if (iter->getSecond() != 0)
2075     return;
2076   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2077                                          : diag::warn_unused_but_set_variable;
2078   Diag(VD->getLocation(), DiagID) << VD;
2079 }
2080 
2081 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2082   // Verify that we have no forward references left.  If so, there was a goto
2083   // or address of a label taken, but no definition of it.  Label fwd
2084   // definitions are indicated with a null substmt which is also not a resolved
2085   // MS inline assembly label name.
2086   bool Diagnose = false;
2087   if (L->isMSAsmLabel())
2088     Diagnose = !L->isResolvedMSAsmLabel();
2089   else
2090     Diagnose = L->getStmt() == nullptr;
2091   if (Diagnose)
2092     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2093 }
2094 
2095 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2096   S->mergeNRVOIntoParent();
2097 
2098   if (S->decl_empty()) return;
2099   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2100          "Scope shouldn't contain decls!");
2101 
2102   for (auto *TmpD : S->decls()) {
2103     assert(TmpD && "This decl didn't get pushed??");
2104 
2105     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2106     NamedDecl *D = cast<NamedDecl>(TmpD);
2107 
2108     // Diagnose unused variables in this scope.
2109     if (!S->hasUnrecoverableErrorOccurred()) {
2110       DiagnoseUnusedDecl(D);
2111       if (const auto *RD = dyn_cast<RecordDecl>(D))
2112         DiagnoseUnusedNestedTypedefs(RD);
2113       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2114         DiagnoseUnusedButSetDecl(VD);
2115         RefsMinusAssignments.erase(VD);
2116       }
2117     }
2118 
2119     if (!D->getDeclName()) continue;
2120 
2121     // If this was a forward reference to a label, verify it was defined.
2122     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2123       CheckPoppedLabel(LD, *this);
2124 
2125     // Remove this name from our lexical scope, and warn on it if we haven't
2126     // already.
2127     IdResolver.RemoveDecl(D);
2128     auto ShadowI = ShadowingDecls.find(D);
2129     if (ShadowI != ShadowingDecls.end()) {
2130       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2131         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2132             << D << FD << FD->getParent();
2133         Diag(FD->getLocation(), diag::note_previous_declaration);
2134       }
2135       ShadowingDecls.erase(ShadowI);
2136     }
2137   }
2138 }
2139 
2140 /// Look for an Objective-C class in the translation unit.
2141 ///
2142 /// \param Id The name of the Objective-C class we're looking for. If
2143 /// typo-correction fixes this name, the Id will be updated
2144 /// to the fixed name.
2145 ///
2146 /// \param IdLoc The location of the name in the translation unit.
2147 ///
2148 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2149 /// if there is no class with the given name.
2150 ///
2151 /// \returns The declaration of the named Objective-C class, or NULL if the
2152 /// class could not be found.
2153 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2154                                               SourceLocation IdLoc,
2155                                               bool DoTypoCorrection) {
2156   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2157   // creation from this context.
2158   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2159 
2160   if (!IDecl && DoTypoCorrection) {
2161     // Perform typo correction at the given location, but only if we
2162     // find an Objective-C class name.
2163     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2164     if (TypoCorrection C =
2165             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2166                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2167       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2168       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2169       Id = IDecl->getIdentifier();
2170     }
2171   }
2172   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2173   // This routine must always return a class definition, if any.
2174   if (Def && Def->getDefinition())
2175       Def = Def->getDefinition();
2176   return Def;
2177 }
2178 
2179 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2180 /// from S, where a non-field would be declared. This routine copes
2181 /// with the difference between C and C++ scoping rules in structs and
2182 /// unions. For example, the following code is well-formed in C but
2183 /// ill-formed in C++:
2184 /// @code
2185 /// struct S6 {
2186 ///   enum { BAR } e;
2187 /// };
2188 ///
2189 /// void test_S6() {
2190 ///   struct S6 a;
2191 ///   a.e = BAR;
2192 /// }
2193 /// @endcode
2194 /// For the declaration of BAR, this routine will return a different
2195 /// scope. The scope S will be the scope of the unnamed enumeration
2196 /// within S6. In C++, this routine will return the scope associated
2197 /// with S6, because the enumeration's scope is a transparent
2198 /// context but structures can contain non-field names. In C, this
2199 /// routine will return the translation unit scope, since the
2200 /// enumeration's scope is a transparent context and structures cannot
2201 /// contain non-field names.
2202 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2203   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2204          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2205          (S->isClassScope() && !getLangOpts().CPlusPlus))
2206     S = S->getParent();
2207   return S;
2208 }
2209 
2210 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2211                                ASTContext::GetBuiltinTypeError Error) {
2212   switch (Error) {
2213   case ASTContext::GE_None:
2214     return "";
2215   case ASTContext::GE_Missing_type:
2216     return BuiltinInfo.getHeaderName(ID);
2217   case ASTContext::GE_Missing_stdio:
2218     return "stdio.h";
2219   case ASTContext::GE_Missing_setjmp:
2220     return "setjmp.h";
2221   case ASTContext::GE_Missing_ucontext:
2222     return "ucontext.h";
2223   }
2224   llvm_unreachable("unhandled error kind");
2225 }
2226 
2227 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2228                                   unsigned ID, SourceLocation Loc) {
2229   DeclContext *Parent = Context.getTranslationUnitDecl();
2230 
2231   if (getLangOpts().CPlusPlus) {
2232     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2233         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2234     CLinkageDecl->setImplicit();
2235     Parent->addDecl(CLinkageDecl);
2236     Parent = CLinkageDecl;
2237   }
2238 
2239   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2240                                            /*TInfo=*/nullptr, SC_Extern,
2241                                            getCurFPFeatures().isFPConstrained(),
2242                                            false, Type->isFunctionProtoType());
2243   New->setImplicit();
2244   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2245 
2246   // Create Decl objects for each parameter, adding them to the
2247   // FunctionDecl.
2248   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2249     SmallVector<ParmVarDecl *, 16> Params;
2250     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2251       ParmVarDecl *parm = ParmVarDecl::Create(
2252           Context, New, SourceLocation(), SourceLocation(), nullptr,
2253           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2254       parm->setScopeInfo(0, i);
2255       Params.push_back(parm);
2256     }
2257     New->setParams(Params);
2258   }
2259 
2260   AddKnownFunctionAttributes(New);
2261   return New;
2262 }
2263 
2264 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2265 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2266 /// if we're creating this built-in in anticipation of redeclaring the
2267 /// built-in.
2268 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2269                                      Scope *S, bool ForRedeclaration,
2270                                      SourceLocation Loc) {
2271   LookupNecessaryTypesForBuiltin(S, ID);
2272 
2273   ASTContext::GetBuiltinTypeError Error;
2274   QualType R = Context.GetBuiltinType(ID, Error);
2275   if (Error) {
2276     if (!ForRedeclaration)
2277       return nullptr;
2278 
2279     // If we have a builtin without an associated type we should not emit a
2280     // warning when we were not able to find a type for it.
2281     if (Error == ASTContext::GE_Missing_type ||
2282         Context.BuiltinInfo.allowTypeMismatch(ID))
2283       return nullptr;
2284 
2285     // If we could not find a type for setjmp it is because the jmp_buf type was
2286     // not defined prior to the setjmp declaration.
2287     if (Error == ASTContext::GE_Missing_setjmp) {
2288       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2289           << Context.BuiltinInfo.getName(ID);
2290       return nullptr;
2291     }
2292 
2293     // Generally, we emit a warning that the declaration requires the
2294     // appropriate header.
2295     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2296         << getHeaderName(Context.BuiltinInfo, ID, Error)
2297         << Context.BuiltinInfo.getName(ID);
2298     return nullptr;
2299   }
2300 
2301   if (!ForRedeclaration &&
2302       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2303        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2304     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2305                            : diag::ext_implicit_lib_function_decl)
2306         << Context.BuiltinInfo.getName(ID) << R;
2307     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2308       Diag(Loc, diag::note_include_header_or_declare)
2309           << Header << Context.BuiltinInfo.getName(ID);
2310   }
2311 
2312   if (R.isNull())
2313     return nullptr;
2314 
2315   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2316   RegisterLocallyScopedExternCDecl(New, S);
2317 
2318   // TUScope is the translation-unit scope to insert this function into.
2319   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2320   // relate Scopes to DeclContexts, and probably eliminate CurContext
2321   // entirely, but we're not there yet.
2322   DeclContext *SavedContext = CurContext;
2323   CurContext = New->getDeclContext();
2324   PushOnScopeChains(New, TUScope);
2325   CurContext = SavedContext;
2326   return New;
2327 }
2328 
2329 /// Typedef declarations don't have linkage, but they still denote the same
2330 /// entity if their types are the same.
2331 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2332 /// isSameEntity.
2333 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2334                                                      TypedefNameDecl *Decl,
2335                                                      LookupResult &Previous) {
2336   // This is only interesting when modules are enabled.
2337   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2338     return;
2339 
2340   // Empty sets are uninteresting.
2341   if (Previous.empty())
2342     return;
2343 
2344   LookupResult::Filter Filter = Previous.makeFilter();
2345   while (Filter.hasNext()) {
2346     NamedDecl *Old = Filter.next();
2347 
2348     // Non-hidden declarations are never ignored.
2349     if (S.isVisible(Old))
2350       continue;
2351 
2352     // Declarations of the same entity are not ignored, even if they have
2353     // different linkages.
2354     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2355       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2356                                 Decl->getUnderlyingType()))
2357         continue;
2358 
2359       // If both declarations give a tag declaration a typedef name for linkage
2360       // purposes, then they declare the same entity.
2361       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2362           Decl->getAnonDeclWithTypedefName())
2363         continue;
2364     }
2365 
2366     Filter.erase();
2367   }
2368 
2369   Filter.done();
2370 }
2371 
2372 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2373   QualType OldType;
2374   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2375     OldType = OldTypedef->getUnderlyingType();
2376   else
2377     OldType = Context.getTypeDeclType(Old);
2378   QualType NewType = New->getUnderlyingType();
2379 
2380   if (NewType->isVariablyModifiedType()) {
2381     // Must not redefine a typedef with a variably-modified type.
2382     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2383     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2384       << Kind << NewType;
2385     if (Old->getLocation().isValid())
2386       notePreviousDefinition(Old, New->getLocation());
2387     New->setInvalidDecl();
2388     return true;
2389   }
2390 
2391   if (OldType != NewType &&
2392       !OldType->isDependentType() &&
2393       !NewType->isDependentType() &&
2394       !Context.hasSameType(OldType, NewType)) {
2395     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2396     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2397       << Kind << NewType << OldType;
2398     if (Old->getLocation().isValid())
2399       notePreviousDefinition(Old, New->getLocation());
2400     New->setInvalidDecl();
2401     return true;
2402   }
2403   return false;
2404 }
2405 
2406 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2407 /// same name and scope as a previous declaration 'Old'.  Figure out
2408 /// how to resolve this situation, merging decls or emitting
2409 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2410 ///
2411 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2412                                 LookupResult &OldDecls) {
2413   // If the new decl is known invalid already, don't bother doing any
2414   // merging checks.
2415   if (New->isInvalidDecl()) return;
2416 
2417   // Allow multiple definitions for ObjC built-in typedefs.
2418   // FIXME: Verify the underlying types are equivalent!
2419   if (getLangOpts().ObjC) {
2420     const IdentifierInfo *TypeID = New->getIdentifier();
2421     switch (TypeID->getLength()) {
2422     default: break;
2423     case 2:
2424       {
2425         if (!TypeID->isStr("id"))
2426           break;
2427         QualType T = New->getUnderlyingType();
2428         if (!T->isPointerType())
2429           break;
2430         if (!T->isVoidPointerType()) {
2431           QualType PT = T->castAs<PointerType>()->getPointeeType();
2432           if (!PT->isStructureType())
2433             break;
2434         }
2435         Context.setObjCIdRedefinitionType(T);
2436         // Install the built-in type for 'id', ignoring the current definition.
2437         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2438         return;
2439       }
2440     case 5:
2441       if (!TypeID->isStr("Class"))
2442         break;
2443       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2444       // Install the built-in type for 'Class', ignoring the current definition.
2445       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2446       return;
2447     case 3:
2448       if (!TypeID->isStr("SEL"))
2449         break;
2450       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2451       // Install the built-in type for 'SEL', ignoring the current definition.
2452       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2453       return;
2454     }
2455     // Fall through - the typedef name was not a builtin type.
2456   }
2457 
2458   // Verify the old decl was also a type.
2459   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2460   if (!Old) {
2461     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2462       << New->getDeclName();
2463 
2464     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2465     if (OldD->getLocation().isValid())
2466       notePreviousDefinition(OldD, New->getLocation());
2467 
2468     return New->setInvalidDecl();
2469   }
2470 
2471   // If the old declaration is invalid, just give up here.
2472   if (Old->isInvalidDecl())
2473     return New->setInvalidDecl();
2474 
2475   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2476     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2477     auto *NewTag = New->getAnonDeclWithTypedefName();
2478     NamedDecl *Hidden = nullptr;
2479     if (OldTag && NewTag &&
2480         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2481         !hasVisibleDefinition(OldTag, &Hidden)) {
2482       // There is a definition of this tag, but it is not visible. Use it
2483       // instead of our tag.
2484       New->setTypeForDecl(OldTD->getTypeForDecl());
2485       if (OldTD->isModed())
2486         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2487                                     OldTD->getUnderlyingType());
2488       else
2489         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2490 
2491       // Make the old tag definition visible.
2492       makeMergedDefinitionVisible(Hidden);
2493 
2494       // If this was an unscoped enumeration, yank all of its enumerators
2495       // out of the scope.
2496       if (isa<EnumDecl>(NewTag)) {
2497         Scope *EnumScope = getNonFieldDeclScope(S);
2498         for (auto *D : NewTag->decls()) {
2499           auto *ED = cast<EnumConstantDecl>(D);
2500           assert(EnumScope->isDeclScope(ED));
2501           EnumScope->RemoveDecl(ED);
2502           IdResolver.RemoveDecl(ED);
2503           ED->getLexicalDeclContext()->removeDecl(ED);
2504         }
2505       }
2506     }
2507   }
2508 
2509   // If the typedef types are not identical, reject them in all languages and
2510   // with any extensions enabled.
2511   if (isIncompatibleTypedef(Old, New))
2512     return;
2513 
2514   // The types match.  Link up the redeclaration chain and merge attributes if
2515   // the old declaration was a typedef.
2516   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2517     New->setPreviousDecl(Typedef);
2518     mergeDeclAttributes(New, Old);
2519   }
2520 
2521   if (getLangOpts().MicrosoftExt)
2522     return;
2523 
2524   if (getLangOpts().CPlusPlus) {
2525     // C++ [dcl.typedef]p2:
2526     //   In a given non-class scope, a typedef specifier can be used to
2527     //   redefine the name of any type declared in that scope to refer
2528     //   to the type to which it already refers.
2529     if (!isa<CXXRecordDecl>(CurContext))
2530       return;
2531 
2532     // C++0x [dcl.typedef]p4:
2533     //   In a given class scope, a typedef specifier can be used to redefine
2534     //   any class-name declared in that scope that is not also a typedef-name
2535     //   to refer to the type to which it already refers.
2536     //
2537     // This wording came in via DR424, which was a correction to the
2538     // wording in DR56, which accidentally banned code like:
2539     //
2540     //   struct S {
2541     //     typedef struct A { } A;
2542     //   };
2543     //
2544     // in the C++03 standard. We implement the C++0x semantics, which
2545     // allow the above but disallow
2546     //
2547     //   struct S {
2548     //     typedef int I;
2549     //     typedef int I;
2550     //   };
2551     //
2552     // since that was the intent of DR56.
2553     if (!isa<TypedefNameDecl>(Old))
2554       return;
2555 
2556     Diag(New->getLocation(), diag::err_redefinition)
2557       << New->getDeclName();
2558     notePreviousDefinition(Old, New->getLocation());
2559     return New->setInvalidDecl();
2560   }
2561 
2562   // Modules always permit redefinition of typedefs, as does C11.
2563   if (getLangOpts().Modules || getLangOpts().C11)
2564     return;
2565 
2566   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2567   // is normally mapped to an error, but can be controlled with
2568   // -Wtypedef-redefinition.  If either the original or the redefinition is
2569   // in a system header, don't emit this for compatibility with GCC.
2570   if (getDiagnostics().getSuppressSystemWarnings() &&
2571       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2572       (Old->isImplicit() ||
2573        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2574        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2575     return;
2576 
2577   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2578     << New->getDeclName();
2579   notePreviousDefinition(Old, New->getLocation());
2580 }
2581 
2582 /// DeclhasAttr - returns true if decl Declaration already has the target
2583 /// attribute.
2584 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2585   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2586   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2587   for (const auto *i : D->attrs())
2588     if (i->getKind() == A->getKind()) {
2589       if (Ann) {
2590         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2591           return true;
2592         continue;
2593       }
2594       // FIXME: Don't hardcode this check
2595       if (OA && isa<OwnershipAttr>(i))
2596         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2597       return true;
2598     }
2599 
2600   return false;
2601 }
2602 
2603 static bool isAttributeTargetADefinition(Decl *D) {
2604   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2605     return VD->isThisDeclarationADefinition();
2606   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2607     return TD->isCompleteDefinition() || TD->isBeingDefined();
2608   return true;
2609 }
2610 
2611 /// Merge alignment attributes from \p Old to \p New, taking into account the
2612 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2613 ///
2614 /// \return \c true if any attributes were added to \p New.
2615 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2616   // Look for alignas attributes on Old, and pick out whichever attribute
2617   // specifies the strictest alignment requirement.
2618   AlignedAttr *OldAlignasAttr = nullptr;
2619   AlignedAttr *OldStrictestAlignAttr = nullptr;
2620   unsigned OldAlign = 0;
2621   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2622     // FIXME: We have no way of representing inherited dependent alignments
2623     // in a case like:
2624     //   template<int A, int B> struct alignas(A) X;
2625     //   template<int A, int B> struct alignas(B) X {};
2626     // For now, we just ignore any alignas attributes which are not on the
2627     // definition in such a case.
2628     if (I->isAlignmentDependent())
2629       return false;
2630 
2631     if (I->isAlignas())
2632       OldAlignasAttr = I;
2633 
2634     unsigned Align = I->getAlignment(S.Context);
2635     if (Align > OldAlign) {
2636       OldAlign = Align;
2637       OldStrictestAlignAttr = I;
2638     }
2639   }
2640 
2641   // Look for alignas attributes on New.
2642   AlignedAttr *NewAlignasAttr = nullptr;
2643   unsigned NewAlign = 0;
2644   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2645     if (I->isAlignmentDependent())
2646       return false;
2647 
2648     if (I->isAlignas())
2649       NewAlignasAttr = I;
2650 
2651     unsigned Align = I->getAlignment(S.Context);
2652     if (Align > NewAlign)
2653       NewAlign = Align;
2654   }
2655 
2656   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2657     // Both declarations have 'alignas' attributes. We require them to match.
2658     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2659     // fall short. (If two declarations both have alignas, they must both match
2660     // every definition, and so must match each other if there is a definition.)
2661 
2662     // If either declaration only contains 'alignas(0)' specifiers, then it
2663     // specifies the natural alignment for the type.
2664     if (OldAlign == 0 || NewAlign == 0) {
2665       QualType Ty;
2666       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2667         Ty = VD->getType();
2668       else
2669         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2670 
2671       if (OldAlign == 0)
2672         OldAlign = S.Context.getTypeAlign(Ty);
2673       if (NewAlign == 0)
2674         NewAlign = S.Context.getTypeAlign(Ty);
2675     }
2676 
2677     if (OldAlign != NewAlign) {
2678       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2679         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2680         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2681       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2682     }
2683   }
2684 
2685   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2686     // C++11 [dcl.align]p6:
2687     //   if any declaration of an entity has an alignment-specifier,
2688     //   every defining declaration of that entity shall specify an
2689     //   equivalent alignment.
2690     // C11 6.7.5/7:
2691     //   If the definition of an object does not have an alignment
2692     //   specifier, any other declaration of that object shall also
2693     //   have no alignment specifier.
2694     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2695       << OldAlignasAttr;
2696     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2697       << OldAlignasAttr;
2698   }
2699 
2700   bool AnyAdded = false;
2701 
2702   // Ensure we have an attribute representing the strictest alignment.
2703   if (OldAlign > NewAlign) {
2704     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2705     Clone->setInherited(true);
2706     New->addAttr(Clone);
2707     AnyAdded = true;
2708   }
2709 
2710   // Ensure we have an alignas attribute if the old declaration had one.
2711   if (OldAlignasAttr && !NewAlignasAttr &&
2712       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2713     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2714     Clone->setInherited(true);
2715     New->addAttr(Clone);
2716     AnyAdded = true;
2717   }
2718 
2719   return AnyAdded;
2720 }
2721 
2722 #define WANT_DECL_MERGE_LOGIC
2723 #include "clang/Sema/AttrParsedAttrImpl.inc"
2724 #undef WANT_DECL_MERGE_LOGIC
2725 
2726 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2727                                const InheritableAttr *Attr,
2728                                Sema::AvailabilityMergeKind AMK) {
2729   // Diagnose any mutual exclusions between the attribute that we want to add
2730   // and attributes that already exist on the declaration.
2731   if (!DiagnoseMutualExclusions(S, D, Attr))
2732     return false;
2733 
2734   // This function copies an attribute Attr from a previous declaration to the
2735   // new declaration D if the new declaration doesn't itself have that attribute
2736   // yet or if that attribute allows duplicates.
2737   // If you're adding a new attribute that requires logic different from
2738   // "use explicit attribute on decl if present, else use attribute from
2739   // previous decl", for example if the attribute needs to be consistent
2740   // between redeclarations, you need to call a custom merge function here.
2741   InheritableAttr *NewAttr = nullptr;
2742   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2743     NewAttr = S.mergeAvailabilityAttr(
2744         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2745         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2746         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2747         AA->getPriority());
2748   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2749     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2750   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2751     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2752   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2753     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2754   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2755     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2756   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2757     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2758   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2759     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2760                                 FA->getFirstArg());
2761   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2762     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2763   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2764     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2765   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2766     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2767                                        IA->getInheritanceModel());
2768   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2769     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2770                                       &S.Context.Idents.get(AA->getSpelling()));
2771   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2772            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2773             isa<CUDAGlobalAttr>(Attr))) {
2774     // CUDA target attributes are part of function signature for
2775     // overloading purposes and must not be merged.
2776     return false;
2777   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2778     NewAttr = S.mergeMinSizeAttr(D, *MA);
2779   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2780     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2781   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2782     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2783   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2784     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2785   else if (isa<AlignedAttr>(Attr))
2786     // AlignedAttrs are handled separately, because we need to handle all
2787     // such attributes on a declaration at the same time.
2788     NewAttr = nullptr;
2789   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2790            (AMK == Sema::AMK_Override ||
2791             AMK == Sema::AMK_ProtocolImplementation ||
2792             AMK == Sema::AMK_OptionalProtocolImplementation))
2793     NewAttr = nullptr;
2794   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2795     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2796   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2797     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2798   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2799     NewAttr = S.mergeImportNameAttr(D, *INA);
2800   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2801     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2802   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2803     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2804   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2805     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2806   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2807     NewAttr =
2808         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2809   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2810     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2811   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2812     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2813 
2814   if (NewAttr) {
2815     NewAttr->setInherited(true);
2816     D->addAttr(NewAttr);
2817     if (isa<MSInheritanceAttr>(NewAttr))
2818       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2819     return true;
2820   }
2821 
2822   return false;
2823 }
2824 
2825 static const NamedDecl *getDefinition(const Decl *D) {
2826   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2827     return TD->getDefinition();
2828   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2829     const VarDecl *Def = VD->getDefinition();
2830     if (Def)
2831       return Def;
2832     return VD->getActingDefinition();
2833   }
2834   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2835     const FunctionDecl *Def = nullptr;
2836     if (FD->isDefined(Def, true))
2837       return Def;
2838   }
2839   return nullptr;
2840 }
2841 
2842 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2843   for (const auto *Attribute : D->attrs())
2844     if (Attribute->getKind() == Kind)
2845       return true;
2846   return false;
2847 }
2848 
2849 /// checkNewAttributesAfterDef - If we already have a definition, check that
2850 /// there are no new attributes in this declaration.
2851 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2852   if (!New->hasAttrs())
2853     return;
2854 
2855   const NamedDecl *Def = getDefinition(Old);
2856   if (!Def || Def == New)
2857     return;
2858 
2859   AttrVec &NewAttributes = New->getAttrs();
2860   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2861     const Attr *NewAttribute = NewAttributes[I];
2862 
2863     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2864       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2865         Sema::SkipBodyInfo SkipBody;
2866         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2867 
2868         // If we're skipping this definition, drop the "alias" attribute.
2869         if (SkipBody.ShouldSkip) {
2870           NewAttributes.erase(NewAttributes.begin() + I);
2871           --E;
2872           continue;
2873         }
2874       } else {
2875         VarDecl *VD = cast<VarDecl>(New);
2876         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2877                                 VarDecl::TentativeDefinition
2878                             ? diag::err_alias_after_tentative
2879                             : diag::err_redefinition;
2880         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2881         if (Diag == diag::err_redefinition)
2882           S.notePreviousDefinition(Def, VD->getLocation());
2883         else
2884           S.Diag(Def->getLocation(), diag::note_previous_definition);
2885         VD->setInvalidDecl();
2886       }
2887       ++I;
2888       continue;
2889     }
2890 
2891     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2892       // Tentative definitions are only interesting for the alias check above.
2893       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2894         ++I;
2895         continue;
2896       }
2897     }
2898 
2899     if (hasAttribute(Def, NewAttribute->getKind())) {
2900       ++I;
2901       continue; // regular attr merging will take care of validating this.
2902     }
2903 
2904     if (isa<C11NoReturnAttr>(NewAttribute)) {
2905       // C's _Noreturn is allowed to be added to a function after it is defined.
2906       ++I;
2907       continue;
2908     } else if (isa<UuidAttr>(NewAttribute)) {
2909       // msvc will allow a subsequent definition to add an uuid to a class
2910       ++I;
2911       continue;
2912     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2913       if (AA->isAlignas()) {
2914         // C++11 [dcl.align]p6:
2915         //   if any declaration of an entity has an alignment-specifier,
2916         //   every defining declaration of that entity shall specify an
2917         //   equivalent alignment.
2918         // C11 6.7.5/7:
2919         //   If the definition of an object does not have an alignment
2920         //   specifier, any other declaration of that object shall also
2921         //   have no alignment specifier.
2922         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2923           << AA;
2924         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2925           << AA;
2926         NewAttributes.erase(NewAttributes.begin() + I);
2927         --E;
2928         continue;
2929       }
2930     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2931       // If there is a C definition followed by a redeclaration with this
2932       // attribute then there are two different definitions. In C++, prefer the
2933       // standard diagnostics.
2934       if (!S.getLangOpts().CPlusPlus) {
2935         S.Diag(NewAttribute->getLocation(),
2936                diag::err_loader_uninitialized_redeclaration);
2937         S.Diag(Def->getLocation(), diag::note_previous_definition);
2938         NewAttributes.erase(NewAttributes.begin() + I);
2939         --E;
2940         continue;
2941       }
2942     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2943                cast<VarDecl>(New)->isInline() &&
2944                !cast<VarDecl>(New)->isInlineSpecified()) {
2945       // Don't warn about applying selectany to implicitly inline variables.
2946       // Older compilers and language modes would require the use of selectany
2947       // to make such variables inline, and it would have no effect if we
2948       // honored it.
2949       ++I;
2950       continue;
2951     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2952       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2953       // declarations after defintions.
2954       ++I;
2955       continue;
2956     }
2957 
2958     S.Diag(NewAttribute->getLocation(),
2959            diag::warn_attribute_precede_definition);
2960     S.Diag(Def->getLocation(), diag::note_previous_definition);
2961     NewAttributes.erase(NewAttributes.begin() + I);
2962     --E;
2963   }
2964 }
2965 
2966 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2967                                      const ConstInitAttr *CIAttr,
2968                                      bool AttrBeforeInit) {
2969   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2970 
2971   // Figure out a good way to write this specifier on the old declaration.
2972   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2973   // enough of the attribute list spelling information to extract that without
2974   // heroics.
2975   std::string SuitableSpelling;
2976   if (S.getLangOpts().CPlusPlus20)
2977     SuitableSpelling = std::string(
2978         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2979   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2980     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2981         InsertLoc, {tok::l_square, tok::l_square,
2982                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2983                     S.PP.getIdentifierInfo("require_constant_initialization"),
2984                     tok::r_square, tok::r_square}));
2985   if (SuitableSpelling.empty())
2986     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2987         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2988                     S.PP.getIdentifierInfo("require_constant_initialization"),
2989                     tok::r_paren, tok::r_paren}));
2990   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2991     SuitableSpelling = "constinit";
2992   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2993     SuitableSpelling = "[[clang::require_constant_initialization]]";
2994   if (SuitableSpelling.empty())
2995     SuitableSpelling = "__attribute__((require_constant_initialization))";
2996   SuitableSpelling += " ";
2997 
2998   if (AttrBeforeInit) {
2999     // extern constinit int a;
3000     // int a = 0; // error (missing 'constinit'), accepted as extension
3001     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3002     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3003         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3004     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3005   } else {
3006     // int a = 0;
3007     // constinit extern int a; // error (missing 'constinit')
3008     S.Diag(CIAttr->getLocation(),
3009            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3010                                  : diag::warn_require_const_init_added_too_late)
3011         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3012     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3013         << CIAttr->isConstinit()
3014         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3015   }
3016 }
3017 
3018 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3019 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3020                                AvailabilityMergeKind AMK) {
3021   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3022     UsedAttr *NewAttr = OldAttr->clone(Context);
3023     NewAttr->setInherited(true);
3024     New->addAttr(NewAttr);
3025   }
3026   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3027     RetainAttr *NewAttr = OldAttr->clone(Context);
3028     NewAttr->setInherited(true);
3029     New->addAttr(NewAttr);
3030   }
3031 
3032   if (!Old->hasAttrs() && !New->hasAttrs())
3033     return;
3034 
3035   // [dcl.constinit]p1:
3036   //   If the [constinit] specifier is applied to any declaration of a
3037   //   variable, it shall be applied to the initializing declaration.
3038   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3039   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3040   if (bool(OldConstInit) != bool(NewConstInit)) {
3041     const auto *OldVD = cast<VarDecl>(Old);
3042     auto *NewVD = cast<VarDecl>(New);
3043 
3044     // Find the initializing declaration. Note that we might not have linked
3045     // the new declaration into the redeclaration chain yet.
3046     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3047     if (!InitDecl &&
3048         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3049       InitDecl = NewVD;
3050 
3051     if (InitDecl == NewVD) {
3052       // This is the initializing declaration. If it would inherit 'constinit',
3053       // that's ill-formed. (Note that we do not apply this to the attribute
3054       // form).
3055       if (OldConstInit && OldConstInit->isConstinit())
3056         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3057                                  /*AttrBeforeInit=*/true);
3058     } else if (NewConstInit) {
3059       // This is the first time we've been told that this declaration should
3060       // have a constant initializer. If we already saw the initializing
3061       // declaration, this is too late.
3062       if (InitDecl && InitDecl != NewVD) {
3063         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3064                                  /*AttrBeforeInit=*/false);
3065         NewVD->dropAttr<ConstInitAttr>();
3066       }
3067     }
3068   }
3069 
3070   // Attributes declared post-definition are currently ignored.
3071   checkNewAttributesAfterDef(*this, New, Old);
3072 
3073   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3074     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3075       if (!OldA->isEquivalent(NewA)) {
3076         // This redeclaration changes __asm__ label.
3077         Diag(New->getLocation(), diag::err_different_asm_label);
3078         Diag(OldA->getLocation(), diag::note_previous_declaration);
3079       }
3080     } else if (Old->isUsed()) {
3081       // This redeclaration adds an __asm__ label to a declaration that has
3082       // already been ODR-used.
3083       Diag(New->getLocation(), diag::err_late_asm_label_name)
3084         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3085     }
3086   }
3087 
3088   // Re-declaration cannot add abi_tag's.
3089   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3090     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3091       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3092         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3093           Diag(NewAbiTagAttr->getLocation(),
3094                diag::err_new_abi_tag_on_redeclaration)
3095               << NewTag;
3096           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3097         }
3098       }
3099     } else {
3100       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3101       Diag(Old->getLocation(), diag::note_previous_declaration);
3102     }
3103   }
3104 
3105   // This redeclaration adds a section attribute.
3106   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3107     if (auto *VD = dyn_cast<VarDecl>(New)) {
3108       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3109         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3110         Diag(Old->getLocation(), diag::note_previous_declaration);
3111       }
3112     }
3113   }
3114 
3115   // Redeclaration adds code-seg attribute.
3116   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3117   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3118       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3119     Diag(New->getLocation(), diag::warn_mismatched_section)
3120          << 0 /*codeseg*/;
3121     Diag(Old->getLocation(), diag::note_previous_declaration);
3122   }
3123 
3124   if (!Old->hasAttrs())
3125     return;
3126 
3127   bool foundAny = New->hasAttrs();
3128 
3129   // Ensure that any moving of objects within the allocated map is done before
3130   // we process them.
3131   if (!foundAny) New->setAttrs(AttrVec());
3132 
3133   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3134     // Ignore deprecated/unavailable/availability attributes if requested.
3135     AvailabilityMergeKind LocalAMK = AMK_None;
3136     if (isa<DeprecatedAttr>(I) ||
3137         isa<UnavailableAttr>(I) ||
3138         isa<AvailabilityAttr>(I)) {
3139       switch (AMK) {
3140       case AMK_None:
3141         continue;
3142 
3143       case AMK_Redeclaration:
3144       case AMK_Override:
3145       case AMK_ProtocolImplementation:
3146       case AMK_OptionalProtocolImplementation:
3147         LocalAMK = AMK;
3148         break;
3149       }
3150     }
3151 
3152     // Already handled.
3153     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3154       continue;
3155 
3156     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3157       foundAny = true;
3158   }
3159 
3160   if (mergeAlignedAttrs(*this, New, Old))
3161     foundAny = true;
3162 
3163   if (!foundAny) New->dropAttrs();
3164 }
3165 
3166 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3167 /// to the new one.
3168 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3169                                      const ParmVarDecl *oldDecl,
3170                                      Sema &S) {
3171   // C++11 [dcl.attr.depend]p2:
3172   //   The first declaration of a function shall specify the
3173   //   carries_dependency attribute for its declarator-id if any declaration
3174   //   of the function specifies the carries_dependency attribute.
3175   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3176   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3177     S.Diag(CDA->getLocation(),
3178            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3179     // Find the first declaration of the parameter.
3180     // FIXME: Should we build redeclaration chains for function parameters?
3181     const FunctionDecl *FirstFD =
3182       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3183     const ParmVarDecl *FirstVD =
3184       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3185     S.Diag(FirstVD->getLocation(),
3186            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3187   }
3188 
3189   if (!oldDecl->hasAttrs())
3190     return;
3191 
3192   bool foundAny = newDecl->hasAttrs();
3193 
3194   // Ensure that any moving of objects within the allocated map is
3195   // done before we process them.
3196   if (!foundAny) newDecl->setAttrs(AttrVec());
3197 
3198   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3199     if (!DeclHasAttr(newDecl, I)) {
3200       InheritableAttr *newAttr =
3201         cast<InheritableParamAttr>(I->clone(S.Context));
3202       newAttr->setInherited(true);
3203       newDecl->addAttr(newAttr);
3204       foundAny = true;
3205     }
3206   }
3207 
3208   if (!foundAny) newDecl->dropAttrs();
3209 }
3210 
3211 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3212                                 const ParmVarDecl *OldParam,
3213                                 Sema &S) {
3214   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3215     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3216       if (*Oldnullability != *Newnullability) {
3217         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3218           << DiagNullabilityKind(
3219                *Newnullability,
3220                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3221                 != 0))
3222           << DiagNullabilityKind(
3223                *Oldnullability,
3224                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3225                 != 0));
3226         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3227       }
3228     } else {
3229       QualType NewT = NewParam->getType();
3230       NewT = S.Context.getAttributedType(
3231                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3232                          NewT, NewT);
3233       NewParam->setType(NewT);
3234     }
3235   }
3236 }
3237 
3238 namespace {
3239 
3240 /// Used in MergeFunctionDecl to keep track of function parameters in
3241 /// C.
3242 struct GNUCompatibleParamWarning {
3243   ParmVarDecl *OldParm;
3244   ParmVarDecl *NewParm;
3245   QualType PromotedType;
3246 };
3247 
3248 } // end anonymous namespace
3249 
3250 // Determine whether the previous declaration was a definition, implicit
3251 // declaration, or a declaration.
3252 template <typename T>
3253 static std::pair<diag::kind, SourceLocation>
3254 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3255   diag::kind PrevDiag;
3256   SourceLocation OldLocation = Old->getLocation();
3257   if (Old->isThisDeclarationADefinition())
3258     PrevDiag = diag::note_previous_definition;
3259   else if (Old->isImplicit()) {
3260     PrevDiag = diag::note_previous_implicit_declaration;
3261     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3262       if (FD->getBuiltinID())
3263         PrevDiag = diag::note_previous_builtin_declaration;
3264     }
3265     if (OldLocation.isInvalid())
3266       OldLocation = New->getLocation();
3267   } else
3268     PrevDiag = diag::note_previous_declaration;
3269   return std::make_pair(PrevDiag, OldLocation);
3270 }
3271 
3272 /// canRedefineFunction - checks if a function can be redefined. Currently,
3273 /// only extern inline functions can be redefined, and even then only in
3274 /// GNU89 mode.
3275 static bool canRedefineFunction(const FunctionDecl *FD,
3276                                 const LangOptions& LangOpts) {
3277   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3278           !LangOpts.CPlusPlus &&
3279           FD->isInlineSpecified() &&
3280           FD->getStorageClass() == SC_Extern);
3281 }
3282 
3283 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3284   const AttributedType *AT = T->getAs<AttributedType>();
3285   while (AT && !AT->isCallingConv())
3286     AT = AT->getModifiedType()->getAs<AttributedType>();
3287   return AT;
3288 }
3289 
3290 template <typename T>
3291 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3292   const DeclContext *DC = Old->getDeclContext();
3293   if (DC->isRecord())
3294     return false;
3295 
3296   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3297   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3298     return true;
3299   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3300     return true;
3301   return false;
3302 }
3303 
3304 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3305 static bool isExternC(VarTemplateDecl *) { return false; }
3306 static bool isExternC(FunctionTemplateDecl *) { return false; }
3307 
3308 /// Check whether a redeclaration of an entity introduced by a
3309 /// using-declaration is valid, given that we know it's not an overload
3310 /// (nor a hidden tag declaration).
3311 template<typename ExpectedDecl>
3312 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3313                                    ExpectedDecl *New) {
3314   // C++11 [basic.scope.declarative]p4:
3315   //   Given a set of declarations in a single declarative region, each of
3316   //   which specifies the same unqualified name,
3317   //   -- they shall all refer to the same entity, or all refer to functions
3318   //      and function templates; or
3319   //   -- exactly one declaration shall declare a class name or enumeration
3320   //      name that is not a typedef name and the other declarations shall all
3321   //      refer to the same variable or enumerator, or all refer to functions
3322   //      and function templates; in this case the class name or enumeration
3323   //      name is hidden (3.3.10).
3324 
3325   // C++11 [namespace.udecl]p14:
3326   //   If a function declaration in namespace scope or block scope has the
3327   //   same name and the same parameter-type-list as a function introduced
3328   //   by a using-declaration, and the declarations do not declare the same
3329   //   function, the program is ill-formed.
3330 
3331   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3332   if (Old &&
3333       !Old->getDeclContext()->getRedeclContext()->Equals(
3334           New->getDeclContext()->getRedeclContext()) &&
3335       !(isExternC(Old) && isExternC(New)))
3336     Old = nullptr;
3337 
3338   if (!Old) {
3339     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3340     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3341     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3342     return true;
3343   }
3344   return false;
3345 }
3346 
3347 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3348                                             const FunctionDecl *B) {
3349   assert(A->getNumParams() == B->getNumParams());
3350 
3351   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3352     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3353     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3354     if (AttrA == AttrB)
3355       return true;
3356     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3357            AttrA->isDynamic() == AttrB->isDynamic();
3358   };
3359 
3360   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3361 }
3362 
3363 /// If necessary, adjust the semantic declaration context for a qualified
3364 /// declaration to name the correct inline namespace within the qualifier.
3365 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3366                                                DeclaratorDecl *OldD) {
3367   // The only case where we need to update the DeclContext is when
3368   // redeclaration lookup for a qualified name finds a declaration
3369   // in an inline namespace within the context named by the qualifier:
3370   //
3371   //   inline namespace N { int f(); }
3372   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3373   //
3374   // For unqualified declarations, the semantic context *can* change
3375   // along the redeclaration chain (for local extern declarations,
3376   // extern "C" declarations, and friend declarations in particular).
3377   if (!NewD->getQualifier())
3378     return;
3379 
3380   // NewD is probably already in the right context.
3381   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3382   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3383   if (NamedDC->Equals(SemaDC))
3384     return;
3385 
3386   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3387           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3388          "unexpected context for redeclaration");
3389 
3390   auto *LexDC = NewD->getLexicalDeclContext();
3391   auto FixSemaDC = [=](NamedDecl *D) {
3392     if (!D)
3393       return;
3394     D->setDeclContext(SemaDC);
3395     D->setLexicalDeclContext(LexDC);
3396   };
3397 
3398   FixSemaDC(NewD);
3399   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3400     FixSemaDC(FD->getDescribedFunctionTemplate());
3401   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3402     FixSemaDC(VD->getDescribedVarTemplate());
3403 }
3404 
3405 /// MergeFunctionDecl - We just parsed a function 'New' from
3406 /// declarator D which has the same name and scope as a previous
3407 /// declaration 'Old'.  Figure out how to resolve this situation,
3408 /// merging decls or emitting diagnostics as appropriate.
3409 ///
3410 /// In C++, New and Old must be declarations that are not
3411 /// overloaded. Use IsOverload to determine whether New and Old are
3412 /// overloaded, and to select the Old declaration that New should be
3413 /// merged with.
3414 ///
3415 /// Returns true if there was an error, false otherwise.
3416 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3417                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3418   // Verify the old decl was also a function.
3419   FunctionDecl *Old = OldD->getAsFunction();
3420   if (!Old) {
3421     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3422       if (New->getFriendObjectKind()) {
3423         Diag(New->getLocation(), diag::err_using_decl_friend);
3424         Diag(Shadow->getTargetDecl()->getLocation(),
3425              diag::note_using_decl_target);
3426         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3427             << 0;
3428         return true;
3429       }
3430 
3431       // Check whether the two declarations might declare the same function or
3432       // function template.
3433       if (FunctionTemplateDecl *NewTemplate =
3434               New->getDescribedFunctionTemplate()) {
3435         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3436                                                          NewTemplate))
3437           return true;
3438         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3439                          ->getAsFunction();
3440       } else {
3441         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3442           return true;
3443         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3444       }
3445     } else {
3446       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3447         << New->getDeclName();
3448       notePreviousDefinition(OldD, New->getLocation());
3449       return true;
3450     }
3451   }
3452 
3453   // If the old declaration was found in an inline namespace and the new
3454   // declaration was qualified, update the DeclContext to match.
3455   adjustDeclContextForDeclaratorDecl(New, Old);
3456 
3457   // If the old declaration is invalid, just give up here.
3458   if (Old->isInvalidDecl())
3459     return true;
3460 
3461   // Disallow redeclaration of some builtins.
3462   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3463     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3464     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3465         << Old << Old->getType();
3466     return true;
3467   }
3468 
3469   diag::kind PrevDiag;
3470   SourceLocation OldLocation;
3471   std::tie(PrevDiag, OldLocation) =
3472       getNoteDiagForInvalidRedeclaration(Old, New);
3473 
3474   // Don't complain about this if we're in GNU89 mode and the old function
3475   // is an extern inline function.
3476   // Don't complain about specializations. They are not supposed to have
3477   // storage classes.
3478   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3479       New->getStorageClass() == SC_Static &&
3480       Old->hasExternalFormalLinkage() &&
3481       !New->getTemplateSpecializationInfo() &&
3482       !canRedefineFunction(Old, getLangOpts())) {
3483     if (getLangOpts().MicrosoftExt) {
3484       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3485       Diag(OldLocation, PrevDiag);
3486     } else {
3487       Diag(New->getLocation(), diag::err_static_non_static) << New;
3488       Diag(OldLocation, PrevDiag);
3489       return true;
3490     }
3491   }
3492 
3493   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3494     if (!Old->hasAttr<InternalLinkageAttr>()) {
3495       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3496           << ILA;
3497       Diag(Old->getLocation(), diag::note_previous_declaration);
3498       New->dropAttr<InternalLinkageAttr>();
3499     }
3500 
3501   if (auto *EA = New->getAttr<ErrorAttr>()) {
3502     if (!Old->hasAttr<ErrorAttr>()) {
3503       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3504       Diag(Old->getLocation(), diag::note_previous_declaration);
3505       New->dropAttr<ErrorAttr>();
3506     }
3507   }
3508 
3509   if (CheckRedeclarationInModule(New, Old))
3510     return true;
3511 
3512   if (!getLangOpts().CPlusPlus) {
3513     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3514     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3515       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3516         << New << OldOvl;
3517 
3518       // Try our best to find a decl that actually has the overloadable
3519       // attribute for the note. In most cases (e.g. programs with only one
3520       // broken declaration/definition), this won't matter.
3521       //
3522       // FIXME: We could do this if we juggled some extra state in
3523       // OverloadableAttr, rather than just removing it.
3524       const Decl *DiagOld = Old;
3525       if (OldOvl) {
3526         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3527           const auto *A = D->getAttr<OverloadableAttr>();
3528           return A && !A->isImplicit();
3529         });
3530         // If we've implicitly added *all* of the overloadable attrs to this
3531         // chain, emitting a "previous redecl" note is pointless.
3532         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3533       }
3534 
3535       if (DiagOld)
3536         Diag(DiagOld->getLocation(),
3537              diag::note_attribute_overloadable_prev_overload)
3538           << OldOvl;
3539 
3540       if (OldOvl)
3541         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3542       else
3543         New->dropAttr<OverloadableAttr>();
3544     }
3545   }
3546 
3547   // If a function is first declared with a calling convention, but is later
3548   // declared or defined without one, all following decls assume the calling
3549   // convention of the first.
3550   //
3551   // It's OK if a function is first declared without a calling convention,
3552   // but is later declared or defined with the default calling convention.
3553   //
3554   // To test if either decl has an explicit calling convention, we look for
3555   // AttributedType sugar nodes on the type as written.  If they are missing or
3556   // were canonicalized away, we assume the calling convention was implicit.
3557   //
3558   // Note also that we DO NOT return at this point, because we still have
3559   // other tests to run.
3560   QualType OldQType = Context.getCanonicalType(Old->getType());
3561   QualType NewQType = Context.getCanonicalType(New->getType());
3562   const FunctionType *OldType = cast<FunctionType>(OldQType);
3563   const FunctionType *NewType = cast<FunctionType>(NewQType);
3564   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3565   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3566   bool RequiresAdjustment = false;
3567 
3568   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3569     FunctionDecl *First = Old->getFirstDecl();
3570     const FunctionType *FT =
3571         First->getType().getCanonicalType()->castAs<FunctionType>();
3572     FunctionType::ExtInfo FI = FT->getExtInfo();
3573     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3574     if (!NewCCExplicit) {
3575       // Inherit the CC from the previous declaration if it was specified
3576       // there but not here.
3577       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3578       RequiresAdjustment = true;
3579     } else if (Old->getBuiltinID()) {
3580       // Builtin attribute isn't propagated to the new one yet at this point,
3581       // so we check if the old one is a builtin.
3582 
3583       // Calling Conventions on a Builtin aren't really useful and setting a
3584       // default calling convention and cdecl'ing some builtin redeclarations is
3585       // common, so warn and ignore the calling convention on the redeclaration.
3586       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3587           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3588           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3589       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3590       RequiresAdjustment = true;
3591     } else {
3592       // Calling conventions aren't compatible, so complain.
3593       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3594       Diag(New->getLocation(), diag::err_cconv_change)
3595         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3596         << !FirstCCExplicit
3597         << (!FirstCCExplicit ? "" :
3598             FunctionType::getNameForCallConv(FI.getCC()));
3599 
3600       // Put the note on the first decl, since it is the one that matters.
3601       Diag(First->getLocation(), diag::note_previous_declaration);
3602       return true;
3603     }
3604   }
3605 
3606   // FIXME: diagnose the other way around?
3607   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3608     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3609     RequiresAdjustment = true;
3610   }
3611 
3612   // Merge regparm attribute.
3613   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3614       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3615     if (NewTypeInfo.getHasRegParm()) {
3616       Diag(New->getLocation(), diag::err_regparm_mismatch)
3617         << NewType->getRegParmType()
3618         << OldType->getRegParmType();
3619       Diag(OldLocation, diag::note_previous_declaration);
3620       return true;
3621     }
3622 
3623     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3624     RequiresAdjustment = true;
3625   }
3626 
3627   // Merge ns_returns_retained attribute.
3628   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3629     if (NewTypeInfo.getProducesResult()) {
3630       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3631           << "'ns_returns_retained'";
3632       Diag(OldLocation, diag::note_previous_declaration);
3633       return true;
3634     }
3635 
3636     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3637     RequiresAdjustment = true;
3638   }
3639 
3640   if (OldTypeInfo.getNoCallerSavedRegs() !=
3641       NewTypeInfo.getNoCallerSavedRegs()) {
3642     if (NewTypeInfo.getNoCallerSavedRegs()) {
3643       AnyX86NoCallerSavedRegistersAttr *Attr =
3644         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3645       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3646       Diag(OldLocation, diag::note_previous_declaration);
3647       return true;
3648     }
3649 
3650     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3651     RequiresAdjustment = true;
3652   }
3653 
3654   if (RequiresAdjustment) {
3655     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3656     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3657     New->setType(QualType(AdjustedType, 0));
3658     NewQType = Context.getCanonicalType(New->getType());
3659   }
3660 
3661   // If this redeclaration makes the function inline, we may need to add it to
3662   // UndefinedButUsed.
3663   if (!Old->isInlined() && New->isInlined() &&
3664       !New->hasAttr<GNUInlineAttr>() &&
3665       !getLangOpts().GNUInline &&
3666       Old->isUsed(false) &&
3667       !Old->isDefined() && !New->isThisDeclarationADefinition())
3668     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3669                                            SourceLocation()));
3670 
3671   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3672   // about it.
3673   if (New->hasAttr<GNUInlineAttr>() &&
3674       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3675     UndefinedButUsed.erase(Old->getCanonicalDecl());
3676   }
3677 
3678   // If pass_object_size params don't match up perfectly, this isn't a valid
3679   // redeclaration.
3680   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3681       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3682     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3683         << New->getDeclName();
3684     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3685     return true;
3686   }
3687 
3688   if (getLangOpts().CPlusPlus) {
3689     // C++1z [over.load]p2
3690     //   Certain function declarations cannot be overloaded:
3691     //     -- Function declarations that differ only in the return type,
3692     //        the exception specification, or both cannot be overloaded.
3693 
3694     // Check the exception specifications match. This may recompute the type of
3695     // both Old and New if it resolved exception specifications, so grab the
3696     // types again after this. Because this updates the type, we do this before
3697     // any of the other checks below, which may update the "de facto" NewQType
3698     // but do not necessarily update the type of New.
3699     if (CheckEquivalentExceptionSpec(Old, New))
3700       return true;
3701     OldQType = Context.getCanonicalType(Old->getType());
3702     NewQType = Context.getCanonicalType(New->getType());
3703 
3704     // Go back to the type source info to compare the declared return types,
3705     // per C++1y [dcl.type.auto]p13:
3706     //   Redeclarations or specializations of a function or function template
3707     //   with a declared return type that uses a placeholder type shall also
3708     //   use that placeholder, not a deduced type.
3709     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3710     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3711     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3712         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3713                                        OldDeclaredReturnType)) {
3714       QualType ResQT;
3715       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3716           OldDeclaredReturnType->isObjCObjectPointerType())
3717         // FIXME: This does the wrong thing for a deduced return type.
3718         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3719       if (ResQT.isNull()) {
3720         if (New->isCXXClassMember() && New->isOutOfLine())
3721           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3722               << New << New->getReturnTypeSourceRange();
3723         else
3724           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3725               << New->getReturnTypeSourceRange();
3726         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3727                                     << Old->getReturnTypeSourceRange();
3728         return true;
3729       }
3730       else
3731         NewQType = ResQT;
3732     }
3733 
3734     QualType OldReturnType = OldType->getReturnType();
3735     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3736     if (OldReturnType != NewReturnType) {
3737       // If this function has a deduced return type and has already been
3738       // defined, copy the deduced value from the old declaration.
3739       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3740       if (OldAT && OldAT->isDeduced()) {
3741         QualType DT = OldAT->getDeducedType();
3742         if (DT.isNull()) {
3743           New->setType(SubstAutoTypeDependent(New->getType()));
3744           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3745         } else {
3746           New->setType(SubstAutoType(New->getType(), DT));
3747           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3748         }
3749       }
3750     }
3751 
3752     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3753     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3754     if (OldMethod && NewMethod) {
3755       // Preserve triviality.
3756       NewMethod->setTrivial(OldMethod->isTrivial());
3757 
3758       // MSVC allows explicit template specialization at class scope:
3759       // 2 CXXMethodDecls referring to the same function will be injected.
3760       // We don't want a redeclaration error.
3761       bool IsClassScopeExplicitSpecialization =
3762                               OldMethod->isFunctionTemplateSpecialization() &&
3763                               NewMethod->isFunctionTemplateSpecialization();
3764       bool isFriend = NewMethod->getFriendObjectKind();
3765 
3766       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3767           !IsClassScopeExplicitSpecialization) {
3768         //    -- Member function declarations with the same name and the
3769         //       same parameter types cannot be overloaded if any of them
3770         //       is a static member function declaration.
3771         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3772           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3773           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3774           return true;
3775         }
3776 
3777         // C++ [class.mem]p1:
3778         //   [...] A member shall not be declared twice in the
3779         //   member-specification, except that a nested class or member
3780         //   class template can be declared and then later defined.
3781         if (!inTemplateInstantiation()) {
3782           unsigned NewDiag;
3783           if (isa<CXXConstructorDecl>(OldMethod))
3784             NewDiag = diag::err_constructor_redeclared;
3785           else if (isa<CXXDestructorDecl>(NewMethod))
3786             NewDiag = diag::err_destructor_redeclared;
3787           else if (isa<CXXConversionDecl>(NewMethod))
3788             NewDiag = diag::err_conv_function_redeclared;
3789           else
3790             NewDiag = diag::err_member_redeclared;
3791 
3792           Diag(New->getLocation(), NewDiag);
3793         } else {
3794           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3795             << New << New->getType();
3796         }
3797         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3798         return true;
3799 
3800       // Complain if this is an explicit declaration of a special
3801       // member that was initially declared implicitly.
3802       //
3803       // As an exception, it's okay to befriend such methods in order
3804       // to permit the implicit constructor/destructor/operator calls.
3805       } else if (OldMethod->isImplicit()) {
3806         if (isFriend) {
3807           NewMethod->setImplicit();
3808         } else {
3809           Diag(NewMethod->getLocation(),
3810                diag::err_definition_of_implicitly_declared_member)
3811             << New << getSpecialMember(OldMethod);
3812           return true;
3813         }
3814       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3815         Diag(NewMethod->getLocation(),
3816              diag::err_definition_of_explicitly_defaulted_member)
3817           << getSpecialMember(OldMethod);
3818         return true;
3819       }
3820     }
3821 
3822     // C++11 [dcl.attr.noreturn]p1:
3823     //   The first declaration of a function shall specify the noreturn
3824     //   attribute if any declaration of that function specifies the noreturn
3825     //   attribute.
3826     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3827       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3828         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3829             << NRA;
3830         Diag(Old->getLocation(), diag::note_previous_declaration);
3831       }
3832 
3833     // C++11 [dcl.attr.depend]p2:
3834     //   The first declaration of a function shall specify the
3835     //   carries_dependency attribute for its declarator-id if any declaration
3836     //   of the function specifies the carries_dependency attribute.
3837     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3838     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3839       Diag(CDA->getLocation(),
3840            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3841       Diag(Old->getFirstDecl()->getLocation(),
3842            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3843     }
3844 
3845     // (C++98 8.3.5p3):
3846     //   All declarations for a function shall agree exactly in both the
3847     //   return type and the parameter-type-list.
3848     // We also want to respect all the extended bits except noreturn.
3849 
3850     // noreturn should now match unless the old type info didn't have it.
3851     QualType OldQTypeForComparison = OldQType;
3852     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3853       auto *OldType = OldQType->castAs<FunctionProtoType>();
3854       const FunctionType *OldTypeForComparison
3855         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3856       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3857       assert(OldQTypeForComparison.isCanonical());
3858     }
3859 
3860     if (haveIncompatibleLanguageLinkages(Old, New)) {
3861       // As a special case, retain the language linkage from previous
3862       // declarations of a friend function as an extension.
3863       //
3864       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3865       // and is useful because there's otherwise no way to specify language
3866       // linkage within class scope.
3867       //
3868       // Check cautiously as the friend object kind isn't yet complete.
3869       if (New->getFriendObjectKind() != Decl::FOK_None) {
3870         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3871         Diag(OldLocation, PrevDiag);
3872       } else {
3873         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3874         Diag(OldLocation, PrevDiag);
3875         return true;
3876       }
3877     }
3878 
3879     // If the function types are compatible, merge the declarations. Ignore the
3880     // exception specifier because it was already checked above in
3881     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3882     // about incompatible types under -fms-compatibility.
3883     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3884                                                          NewQType))
3885       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3886 
3887     // If the types are imprecise (due to dependent constructs in friends or
3888     // local extern declarations), it's OK if they differ. We'll check again
3889     // during instantiation.
3890     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3891       return false;
3892 
3893     // Fall through for conflicting redeclarations and redefinitions.
3894   }
3895 
3896   // C: Function types need to be compatible, not identical. This handles
3897   // duplicate function decls like "void f(int); void f(enum X);" properly.
3898   if (!getLangOpts().CPlusPlus) {
3899     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3900     // type is specified by a function definition that contains a (possibly
3901     // empty) identifier list, both shall agree in the number of parameters
3902     // and the type of each parameter shall be compatible with the type that
3903     // results from the application of default argument promotions to the
3904     // type of the corresponding identifier. ...
3905     // This cannot be handled by ASTContext::typesAreCompatible() because that
3906     // doesn't know whether the function type is for a definition or not when
3907     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3908     // we need to cover here is that the number of arguments agree as the
3909     // default argument promotion rules were already checked by
3910     // ASTContext::typesAreCompatible().
3911     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3912         Old->getNumParams() != New->getNumParams()) {
3913       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3914       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3915       return true;
3916     }
3917 
3918     // If we are merging two functions where only one of them has a prototype,
3919     // we may have enough information to decide to issue a diagnostic that the
3920     // function without a protoype will change behavior in C2x. This handles
3921     // cases like:
3922     //   void i(); void i(int j);
3923     //   void i(int j); void i();
3924     //   void i(); void i(int j) {}
3925     // See ActOnFinishFunctionBody() for other cases of the behavior change
3926     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3927     // type without a prototype.
3928     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3929         !New->isImplicit() && !Old->isImplicit()) {
3930       const FunctionDecl *WithProto, *WithoutProto;
3931       if (New->hasWrittenPrototype()) {
3932         WithProto = New;
3933         WithoutProto = Old;
3934       } else {
3935         WithProto = Old;
3936         WithoutProto = New;
3937       }
3938 
3939       if (WithProto->getNumParams() != 0) {
3940         // The function definition has parameters, so this will change
3941         // behavior in C2x.
3942         //
3943         // If we already warned about about the function without a prototype
3944         // being deprecated, add a note that it also changes behavior. If we
3945         // didn't warn about it being deprecated (because the diagnostic is
3946         // not enabled), warn now that it is deprecated and changes behavior.
3947         bool AddNote = false;
3948         if (Diags.isIgnored(diag::warn_strict_prototypes,
3949                             WithoutProto->getLocation())) {
3950           if (WithoutProto->getBuiltinID() == 0 &&
3951               !WithoutProto->isImplicit() &&
3952               SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
3953                                                   WithProto->getLocation())) {
3954             PartialDiagnostic PD =
3955                 PDiag(diag::warn_non_prototype_changes_behavior);
3956             if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
3957               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
3958                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
3959             }
3960             Diag(WithoutProto->getLocation(), PD);
3961           }
3962         } else {
3963           AddNote = true;
3964         }
3965 
3966         // Because the function with a prototype has parameters but a previous
3967         // declaration had none, the function with the prototype will also
3968         // change behavior in C2x.
3969         if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) {
3970           if (SourceMgr.isBeforeInTranslationUnit(
3971                   WithProto->getLocation(), WithoutProto->getLocation())) {
3972             // If the function with the prototype comes before the function
3973             // without the prototype, we only want to diagnose the one without
3974             // the prototype.
3975             Diag(WithoutProto->getLocation(),
3976                  diag::warn_non_prototype_changes_behavior);
3977           } else {
3978             // Otherwise, diagnose the one with the prototype, and potentially
3979             // attach a note to the one without a prototype if needed.
3980             Diag(WithProto->getLocation(),
3981                  diag::warn_non_prototype_changes_behavior);
3982             if (AddNote && WithoutProto->getBuiltinID() == 0)
3983               Diag(WithoutProto->getLocation(),
3984                    diag::note_func_decl_changes_behavior);
3985           }
3986         } else if (AddNote && WithoutProto->getBuiltinID() == 0 &&
3987                    !WithoutProto->isImplicit()) {
3988           // If we were supposed to add a note but the function with a
3989           // prototype is a builtin or was implicitly declared, which means we
3990           // have nothing to attach the note to, so we issue a warning instead.
3991           Diag(WithoutProto->getLocation(),
3992                diag::warn_non_prototype_changes_behavior);
3993         }
3994       }
3995     }
3996 
3997     if (Context.typesAreCompatible(OldQType, NewQType)) {
3998       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3999       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4000       const FunctionProtoType *OldProto = nullptr;
4001       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4002           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4003         // The old declaration provided a function prototype, but the
4004         // new declaration does not. Merge in the prototype.
4005         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4006         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4007         NewQType =
4008             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4009                                     OldProto->getExtProtoInfo());
4010         New->setType(NewQType);
4011         New->setHasInheritedPrototype();
4012 
4013         // Synthesize parameters with the same types.
4014         SmallVector<ParmVarDecl *, 16> Params;
4015         for (const auto &ParamType : OldProto->param_types()) {
4016           ParmVarDecl *Param = ParmVarDecl::Create(
4017               Context, New, SourceLocation(), SourceLocation(), nullptr,
4018               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4019           Param->setScopeInfo(0, Params.size());
4020           Param->setImplicit();
4021           Params.push_back(Param);
4022         }
4023 
4024         New->setParams(Params);
4025       }
4026 
4027       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4028     }
4029   }
4030 
4031   // Check if the function types are compatible when pointer size address
4032   // spaces are ignored.
4033   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4034     return false;
4035 
4036   // GNU C permits a K&R definition to follow a prototype declaration
4037   // if the declared types of the parameters in the K&R definition
4038   // match the types in the prototype declaration, even when the
4039   // promoted types of the parameters from the K&R definition differ
4040   // from the types in the prototype. GCC then keeps the types from
4041   // the prototype.
4042   //
4043   // If a variadic prototype is followed by a non-variadic K&R definition,
4044   // the K&R definition becomes variadic.  This is sort of an edge case, but
4045   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4046   // C99 6.9.1p8.
4047   if (!getLangOpts().CPlusPlus &&
4048       Old->hasPrototype() && !New->hasPrototype() &&
4049       New->getType()->getAs<FunctionProtoType>() &&
4050       Old->getNumParams() == New->getNumParams()) {
4051     SmallVector<QualType, 16> ArgTypes;
4052     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4053     const FunctionProtoType *OldProto
4054       = Old->getType()->getAs<FunctionProtoType>();
4055     const FunctionProtoType *NewProto
4056       = New->getType()->getAs<FunctionProtoType>();
4057 
4058     // Determine whether this is the GNU C extension.
4059     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4060                                                NewProto->getReturnType());
4061     bool LooseCompatible = !MergedReturn.isNull();
4062     for (unsigned Idx = 0, End = Old->getNumParams();
4063          LooseCompatible && Idx != End; ++Idx) {
4064       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4065       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4066       if (Context.typesAreCompatible(OldParm->getType(),
4067                                      NewProto->getParamType(Idx))) {
4068         ArgTypes.push_back(NewParm->getType());
4069       } else if (Context.typesAreCompatible(OldParm->getType(),
4070                                             NewParm->getType(),
4071                                             /*CompareUnqualified=*/true)) {
4072         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4073                                            NewProto->getParamType(Idx) };
4074         Warnings.push_back(Warn);
4075         ArgTypes.push_back(NewParm->getType());
4076       } else
4077         LooseCompatible = false;
4078     }
4079 
4080     if (LooseCompatible) {
4081       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4082         Diag(Warnings[Warn].NewParm->getLocation(),
4083              diag::ext_param_promoted_not_compatible_with_prototype)
4084           << Warnings[Warn].PromotedType
4085           << Warnings[Warn].OldParm->getType();
4086         if (Warnings[Warn].OldParm->getLocation().isValid())
4087           Diag(Warnings[Warn].OldParm->getLocation(),
4088                diag::note_previous_declaration);
4089       }
4090 
4091       if (MergeTypeWithOld)
4092         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4093                                              OldProto->getExtProtoInfo()));
4094       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4095     }
4096 
4097     // Fall through to diagnose conflicting types.
4098   }
4099 
4100   // A function that has already been declared has been redeclared or
4101   // defined with a different type; show an appropriate diagnostic.
4102 
4103   // If the previous declaration was an implicitly-generated builtin
4104   // declaration, then at the very least we should use a specialized note.
4105   unsigned BuiltinID;
4106   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4107     // If it's actually a library-defined builtin function like 'malloc'
4108     // or 'printf', just warn about the incompatible redeclaration.
4109     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4110       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4111       Diag(OldLocation, diag::note_previous_builtin_declaration)
4112         << Old << Old->getType();
4113       return false;
4114     }
4115 
4116     PrevDiag = diag::note_previous_builtin_declaration;
4117   }
4118 
4119   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4120   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4121   return true;
4122 }
4123 
4124 /// Completes the merge of two function declarations that are
4125 /// known to be compatible.
4126 ///
4127 /// This routine handles the merging of attributes and other
4128 /// properties of function declarations from the old declaration to
4129 /// the new declaration, once we know that New is in fact a
4130 /// redeclaration of Old.
4131 ///
4132 /// \returns false
4133 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4134                                         Scope *S, bool MergeTypeWithOld) {
4135   // Merge the attributes
4136   mergeDeclAttributes(New, Old);
4137 
4138   // Merge "pure" flag.
4139   if (Old->isPure())
4140     New->setPure();
4141 
4142   // Merge "used" flag.
4143   if (Old->getMostRecentDecl()->isUsed(false))
4144     New->setIsUsed();
4145 
4146   // Merge attributes from the parameters.  These can mismatch with K&R
4147   // declarations.
4148   if (New->getNumParams() == Old->getNumParams())
4149       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4150         ParmVarDecl *NewParam = New->getParamDecl(i);
4151         ParmVarDecl *OldParam = Old->getParamDecl(i);
4152         mergeParamDeclAttributes(NewParam, OldParam, *this);
4153         mergeParamDeclTypes(NewParam, OldParam, *this);
4154       }
4155 
4156   if (getLangOpts().CPlusPlus)
4157     return MergeCXXFunctionDecl(New, Old, S);
4158 
4159   // Merge the function types so the we get the composite types for the return
4160   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4161   // was visible.
4162   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4163   if (!Merged.isNull() && MergeTypeWithOld)
4164     New->setType(Merged);
4165 
4166   return false;
4167 }
4168 
4169 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4170                                 ObjCMethodDecl *oldMethod) {
4171   // Merge the attributes, including deprecated/unavailable
4172   AvailabilityMergeKind MergeKind =
4173       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4174           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4175                                      : AMK_ProtocolImplementation)
4176           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4177                                                            : AMK_Override;
4178 
4179   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4180 
4181   // Merge attributes from the parameters.
4182   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4183                                        oe = oldMethod->param_end();
4184   for (ObjCMethodDecl::param_iterator
4185          ni = newMethod->param_begin(), ne = newMethod->param_end();
4186        ni != ne && oi != oe; ++ni, ++oi)
4187     mergeParamDeclAttributes(*ni, *oi, *this);
4188 
4189   CheckObjCMethodOverride(newMethod, oldMethod);
4190 }
4191 
4192 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4193   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4194 
4195   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4196          ? diag::err_redefinition_different_type
4197          : diag::err_redeclaration_different_type)
4198     << New->getDeclName() << New->getType() << Old->getType();
4199 
4200   diag::kind PrevDiag;
4201   SourceLocation OldLocation;
4202   std::tie(PrevDiag, OldLocation)
4203     = getNoteDiagForInvalidRedeclaration(Old, New);
4204   S.Diag(OldLocation, PrevDiag);
4205   New->setInvalidDecl();
4206 }
4207 
4208 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4209 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4210 /// emitting diagnostics as appropriate.
4211 ///
4212 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4213 /// to here in AddInitializerToDecl. We can't check them before the initializer
4214 /// is attached.
4215 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4216                              bool MergeTypeWithOld) {
4217   if (New->isInvalidDecl() || Old->isInvalidDecl())
4218     return;
4219 
4220   QualType MergedT;
4221   if (getLangOpts().CPlusPlus) {
4222     if (New->getType()->isUndeducedType()) {
4223       // We don't know what the new type is until the initializer is attached.
4224       return;
4225     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4226       // These could still be something that needs exception specs checked.
4227       return MergeVarDeclExceptionSpecs(New, Old);
4228     }
4229     // C++ [basic.link]p10:
4230     //   [...] the types specified by all declarations referring to a given
4231     //   object or function shall be identical, except that declarations for an
4232     //   array object can specify array types that differ by the presence or
4233     //   absence of a major array bound (8.3.4).
4234     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4235       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4236       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4237 
4238       // We are merging a variable declaration New into Old. If it has an array
4239       // bound, and that bound differs from Old's bound, we should diagnose the
4240       // mismatch.
4241       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4242         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4243              PrevVD = PrevVD->getPreviousDecl()) {
4244           QualType PrevVDTy = PrevVD->getType();
4245           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4246             continue;
4247 
4248           if (!Context.hasSameType(New->getType(), PrevVDTy))
4249             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4250         }
4251       }
4252 
4253       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4254         if (Context.hasSameType(OldArray->getElementType(),
4255                                 NewArray->getElementType()))
4256           MergedT = New->getType();
4257       }
4258       // FIXME: Check visibility. New is hidden but has a complete type. If New
4259       // has no array bound, it should not inherit one from Old, if Old is not
4260       // visible.
4261       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4262         if (Context.hasSameType(OldArray->getElementType(),
4263                                 NewArray->getElementType()))
4264           MergedT = Old->getType();
4265       }
4266     }
4267     else if (New->getType()->isObjCObjectPointerType() &&
4268                Old->getType()->isObjCObjectPointerType()) {
4269       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4270                                               Old->getType());
4271     }
4272   } else {
4273     // C 6.2.7p2:
4274     //   All declarations that refer to the same object or function shall have
4275     //   compatible type.
4276     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4277   }
4278   if (MergedT.isNull()) {
4279     // It's OK if we couldn't merge types if either type is dependent, for a
4280     // block-scope variable. In other cases (static data members of class
4281     // templates, variable templates, ...), we require the types to be
4282     // equivalent.
4283     // FIXME: The C++ standard doesn't say anything about this.
4284     if ((New->getType()->isDependentType() ||
4285          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4286       // If the old type was dependent, we can't merge with it, so the new type
4287       // becomes dependent for now. We'll reproduce the original type when we
4288       // instantiate the TypeSourceInfo for the variable.
4289       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4290         New->setType(Context.DependentTy);
4291       return;
4292     }
4293     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4294   }
4295 
4296   // Don't actually update the type on the new declaration if the old
4297   // declaration was an extern declaration in a different scope.
4298   if (MergeTypeWithOld)
4299     New->setType(MergedT);
4300 }
4301 
4302 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4303                                   LookupResult &Previous) {
4304   // C11 6.2.7p4:
4305   //   For an identifier with internal or external linkage declared
4306   //   in a scope in which a prior declaration of that identifier is
4307   //   visible, if the prior declaration specifies internal or
4308   //   external linkage, the type of the identifier at the later
4309   //   declaration becomes the composite type.
4310   //
4311   // If the variable isn't visible, we do not merge with its type.
4312   if (Previous.isShadowed())
4313     return false;
4314 
4315   if (S.getLangOpts().CPlusPlus) {
4316     // C++11 [dcl.array]p3:
4317     //   If there is a preceding declaration of the entity in the same
4318     //   scope in which the bound was specified, an omitted array bound
4319     //   is taken to be the same as in that earlier declaration.
4320     return NewVD->isPreviousDeclInSameBlockScope() ||
4321            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4322             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4323   } else {
4324     // If the old declaration was function-local, don't merge with its
4325     // type unless we're in the same function.
4326     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4327            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4328   }
4329 }
4330 
4331 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4332 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4333 /// situation, merging decls or emitting diagnostics as appropriate.
4334 ///
4335 /// Tentative definition rules (C99 6.9.2p2) are checked by
4336 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4337 /// definitions here, since the initializer hasn't been attached.
4338 ///
4339 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4340   // If the new decl is already invalid, don't do any other checking.
4341   if (New->isInvalidDecl())
4342     return;
4343 
4344   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4345     return;
4346 
4347   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4348 
4349   // Verify the old decl was also a variable or variable template.
4350   VarDecl *Old = nullptr;
4351   VarTemplateDecl *OldTemplate = nullptr;
4352   if (Previous.isSingleResult()) {
4353     if (NewTemplate) {
4354       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4355       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4356 
4357       if (auto *Shadow =
4358               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4359         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4360           return New->setInvalidDecl();
4361     } else {
4362       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4363 
4364       if (auto *Shadow =
4365               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4366         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4367           return New->setInvalidDecl();
4368     }
4369   }
4370   if (!Old) {
4371     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4372         << New->getDeclName();
4373     notePreviousDefinition(Previous.getRepresentativeDecl(),
4374                            New->getLocation());
4375     return New->setInvalidDecl();
4376   }
4377 
4378   // If the old declaration was found in an inline namespace and the new
4379   // declaration was qualified, update the DeclContext to match.
4380   adjustDeclContextForDeclaratorDecl(New, Old);
4381 
4382   // Ensure the template parameters are compatible.
4383   if (NewTemplate &&
4384       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4385                                       OldTemplate->getTemplateParameters(),
4386                                       /*Complain=*/true, TPL_TemplateMatch))
4387     return New->setInvalidDecl();
4388 
4389   // C++ [class.mem]p1:
4390   //   A member shall not be declared twice in the member-specification [...]
4391   //
4392   // Here, we need only consider static data members.
4393   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4394     Diag(New->getLocation(), diag::err_duplicate_member)
4395       << New->getIdentifier();
4396     Diag(Old->getLocation(), diag::note_previous_declaration);
4397     New->setInvalidDecl();
4398   }
4399 
4400   mergeDeclAttributes(New, Old);
4401   // Warn if an already-declared variable is made a weak_import in a subsequent
4402   // declaration
4403   if (New->hasAttr<WeakImportAttr>() &&
4404       Old->getStorageClass() == SC_None &&
4405       !Old->hasAttr<WeakImportAttr>()) {
4406     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4407     Diag(Old->getLocation(), diag::note_previous_declaration);
4408     // Remove weak_import attribute on new declaration.
4409     New->dropAttr<WeakImportAttr>();
4410   }
4411 
4412   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4413     if (!Old->hasAttr<InternalLinkageAttr>()) {
4414       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4415           << ILA;
4416       Diag(Old->getLocation(), diag::note_previous_declaration);
4417       New->dropAttr<InternalLinkageAttr>();
4418     }
4419 
4420   // Merge the types.
4421   VarDecl *MostRecent = Old->getMostRecentDecl();
4422   if (MostRecent != Old) {
4423     MergeVarDeclTypes(New, MostRecent,
4424                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4425     if (New->isInvalidDecl())
4426       return;
4427   }
4428 
4429   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4430   if (New->isInvalidDecl())
4431     return;
4432 
4433   diag::kind PrevDiag;
4434   SourceLocation OldLocation;
4435   std::tie(PrevDiag, OldLocation) =
4436       getNoteDiagForInvalidRedeclaration(Old, New);
4437 
4438   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4439   if (New->getStorageClass() == SC_Static &&
4440       !New->isStaticDataMember() &&
4441       Old->hasExternalFormalLinkage()) {
4442     if (getLangOpts().MicrosoftExt) {
4443       Diag(New->getLocation(), diag::ext_static_non_static)
4444           << New->getDeclName();
4445       Diag(OldLocation, PrevDiag);
4446     } else {
4447       Diag(New->getLocation(), diag::err_static_non_static)
4448           << New->getDeclName();
4449       Diag(OldLocation, PrevDiag);
4450       return New->setInvalidDecl();
4451     }
4452   }
4453   // C99 6.2.2p4:
4454   //   For an identifier declared with the storage-class specifier
4455   //   extern in a scope in which a prior declaration of that
4456   //   identifier is visible,23) if the prior declaration specifies
4457   //   internal or external linkage, the linkage of the identifier at
4458   //   the later declaration is the same as the linkage specified at
4459   //   the prior declaration. If no prior declaration is visible, or
4460   //   if the prior declaration specifies no linkage, then the
4461   //   identifier has external linkage.
4462   if (New->hasExternalStorage() && Old->hasLinkage())
4463     /* Okay */;
4464   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4465            !New->isStaticDataMember() &&
4466            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4467     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4468     Diag(OldLocation, PrevDiag);
4469     return New->setInvalidDecl();
4470   }
4471 
4472   // Check if extern is followed by non-extern and vice-versa.
4473   if (New->hasExternalStorage() &&
4474       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4475     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4476     Diag(OldLocation, PrevDiag);
4477     return New->setInvalidDecl();
4478   }
4479   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4480       !New->hasExternalStorage()) {
4481     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4482     Diag(OldLocation, PrevDiag);
4483     return New->setInvalidDecl();
4484   }
4485 
4486   if (CheckRedeclarationInModule(New, Old))
4487     return;
4488 
4489   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4490 
4491   // FIXME: The test for external storage here seems wrong? We still
4492   // need to check for mismatches.
4493   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4494       // Don't complain about out-of-line definitions of static members.
4495       !(Old->getLexicalDeclContext()->isRecord() &&
4496         !New->getLexicalDeclContext()->isRecord())) {
4497     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4498     Diag(OldLocation, PrevDiag);
4499     return New->setInvalidDecl();
4500   }
4501 
4502   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4503     if (VarDecl *Def = Old->getDefinition()) {
4504       // C++1z [dcl.fcn.spec]p4:
4505       //   If the definition of a variable appears in a translation unit before
4506       //   its first declaration as inline, the program is ill-formed.
4507       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4508       Diag(Def->getLocation(), diag::note_previous_definition);
4509     }
4510   }
4511 
4512   // If this redeclaration makes the variable inline, we may need to add it to
4513   // UndefinedButUsed.
4514   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4515       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4516     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4517                                            SourceLocation()));
4518 
4519   if (New->getTLSKind() != Old->getTLSKind()) {
4520     if (!Old->getTLSKind()) {
4521       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4522       Diag(OldLocation, PrevDiag);
4523     } else if (!New->getTLSKind()) {
4524       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4525       Diag(OldLocation, PrevDiag);
4526     } else {
4527       // Do not allow redeclaration to change the variable between requiring
4528       // static and dynamic initialization.
4529       // FIXME: GCC allows this, but uses the TLS keyword on the first
4530       // declaration to determine the kind. Do we need to be compatible here?
4531       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4532         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4533       Diag(OldLocation, PrevDiag);
4534     }
4535   }
4536 
4537   // C++ doesn't have tentative definitions, so go right ahead and check here.
4538   if (getLangOpts().CPlusPlus &&
4539       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4540     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4541         Old->getCanonicalDecl()->isConstexpr()) {
4542       // This definition won't be a definition any more once it's been merged.
4543       Diag(New->getLocation(),
4544            diag::warn_deprecated_redundant_constexpr_static_def);
4545     } else if (VarDecl *Def = Old->getDefinition()) {
4546       if (checkVarDeclRedefinition(Def, New))
4547         return;
4548     }
4549   }
4550 
4551   if (haveIncompatibleLanguageLinkages(Old, New)) {
4552     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4553     Diag(OldLocation, PrevDiag);
4554     New->setInvalidDecl();
4555     return;
4556   }
4557 
4558   // Merge "used" flag.
4559   if (Old->getMostRecentDecl()->isUsed(false))
4560     New->setIsUsed();
4561 
4562   // Keep a chain of previous declarations.
4563   New->setPreviousDecl(Old);
4564   if (NewTemplate)
4565     NewTemplate->setPreviousDecl(OldTemplate);
4566 
4567   // Inherit access appropriately.
4568   New->setAccess(Old->getAccess());
4569   if (NewTemplate)
4570     NewTemplate->setAccess(New->getAccess());
4571 
4572   if (Old->isInline())
4573     New->setImplicitlyInline();
4574 }
4575 
4576 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4577   SourceManager &SrcMgr = getSourceManager();
4578   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4579   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4580   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4581   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4582   auto &HSI = PP.getHeaderSearchInfo();
4583   StringRef HdrFilename =
4584       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4585 
4586   auto noteFromModuleOrInclude = [&](Module *Mod,
4587                                      SourceLocation IncLoc) -> bool {
4588     // Redefinition errors with modules are common with non modular mapped
4589     // headers, example: a non-modular header H in module A that also gets
4590     // included directly in a TU. Pointing twice to the same header/definition
4591     // is confusing, try to get better diagnostics when modules is on.
4592     if (IncLoc.isValid()) {
4593       if (Mod) {
4594         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4595             << HdrFilename.str() << Mod->getFullModuleName();
4596         if (!Mod->DefinitionLoc.isInvalid())
4597           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4598               << Mod->getFullModuleName();
4599       } else {
4600         Diag(IncLoc, diag::note_redefinition_include_same_file)
4601             << HdrFilename.str();
4602       }
4603       return true;
4604     }
4605 
4606     return false;
4607   };
4608 
4609   // Is it the same file and same offset? Provide more information on why
4610   // this leads to a redefinition error.
4611   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4612     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4613     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4614     bool EmittedDiag =
4615         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4616     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4617 
4618     // If the header has no guards, emit a note suggesting one.
4619     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4620       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4621 
4622     if (EmittedDiag)
4623       return;
4624   }
4625 
4626   // Redefinition coming from different files or couldn't do better above.
4627   if (Old->getLocation().isValid())
4628     Diag(Old->getLocation(), diag::note_previous_definition);
4629 }
4630 
4631 /// We've just determined that \p Old and \p New both appear to be definitions
4632 /// of the same variable. Either diagnose or fix the problem.
4633 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4634   if (!hasVisibleDefinition(Old) &&
4635       (New->getFormalLinkage() == InternalLinkage ||
4636        New->isInline() ||
4637        New->getDescribedVarTemplate() ||
4638        New->getNumTemplateParameterLists() ||
4639        New->getDeclContext()->isDependentContext())) {
4640     // The previous definition is hidden, and multiple definitions are
4641     // permitted (in separate TUs). Demote this to a declaration.
4642     New->demoteThisDefinitionToDeclaration();
4643 
4644     // Make the canonical definition visible.
4645     if (auto *OldTD = Old->getDescribedVarTemplate())
4646       makeMergedDefinitionVisible(OldTD);
4647     makeMergedDefinitionVisible(Old);
4648     return false;
4649   } else {
4650     Diag(New->getLocation(), diag::err_redefinition) << New;
4651     notePreviousDefinition(Old, New->getLocation());
4652     New->setInvalidDecl();
4653     return true;
4654   }
4655 }
4656 
4657 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4658 /// no declarator (e.g. "struct foo;") is parsed.
4659 Decl *
4660 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4661                                  RecordDecl *&AnonRecord) {
4662   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4663                                     AnonRecord);
4664 }
4665 
4666 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4667 // disambiguate entities defined in different scopes.
4668 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4669 // compatibility.
4670 // We will pick our mangling number depending on which version of MSVC is being
4671 // targeted.
4672 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4673   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4674              ? S->getMSCurManglingNumber()
4675              : S->getMSLastManglingNumber();
4676 }
4677 
4678 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4679   if (!Context.getLangOpts().CPlusPlus)
4680     return;
4681 
4682   if (isa<CXXRecordDecl>(Tag->getParent())) {
4683     // If this tag is the direct child of a class, number it if
4684     // it is anonymous.
4685     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4686       return;
4687     MangleNumberingContext &MCtx =
4688         Context.getManglingNumberContext(Tag->getParent());
4689     Context.setManglingNumber(
4690         Tag, MCtx.getManglingNumber(
4691                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4692     return;
4693   }
4694 
4695   // If this tag isn't a direct child of a class, number it if it is local.
4696   MangleNumberingContext *MCtx;
4697   Decl *ManglingContextDecl;
4698   std::tie(MCtx, ManglingContextDecl) =
4699       getCurrentMangleNumberContext(Tag->getDeclContext());
4700   if (MCtx) {
4701     Context.setManglingNumber(
4702         Tag, MCtx->getManglingNumber(
4703                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4704   }
4705 }
4706 
4707 namespace {
4708 struct NonCLikeKind {
4709   enum {
4710     None,
4711     BaseClass,
4712     DefaultMemberInit,
4713     Lambda,
4714     Friend,
4715     OtherMember,
4716     Invalid,
4717   } Kind = None;
4718   SourceRange Range;
4719 
4720   explicit operator bool() { return Kind != None; }
4721 };
4722 }
4723 
4724 /// Determine whether a class is C-like, according to the rules of C++
4725 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4726 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4727   if (RD->isInvalidDecl())
4728     return {NonCLikeKind::Invalid, {}};
4729 
4730   // C++ [dcl.typedef]p9: [P1766R1]
4731   //   An unnamed class with a typedef name for linkage purposes shall not
4732   //
4733   //    -- have any base classes
4734   if (RD->getNumBases())
4735     return {NonCLikeKind::BaseClass,
4736             SourceRange(RD->bases_begin()->getBeginLoc(),
4737                         RD->bases_end()[-1].getEndLoc())};
4738   bool Invalid = false;
4739   for (Decl *D : RD->decls()) {
4740     // Don't complain about things we already diagnosed.
4741     if (D->isInvalidDecl()) {
4742       Invalid = true;
4743       continue;
4744     }
4745 
4746     //  -- have any [...] default member initializers
4747     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4748       if (FD->hasInClassInitializer()) {
4749         auto *Init = FD->getInClassInitializer();
4750         return {NonCLikeKind::DefaultMemberInit,
4751                 Init ? Init->getSourceRange() : D->getSourceRange()};
4752       }
4753       continue;
4754     }
4755 
4756     // FIXME: We don't allow friend declarations. This violates the wording of
4757     // P1766, but not the intent.
4758     if (isa<FriendDecl>(D))
4759       return {NonCLikeKind::Friend, D->getSourceRange()};
4760 
4761     //  -- declare any members other than non-static data members, member
4762     //     enumerations, or member classes,
4763     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4764         isa<EnumDecl>(D))
4765       continue;
4766     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4767     if (!MemberRD) {
4768       if (D->isImplicit())
4769         continue;
4770       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4771     }
4772 
4773     //  -- contain a lambda-expression,
4774     if (MemberRD->isLambda())
4775       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4776 
4777     //  and all member classes shall also satisfy these requirements
4778     //  (recursively).
4779     if (MemberRD->isThisDeclarationADefinition()) {
4780       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4781         return Kind;
4782     }
4783   }
4784 
4785   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4786 }
4787 
4788 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4789                                         TypedefNameDecl *NewTD) {
4790   if (TagFromDeclSpec->isInvalidDecl())
4791     return;
4792 
4793   // Do nothing if the tag already has a name for linkage purposes.
4794   if (TagFromDeclSpec->hasNameForLinkage())
4795     return;
4796 
4797   // A well-formed anonymous tag must always be a TUK_Definition.
4798   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4799 
4800   // The type must match the tag exactly;  no qualifiers allowed.
4801   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4802                            Context.getTagDeclType(TagFromDeclSpec))) {
4803     if (getLangOpts().CPlusPlus)
4804       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4805     return;
4806   }
4807 
4808   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4809   //   An unnamed class with a typedef name for linkage purposes shall [be
4810   //   C-like].
4811   //
4812   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4813   // shouldn't happen, but there are constructs that the language rule doesn't
4814   // disallow for which we can't reasonably avoid computing linkage early.
4815   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4816   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4817                              : NonCLikeKind();
4818   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4819   if (NonCLike || ChangesLinkage) {
4820     if (NonCLike.Kind == NonCLikeKind::Invalid)
4821       return;
4822 
4823     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4824     if (ChangesLinkage) {
4825       // If the linkage changes, we can't accept this as an extension.
4826       if (NonCLike.Kind == NonCLikeKind::None)
4827         DiagID = diag::err_typedef_changes_linkage;
4828       else
4829         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4830     }
4831 
4832     SourceLocation FixitLoc =
4833         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4834     llvm::SmallString<40> TextToInsert;
4835     TextToInsert += ' ';
4836     TextToInsert += NewTD->getIdentifier()->getName();
4837 
4838     Diag(FixitLoc, DiagID)
4839       << isa<TypeAliasDecl>(NewTD)
4840       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4841     if (NonCLike.Kind != NonCLikeKind::None) {
4842       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4843         << NonCLike.Kind - 1 << NonCLike.Range;
4844     }
4845     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4846       << NewTD << isa<TypeAliasDecl>(NewTD);
4847 
4848     if (ChangesLinkage)
4849       return;
4850   }
4851 
4852   // Otherwise, set this as the anon-decl typedef for the tag.
4853   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4854 }
4855 
4856 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4857   switch (T) {
4858   case DeclSpec::TST_class:
4859     return 0;
4860   case DeclSpec::TST_struct:
4861     return 1;
4862   case DeclSpec::TST_interface:
4863     return 2;
4864   case DeclSpec::TST_union:
4865     return 3;
4866   case DeclSpec::TST_enum:
4867     return 4;
4868   default:
4869     llvm_unreachable("unexpected type specifier");
4870   }
4871 }
4872 
4873 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4874 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4875 /// parameters to cope with template friend declarations.
4876 Decl *
4877 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4878                                  MultiTemplateParamsArg TemplateParams,
4879                                  bool IsExplicitInstantiation,
4880                                  RecordDecl *&AnonRecord) {
4881   Decl *TagD = nullptr;
4882   TagDecl *Tag = nullptr;
4883   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4884       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4885       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4886       DS.getTypeSpecType() == DeclSpec::TST_union ||
4887       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4888     TagD = DS.getRepAsDecl();
4889 
4890     if (!TagD) // We probably had an error
4891       return nullptr;
4892 
4893     // Note that the above type specs guarantee that the
4894     // type rep is a Decl, whereas in many of the others
4895     // it's a Type.
4896     if (isa<TagDecl>(TagD))
4897       Tag = cast<TagDecl>(TagD);
4898     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4899       Tag = CTD->getTemplatedDecl();
4900   }
4901 
4902   if (Tag) {
4903     handleTagNumbering(Tag, S);
4904     Tag->setFreeStanding();
4905     if (Tag->isInvalidDecl())
4906       return Tag;
4907   }
4908 
4909   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4910     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4911     // or incomplete types shall not be restrict-qualified."
4912     if (TypeQuals & DeclSpec::TQ_restrict)
4913       Diag(DS.getRestrictSpecLoc(),
4914            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4915            << DS.getSourceRange();
4916   }
4917 
4918   if (DS.isInlineSpecified())
4919     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4920         << getLangOpts().CPlusPlus17;
4921 
4922   if (DS.hasConstexprSpecifier()) {
4923     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4924     // and definitions of functions and variables.
4925     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4926     // the declaration of a function or function template
4927     if (Tag)
4928       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4929           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4930           << static_cast<int>(DS.getConstexprSpecifier());
4931     else
4932       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4933           << static_cast<int>(DS.getConstexprSpecifier());
4934     // Don't emit warnings after this error.
4935     return TagD;
4936   }
4937 
4938   DiagnoseFunctionSpecifiers(DS);
4939 
4940   if (DS.isFriendSpecified()) {
4941     // If we're dealing with a decl but not a TagDecl, assume that
4942     // whatever routines created it handled the friendship aspect.
4943     if (TagD && !Tag)
4944       return nullptr;
4945     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4946   }
4947 
4948   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4949   bool IsExplicitSpecialization =
4950     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4951   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4952       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4953       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4954     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4955     // nested-name-specifier unless it is an explicit instantiation
4956     // or an explicit specialization.
4957     //
4958     // FIXME: We allow class template partial specializations here too, per the
4959     // obvious intent of DR1819.
4960     //
4961     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4962     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4963         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4964     return nullptr;
4965   }
4966 
4967   // Track whether this decl-specifier declares anything.
4968   bool DeclaresAnything = true;
4969 
4970   // Handle anonymous struct definitions.
4971   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4972     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4973         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4974       if (getLangOpts().CPlusPlus ||
4975           Record->getDeclContext()->isRecord()) {
4976         // If CurContext is a DeclContext that can contain statements,
4977         // RecursiveASTVisitor won't visit the decls that
4978         // BuildAnonymousStructOrUnion() will put into CurContext.
4979         // Also store them here so that they can be part of the
4980         // DeclStmt that gets created in this case.
4981         // FIXME: Also return the IndirectFieldDecls created by
4982         // BuildAnonymousStructOr union, for the same reason?
4983         if (CurContext->isFunctionOrMethod())
4984           AnonRecord = Record;
4985         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4986                                            Context.getPrintingPolicy());
4987       }
4988 
4989       DeclaresAnything = false;
4990     }
4991   }
4992 
4993   // C11 6.7.2.1p2:
4994   //   A struct-declaration that does not declare an anonymous structure or
4995   //   anonymous union shall contain a struct-declarator-list.
4996   //
4997   // This rule also existed in C89 and C99; the grammar for struct-declaration
4998   // did not permit a struct-declaration without a struct-declarator-list.
4999   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5000       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5001     // Check for Microsoft C extension: anonymous struct/union member.
5002     // Handle 2 kinds of anonymous struct/union:
5003     //   struct STRUCT;
5004     //   union UNION;
5005     // and
5006     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5007     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5008     if ((Tag && Tag->getDeclName()) ||
5009         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5010       RecordDecl *Record = nullptr;
5011       if (Tag)
5012         Record = dyn_cast<RecordDecl>(Tag);
5013       else if (const RecordType *RT =
5014                    DS.getRepAsType().get()->getAsStructureType())
5015         Record = RT->getDecl();
5016       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5017         Record = UT->getDecl();
5018 
5019       if (Record && getLangOpts().MicrosoftExt) {
5020         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5021             << Record->isUnion() << DS.getSourceRange();
5022         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5023       }
5024 
5025       DeclaresAnything = false;
5026     }
5027   }
5028 
5029   // Skip all the checks below if we have a type error.
5030   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5031       (TagD && TagD->isInvalidDecl()))
5032     return TagD;
5033 
5034   if (getLangOpts().CPlusPlus &&
5035       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5036     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5037       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5038           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5039         DeclaresAnything = false;
5040 
5041   if (!DS.isMissingDeclaratorOk()) {
5042     // Customize diagnostic for a typedef missing a name.
5043     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5044       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5045           << DS.getSourceRange();
5046     else
5047       DeclaresAnything = false;
5048   }
5049 
5050   if (DS.isModulePrivateSpecified() &&
5051       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5052     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5053       << Tag->getTagKind()
5054       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5055 
5056   ActOnDocumentableDecl(TagD);
5057 
5058   // C 6.7/2:
5059   //   A declaration [...] shall declare at least a declarator [...], a tag,
5060   //   or the members of an enumeration.
5061   // C++ [dcl.dcl]p3:
5062   //   [If there are no declarators], and except for the declaration of an
5063   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5064   //   names into the program, or shall redeclare a name introduced by a
5065   //   previous declaration.
5066   if (!DeclaresAnything) {
5067     // In C, we allow this as a (popular) extension / bug. Don't bother
5068     // producing further diagnostics for redundant qualifiers after this.
5069     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5070                                ? diag::err_no_declarators
5071                                : diag::ext_no_declarators)
5072         << DS.getSourceRange();
5073     return TagD;
5074   }
5075 
5076   // C++ [dcl.stc]p1:
5077   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5078   //   init-declarator-list of the declaration shall not be empty.
5079   // C++ [dcl.fct.spec]p1:
5080   //   If a cv-qualifier appears in a decl-specifier-seq, the
5081   //   init-declarator-list of the declaration shall not be empty.
5082   //
5083   // Spurious qualifiers here appear to be valid in C.
5084   unsigned DiagID = diag::warn_standalone_specifier;
5085   if (getLangOpts().CPlusPlus)
5086     DiagID = diag::ext_standalone_specifier;
5087 
5088   // Note that a linkage-specification sets a storage class, but
5089   // 'extern "C" struct foo;' is actually valid and not theoretically
5090   // useless.
5091   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5092     if (SCS == DeclSpec::SCS_mutable)
5093       // Since mutable is not a viable storage class specifier in C, there is
5094       // no reason to treat it as an extension. Instead, diagnose as an error.
5095       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5096     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5097       Diag(DS.getStorageClassSpecLoc(), DiagID)
5098         << DeclSpec::getSpecifierName(SCS);
5099   }
5100 
5101   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5102     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5103       << DeclSpec::getSpecifierName(TSCS);
5104   if (DS.getTypeQualifiers()) {
5105     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5106       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5107     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5108       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5109     // Restrict is covered above.
5110     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5111       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5112     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5113       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5114   }
5115 
5116   // Warn about ignored type attributes, for example:
5117   // __attribute__((aligned)) struct A;
5118   // Attributes should be placed after tag to apply to type declaration.
5119   if (!DS.getAttributes().empty()) {
5120     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5121     if (TypeSpecType == DeclSpec::TST_class ||
5122         TypeSpecType == DeclSpec::TST_struct ||
5123         TypeSpecType == DeclSpec::TST_interface ||
5124         TypeSpecType == DeclSpec::TST_union ||
5125         TypeSpecType == DeclSpec::TST_enum) {
5126       for (const ParsedAttr &AL : DS.getAttributes())
5127         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5128             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5129     }
5130   }
5131 
5132   return TagD;
5133 }
5134 
5135 /// We are trying to inject an anonymous member into the given scope;
5136 /// check if there's an existing declaration that can't be overloaded.
5137 ///
5138 /// \return true if this is a forbidden redeclaration
5139 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5140                                          Scope *S,
5141                                          DeclContext *Owner,
5142                                          DeclarationName Name,
5143                                          SourceLocation NameLoc,
5144                                          bool IsUnion) {
5145   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5146                  Sema::ForVisibleRedeclaration);
5147   if (!SemaRef.LookupName(R, S)) return false;
5148 
5149   // Pick a representative declaration.
5150   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5151   assert(PrevDecl && "Expected a non-null Decl");
5152 
5153   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5154     return false;
5155 
5156   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5157     << IsUnion << Name;
5158   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5159 
5160   return true;
5161 }
5162 
5163 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5164 /// anonymous struct or union AnonRecord into the owning context Owner
5165 /// and scope S. This routine will be invoked just after we realize
5166 /// that an unnamed union or struct is actually an anonymous union or
5167 /// struct, e.g.,
5168 ///
5169 /// @code
5170 /// union {
5171 ///   int i;
5172 ///   float f;
5173 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5174 ///    // f into the surrounding scope.x
5175 /// @endcode
5176 ///
5177 /// This routine is recursive, injecting the names of nested anonymous
5178 /// structs/unions into the owning context and scope as well.
5179 static bool
5180 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5181                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5182                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5183   bool Invalid = false;
5184 
5185   // Look every FieldDecl and IndirectFieldDecl with a name.
5186   for (auto *D : AnonRecord->decls()) {
5187     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5188         cast<NamedDecl>(D)->getDeclName()) {
5189       ValueDecl *VD = cast<ValueDecl>(D);
5190       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5191                                        VD->getLocation(),
5192                                        AnonRecord->isUnion())) {
5193         // C++ [class.union]p2:
5194         //   The names of the members of an anonymous union shall be
5195         //   distinct from the names of any other entity in the
5196         //   scope in which the anonymous union is declared.
5197         Invalid = true;
5198       } else {
5199         // C++ [class.union]p2:
5200         //   For the purpose of name lookup, after the anonymous union
5201         //   definition, the members of the anonymous union are
5202         //   considered to have been defined in the scope in which the
5203         //   anonymous union is declared.
5204         unsigned OldChainingSize = Chaining.size();
5205         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5206           Chaining.append(IF->chain_begin(), IF->chain_end());
5207         else
5208           Chaining.push_back(VD);
5209 
5210         assert(Chaining.size() >= 2);
5211         NamedDecl **NamedChain =
5212           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5213         for (unsigned i = 0; i < Chaining.size(); i++)
5214           NamedChain[i] = Chaining[i];
5215 
5216         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5217             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5218             VD->getType(), {NamedChain, Chaining.size()});
5219 
5220         for (const auto *Attr : VD->attrs())
5221           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5222 
5223         IndirectField->setAccess(AS);
5224         IndirectField->setImplicit();
5225         SemaRef.PushOnScopeChains(IndirectField, S);
5226 
5227         // That includes picking up the appropriate access specifier.
5228         if (AS != AS_none) IndirectField->setAccess(AS);
5229 
5230         Chaining.resize(OldChainingSize);
5231       }
5232     }
5233   }
5234 
5235   return Invalid;
5236 }
5237 
5238 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5239 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5240 /// illegal input values are mapped to SC_None.
5241 static StorageClass
5242 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5243   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5244   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5245          "Parser allowed 'typedef' as storage class VarDecl.");
5246   switch (StorageClassSpec) {
5247   case DeclSpec::SCS_unspecified:    return SC_None;
5248   case DeclSpec::SCS_extern:
5249     if (DS.isExternInLinkageSpec())
5250       return SC_None;
5251     return SC_Extern;
5252   case DeclSpec::SCS_static:         return SC_Static;
5253   case DeclSpec::SCS_auto:           return SC_Auto;
5254   case DeclSpec::SCS_register:       return SC_Register;
5255   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5256     // Illegal SCSs map to None: error reporting is up to the caller.
5257   case DeclSpec::SCS_mutable:        // Fall through.
5258   case DeclSpec::SCS_typedef:        return SC_None;
5259   }
5260   llvm_unreachable("unknown storage class specifier");
5261 }
5262 
5263 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5264   assert(Record->hasInClassInitializer());
5265 
5266   for (const auto *I : Record->decls()) {
5267     const auto *FD = dyn_cast<FieldDecl>(I);
5268     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5269       FD = IFD->getAnonField();
5270     if (FD && FD->hasInClassInitializer())
5271       return FD->getLocation();
5272   }
5273 
5274   llvm_unreachable("couldn't find in-class initializer");
5275 }
5276 
5277 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5278                                       SourceLocation DefaultInitLoc) {
5279   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5280     return;
5281 
5282   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5283   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5284 }
5285 
5286 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5287                                       CXXRecordDecl *AnonUnion) {
5288   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5289     return;
5290 
5291   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5292 }
5293 
5294 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5295 /// anonymous structure or union. Anonymous unions are a C++ feature
5296 /// (C++ [class.union]) and a C11 feature; anonymous structures
5297 /// are a C11 feature and GNU C++ extension.
5298 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5299                                         AccessSpecifier AS,
5300                                         RecordDecl *Record,
5301                                         const PrintingPolicy &Policy) {
5302   DeclContext *Owner = Record->getDeclContext();
5303 
5304   // Diagnose whether this anonymous struct/union is an extension.
5305   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5306     Diag(Record->getLocation(), diag::ext_anonymous_union);
5307   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5308     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5309   else if (!Record->isUnion() && !getLangOpts().C11)
5310     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5311 
5312   // C and C++ require different kinds of checks for anonymous
5313   // structs/unions.
5314   bool Invalid = false;
5315   if (getLangOpts().CPlusPlus) {
5316     const char *PrevSpec = nullptr;
5317     if (Record->isUnion()) {
5318       // C++ [class.union]p6:
5319       // C++17 [class.union.anon]p2:
5320       //   Anonymous unions declared in a named namespace or in the
5321       //   global namespace shall be declared static.
5322       unsigned DiagID;
5323       DeclContext *OwnerScope = Owner->getRedeclContext();
5324       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5325           (OwnerScope->isTranslationUnit() ||
5326            (OwnerScope->isNamespace() &&
5327             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5328         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5329           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5330 
5331         // Recover by adding 'static'.
5332         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5333                                PrevSpec, DiagID, Policy);
5334       }
5335       // C++ [class.union]p6:
5336       //   A storage class is not allowed in a declaration of an
5337       //   anonymous union in a class scope.
5338       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5339                isa<RecordDecl>(Owner)) {
5340         Diag(DS.getStorageClassSpecLoc(),
5341              diag::err_anonymous_union_with_storage_spec)
5342           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5343 
5344         // Recover by removing the storage specifier.
5345         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5346                                SourceLocation(),
5347                                PrevSpec, DiagID, Context.getPrintingPolicy());
5348       }
5349     }
5350 
5351     // Ignore const/volatile/restrict qualifiers.
5352     if (DS.getTypeQualifiers()) {
5353       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5354         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5355           << Record->isUnion() << "const"
5356           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5357       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5358         Diag(DS.getVolatileSpecLoc(),
5359              diag::ext_anonymous_struct_union_qualified)
5360           << Record->isUnion() << "volatile"
5361           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5362       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5363         Diag(DS.getRestrictSpecLoc(),
5364              diag::ext_anonymous_struct_union_qualified)
5365           << Record->isUnion() << "restrict"
5366           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5367       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5368         Diag(DS.getAtomicSpecLoc(),
5369              diag::ext_anonymous_struct_union_qualified)
5370           << Record->isUnion() << "_Atomic"
5371           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5372       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5373         Diag(DS.getUnalignedSpecLoc(),
5374              diag::ext_anonymous_struct_union_qualified)
5375           << Record->isUnion() << "__unaligned"
5376           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5377 
5378       DS.ClearTypeQualifiers();
5379     }
5380 
5381     // C++ [class.union]p2:
5382     //   The member-specification of an anonymous union shall only
5383     //   define non-static data members. [Note: nested types and
5384     //   functions cannot be declared within an anonymous union. ]
5385     for (auto *Mem : Record->decls()) {
5386       // Ignore invalid declarations; we already diagnosed them.
5387       if (Mem->isInvalidDecl())
5388         continue;
5389 
5390       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5391         // C++ [class.union]p3:
5392         //   An anonymous union shall not have private or protected
5393         //   members (clause 11).
5394         assert(FD->getAccess() != AS_none);
5395         if (FD->getAccess() != AS_public) {
5396           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5397             << Record->isUnion() << (FD->getAccess() == AS_protected);
5398           Invalid = true;
5399         }
5400 
5401         // C++ [class.union]p1
5402         //   An object of a class with a non-trivial constructor, a non-trivial
5403         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5404         //   assignment operator cannot be a member of a union, nor can an
5405         //   array of such objects.
5406         if (CheckNontrivialField(FD))
5407           Invalid = true;
5408       } else if (Mem->isImplicit()) {
5409         // Any implicit members are fine.
5410       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5411         // This is a type that showed up in an
5412         // elaborated-type-specifier inside the anonymous struct or
5413         // union, but which actually declares a type outside of the
5414         // anonymous struct or union. It's okay.
5415       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5416         if (!MemRecord->isAnonymousStructOrUnion() &&
5417             MemRecord->getDeclName()) {
5418           // Visual C++ allows type definition in anonymous struct or union.
5419           if (getLangOpts().MicrosoftExt)
5420             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5421               << Record->isUnion();
5422           else {
5423             // This is a nested type declaration.
5424             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5425               << Record->isUnion();
5426             Invalid = true;
5427           }
5428         } else {
5429           // This is an anonymous type definition within another anonymous type.
5430           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5431           // not part of standard C++.
5432           Diag(MemRecord->getLocation(),
5433                diag::ext_anonymous_record_with_anonymous_type)
5434             << Record->isUnion();
5435         }
5436       } else if (isa<AccessSpecDecl>(Mem)) {
5437         // Any access specifier is fine.
5438       } else if (isa<StaticAssertDecl>(Mem)) {
5439         // In C++1z, static_assert declarations are also fine.
5440       } else {
5441         // We have something that isn't a non-static data
5442         // member. Complain about it.
5443         unsigned DK = diag::err_anonymous_record_bad_member;
5444         if (isa<TypeDecl>(Mem))
5445           DK = diag::err_anonymous_record_with_type;
5446         else if (isa<FunctionDecl>(Mem))
5447           DK = diag::err_anonymous_record_with_function;
5448         else if (isa<VarDecl>(Mem))
5449           DK = diag::err_anonymous_record_with_static;
5450 
5451         // Visual C++ allows type definition in anonymous struct or union.
5452         if (getLangOpts().MicrosoftExt &&
5453             DK == diag::err_anonymous_record_with_type)
5454           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5455             << Record->isUnion();
5456         else {
5457           Diag(Mem->getLocation(), DK) << Record->isUnion();
5458           Invalid = true;
5459         }
5460       }
5461     }
5462 
5463     // C++11 [class.union]p8 (DR1460):
5464     //   At most one variant member of a union may have a
5465     //   brace-or-equal-initializer.
5466     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5467         Owner->isRecord())
5468       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5469                                 cast<CXXRecordDecl>(Record));
5470   }
5471 
5472   if (!Record->isUnion() && !Owner->isRecord()) {
5473     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5474       << getLangOpts().CPlusPlus;
5475     Invalid = true;
5476   }
5477 
5478   // C++ [dcl.dcl]p3:
5479   //   [If there are no declarators], and except for the declaration of an
5480   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5481   //   names into the program
5482   // C++ [class.mem]p2:
5483   //   each such member-declaration shall either declare at least one member
5484   //   name of the class or declare at least one unnamed bit-field
5485   //
5486   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5487   if (getLangOpts().CPlusPlus && Record->field_empty())
5488     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5489 
5490   // Mock up a declarator.
5491   Declarator Dc(DS, DeclaratorContext::Member);
5492   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5493   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5494 
5495   // Create a declaration for this anonymous struct/union.
5496   NamedDecl *Anon = nullptr;
5497   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5498     Anon = FieldDecl::Create(
5499         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5500         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5501         /*BitWidth=*/nullptr, /*Mutable=*/false,
5502         /*InitStyle=*/ICIS_NoInit);
5503     Anon->setAccess(AS);
5504     ProcessDeclAttributes(S, Anon, Dc);
5505 
5506     if (getLangOpts().CPlusPlus)
5507       FieldCollector->Add(cast<FieldDecl>(Anon));
5508   } else {
5509     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5510     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5511     if (SCSpec == DeclSpec::SCS_mutable) {
5512       // mutable can only appear on non-static class members, so it's always
5513       // an error here
5514       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5515       Invalid = true;
5516       SC = SC_None;
5517     }
5518 
5519     assert(DS.getAttributes().empty() && "No attribute expected");
5520     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5521                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5522                            Context.getTypeDeclType(Record), TInfo, SC);
5523 
5524     // Default-initialize the implicit variable. This initialization will be
5525     // trivial in almost all cases, except if a union member has an in-class
5526     // initializer:
5527     //   union { int n = 0; };
5528     ActOnUninitializedDecl(Anon);
5529   }
5530   Anon->setImplicit();
5531 
5532   // Mark this as an anonymous struct/union type.
5533   Record->setAnonymousStructOrUnion(true);
5534 
5535   // Add the anonymous struct/union object to the current
5536   // context. We'll be referencing this object when we refer to one of
5537   // its members.
5538   Owner->addDecl(Anon);
5539 
5540   // Inject the members of the anonymous struct/union into the owning
5541   // context and into the identifier resolver chain for name lookup
5542   // purposes.
5543   SmallVector<NamedDecl*, 2> Chain;
5544   Chain.push_back(Anon);
5545 
5546   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5547     Invalid = true;
5548 
5549   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5550     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5551       MangleNumberingContext *MCtx;
5552       Decl *ManglingContextDecl;
5553       std::tie(MCtx, ManglingContextDecl) =
5554           getCurrentMangleNumberContext(NewVD->getDeclContext());
5555       if (MCtx) {
5556         Context.setManglingNumber(
5557             NewVD, MCtx->getManglingNumber(
5558                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5559         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5560       }
5561     }
5562   }
5563 
5564   if (Invalid)
5565     Anon->setInvalidDecl();
5566 
5567   return Anon;
5568 }
5569 
5570 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5571 /// Microsoft C anonymous structure.
5572 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5573 /// Example:
5574 ///
5575 /// struct A { int a; };
5576 /// struct B { struct A; int b; };
5577 ///
5578 /// void foo() {
5579 ///   B var;
5580 ///   var.a = 3;
5581 /// }
5582 ///
5583 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5584                                            RecordDecl *Record) {
5585   assert(Record && "expected a record!");
5586 
5587   // Mock up a declarator.
5588   Declarator Dc(DS, DeclaratorContext::TypeName);
5589   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5590   assert(TInfo && "couldn't build declarator info for anonymous struct");
5591 
5592   auto *ParentDecl = cast<RecordDecl>(CurContext);
5593   QualType RecTy = Context.getTypeDeclType(Record);
5594 
5595   // Create a declaration for this anonymous struct.
5596   NamedDecl *Anon =
5597       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5598                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5599                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5600                         /*InitStyle=*/ICIS_NoInit);
5601   Anon->setImplicit();
5602 
5603   // Add the anonymous struct object to the current context.
5604   CurContext->addDecl(Anon);
5605 
5606   // Inject the members of the anonymous struct into the current
5607   // context and into the identifier resolver chain for name lookup
5608   // purposes.
5609   SmallVector<NamedDecl*, 2> Chain;
5610   Chain.push_back(Anon);
5611 
5612   RecordDecl *RecordDef = Record->getDefinition();
5613   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5614                                diag::err_field_incomplete_or_sizeless) ||
5615       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5616                                           AS_none, Chain)) {
5617     Anon->setInvalidDecl();
5618     ParentDecl->setInvalidDecl();
5619   }
5620 
5621   return Anon;
5622 }
5623 
5624 /// GetNameForDeclarator - Determine the full declaration name for the
5625 /// given Declarator.
5626 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5627   return GetNameFromUnqualifiedId(D.getName());
5628 }
5629 
5630 /// Retrieves the declaration name from a parsed unqualified-id.
5631 DeclarationNameInfo
5632 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5633   DeclarationNameInfo NameInfo;
5634   NameInfo.setLoc(Name.StartLocation);
5635 
5636   switch (Name.getKind()) {
5637 
5638   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5639   case UnqualifiedIdKind::IK_Identifier:
5640     NameInfo.setName(Name.Identifier);
5641     return NameInfo;
5642 
5643   case UnqualifiedIdKind::IK_DeductionGuideName: {
5644     // C++ [temp.deduct.guide]p3:
5645     //   The simple-template-id shall name a class template specialization.
5646     //   The template-name shall be the same identifier as the template-name
5647     //   of the simple-template-id.
5648     // These together intend to imply that the template-name shall name a
5649     // class template.
5650     // FIXME: template<typename T> struct X {};
5651     //        template<typename T> using Y = X<T>;
5652     //        Y(int) -> Y<int>;
5653     //   satisfies these rules but does not name a class template.
5654     TemplateName TN = Name.TemplateName.get().get();
5655     auto *Template = TN.getAsTemplateDecl();
5656     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5657       Diag(Name.StartLocation,
5658            diag::err_deduction_guide_name_not_class_template)
5659         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5660       if (Template)
5661         Diag(Template->getLocation(), diag::note_template_decl_here);
5662       return DeclarationNameInfo();
5663     }
5664 
5665     NameInfo.setName(
5666         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5667     return NameInfo;
5668   }
5669 
5670   case UnqualifiedIdKind::IK_OperatorFunctionId:
5671     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5672                                            Name.OperatorFunctionId.Operator));
5673     NameInfo.setCXXOperatorNameRange(SourceRange(
5674         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5675     return NameInfo;
5676 
5677   case UnqualifiedIdKind::IK_LiteralOperatorId:
5678     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5679                                                            Name.Identifier));
5680     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5681     return NameInfo;
5682 
5683   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5684     TypeSourceInfo *TInfo;
5685     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5686     if (Ty.isNull())
5687       return DeclarationNameInfo();
5688     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5689                                                Context.getCanonicalType(Ty)));
5690     NameInfo.setNamedTypeInfo(TInfo);
5691     return NameInfo;
5692   }
5693 
5694   case UnqualifiedIdKind::IK_ConstructorName: {
5695     TypeSourceInfo *TInfo;
5696     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5697     if (Ty.isNull())
5698       return DeclarationNameInfo();
5699     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5700                                               Context.getCanonicalType(Ty)));
5701     NameInfo.setNamedTypeInfo(TInfo);
5702     return NameInfo;
5703   }
5704 
5705   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5706     // In well-formed code, we can only have a constructor
5707     // template-id that refers to the current context, so go there
5708     // to find the actual type being constructed.
5709     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5710     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5711       return DeclarationNameInfo();
5712 
5713     // Determine the type of the class being constructed.
5714     QualType CurClassType = Context.getTypeDeclType(CurClass);
5715 
5716     // FIXME: Check two things: that the template-id names the same type as
5717     // CurClassType, and that the template-id does not occur when the name
5718     // was qualified.
5719 
5720     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5721                                     Context.getCanonicalType(CurClassType)));
5722     // FIXME: should we retrieve TypeSourceInfo?
5723     NameInfo.setNamedTypeInfo(nullptr);
5724     return NameInfo;
5725   }
5726 
5727   case UnqualifiedIdKind::IK_DestructorName: {
5728     TypeSourceInfo *TInfo;
5729     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5730     if (Ty.isNull())
5731       return DeclarationNameInfo();
5732     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5733                                               Context.getCanonicalType(Ty)));
5734     NameInfo.setNamedTypeInfo(TInfo);
5735     return NameInfo;
5736   }
5737 
5738   case UnqualifiedIdKind::IK_TemplateId: {
5739     TemplateName TName = Name.TemplateId->Template.get();
5740     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5741     return Context.getNameForTemplate(TName, TNameLoc);
5742   }
5743 
5744   } // switch (Name.getKind())
5745 
5746   llvm_unreachable("Unknown name kind");
5747 }
5748 
5749 static QualType getCoreType(QualType Ty) {
5750   do {
5751     if (Ty->isPointerType() || Ty->isReferenceType())
5752       Ty = Ty->getPointeeType();
5753     else if (Ty->isArrayType())
5754       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5755     else
5756       return Ty.withoutLocalFastQualifiers();
5757   } while (true);
5758 }
5759 
5760 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5761 /// and Definition have "nearly" matching parameters. This heuristic is
5762 /// used to improve diagnostics in the case where an out-of-line function
5763 /// definition doesn't match any declaration within the class or namespace.
5764 /// Also sets Params to the list of indices to the parameters that differ
5765 /// between the declaration and the definition. If hasSimilarParameters
5766 /// returns true and Params is empty, then all of the parameters match.
5767 static bool hasSimilarParameters(ASTContext &Context,
5768                                      FunctionDecl *Declaration,
5769                                      FunctionDecl *Definition,
5770                                      SmallVectorImpl<unsigned> &Params) {
5771   Params.clear();
5772   if (Declaration->param_size() != Definition->param_size())
5773     return false;
5774   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5775     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5776     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5777 
5778     // The parameter types are identical
5779     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5780       continue;
5781 
5782     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5783     QualType DefParamBaseTy = getCoreType(DefParamTy);
5784     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5785     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5786 
5787     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5788         (DeclTyName && DeclTyName == DefTyName))
5789       Params.push_back(Idx);
5790     else  // The two parameters aren't even close
5791       return false;
5792   }
5793 
5794   return true;
5795 }
5796 
5797 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5798 /// declarator needs to be rebuilt in the current instantiation.
5799 /// Any bits of declarator which appear before the name are valid for
5800 /// consideration here.  That's specifically the type in the decl spec
5801 /// and the base type in any member-pointer chunks.
5802 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5803                                                     DeclarationName Name) {
5804   // The types we specifically need to rebuild are:
5805   //   - typenames, typeofs, and decltypes
5806   //   - types which will become injected class names
5807   // Of course, we also need to rebuild any type referencing such a
5808   // type.  It's safest to just say "dependent", but we call out a
5809   // few cases here.
5810 
5811   DeclSpec &DS = D.getMutableDeclSpec();
5812   switch (DS.getTypeSpecType()) {
5813   case DeclSpec::TST_typename:
5814   case DeclSpec::TST_typeofType:
5815   case DeclSpec::TST_underlyingType:
5816   case DeclSpec::TST_atomic: {
5817     // Grab the type from the parser.
5818     TypeSourceInfo *TSI = nullptr;
5819     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5820     if (T.isNull() || !T->isInstantiationDependentType()) break;
5821 
5822     // Make sure there's a type source info.  This isn't really much
5823     // of a waste; most dependent types should have type source info
5824     // attached already.
5825     if (!TSI)
5826       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5827 
5828     // Rebuild the type in the current instantiation.
5829     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5830     if (!TSI) return true;
5831 
5832     // Store the new type back in the decl spec.
5833     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5834     DS.UpdateTypeRep(LocType);
5835     break;
5836   }
5837 
5838   case DeclSpec::TST_decltype:
5839   case DeclSpec::TST_typeofExpr: {
5840     Expr *E = DS.getRepAsExpr();
5841     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5842     if (Result.isInvalid()) return true;
5843     DS.UpdateExprRep(Result.get());
5844     break;
5845   }
5846 
5847   default:
5848     // Nothing to do for these decl specs.
5849     break;
5850   }
5851 
5852   // It doesn't matter what order we do this in.
5853   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5854     DeclaratorChunk &Chunk = D.getTypeObject(I);
5855 
5856     // The only type information in the declarator which can come
5857     // before the declaration name is the base type of a member
5858     // pointer.
5859     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5860       continue;
5861 
5862     // Rebuild the scope specifier in-place.
5863     CXXScopeSpec &SS = Chunk.Mem.Scope();
5864     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5865       return true;
5866   }
5867 
5868   return false;
5869 }
5870 
5871 /// Returns true if the declaration is declared in a system header or from a
5872 /// system macro.
5873 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5874   return SM.isInSystemHeader(D->getLocation()) ||
5875          SM.isInSystemMacro(D->getLocation());
5876 }
5877 
5878 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5879   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5880   // of system decl.
5881   if (D->getPreviousDecl() || D->isImplicit())
5882     return;
5883   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5884   if (Status != ReservedIdentifierStatus::NotReserved &&
5885       !isFromSystemHeader(Context.getSourceManager(), D)) {
5886     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5887         << D << static_cast<int>(Status);
5888   }
5889 }
5890 
5891 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5892   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5893   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5894 
5895   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5896       Dcl && Dcl->getDeclContext()->isFileContext())
5897     Dcl->setTopLevelDeclInObjCContainer();
5898 
5899   return Dcl;
5900 }
5901 
5902 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5903 ///   If T is the name of a class, then each of the following shall have a
5904 ///   name different from T:
5905 ///     - every static data member of class T;
5906 ///     - every member function of class T
5907 ///     - every member of class T that is itself a type;
5908 /// \returns true if the declaration name violates these rules.
5909 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5910                                    DeclarationNameInfo NameInfo) {
5911   DeclarationName Name = NameInfo.getName();
5912 
5913   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5914   while (Record && Record->isAnonymousStructOrUnion())
5915     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5916   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5917     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5918     return true;
5919   }
5920 
5921   return false;
5922 }
5923 
5924 /// Diagnose a declaration whose declarator-id has the given
5925 /// nested-name-specifier.
5926 ///
5927 /// \param SS The nested-name-specifier of the declarator-id.
5928 ///
5929 /// \param DC The declaration context to which the nested-name-specifier
5930 /// resolves.
5931 ///
5932 /// \param Name The name of the entity being declared.
5933 ///
5934 /// \param Loc The location of the name of the entity being declared.
5935 ///
5936 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5937 /// we're declaring an explicit / partial specialization / instantiation.
5938 ///
5939 /// \returns true if we cannot safely recover from this error, false otherwise.
5940 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5941                                         DeclarationName Name,
5942                                         SourceLocation Loc, bool IsTemplateId) {
5943   DeclContext *Cur = CurContext;
5944   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5945     Cur = Cur->getParent();
5946 
5947   // If the user provided a superfluous scope specifier that refers back to the
5948   // class in which the entity is already declared, diagnose and ignore it.
5949   //
5950   // class X {
5951   //   void X::f();
5952   // };
5953   //
5954   // Note, it was once ill-formed to give redundant qualification in all
5955   // contexts, but that rule was removed by DR482.
5956   if (Cur->Equals(DC)) {
5957     if (Cur->isRecord()) {
5958       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5959                                       : diag::err_member_extra_qualification)
5960         << Name << FixItHint::CreateRemoval(SS.getRange());
5961       SS.clear();
5962     } else {
5963       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5964     }
5965     return false;
5966   }
5967 
5968   // Check whether the qualifying scope encloses the scope of the original
5969   // declaration. For a template-id, we perform the checks in
5970   // CheckTemplateSpecializationScope.
5971   if (!Cur->Encloses(DC) && !IsTemplateId) {
5972     if (Cur->isRecord())
5973       Diag(Loc, diag::err_member_qualification)
5974         << Name << SS.getRange();
5975     else if (isa<TranslationUnitDecl>(DC))
5976       Diag(Loc, diag::err_invalid_declarator_global_scope)
5977         << Name << SS.getRange();
5978     else if (isa<FunctionDecl>(Cur))
5979       Diag(Loc, diag::err_invalid_declarator_in_function)
5980         << Name << SS.getRange();
5981     else if (isa<BlockDecl>(Cur))
5982       Diag(Loc, diag::err_invalid_declarator_in_block)
5983         << Name << SS.getRange();
5984     else if (isa<ExportDecl>(Cur)) {
5985       if (!isa<NamespaceDecl>(DC))
5986         Diag(Loc, diag::err_export_non_namespace_scope_name)
5987             << Name << SS.getRange();
5988       else
5989         // The cases that DC is not NamespaceDecl should be handled in
5990         // CheckRedeclarationExported.
5991         return false;
5992     } else
5993       Diag(Loc, diag::err_invalid_declarator_scope)
5994       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5995 
5996     return true;
5997   }
5998 
5999   if (Cur->isRecord()) {
6000     // Cannot qualify members within a class.
6001     Diag(Loc, diag::err_member_qualification)
6002       << Name << SS.getRange();
6003     SS.clear();
6004 
6005     // C++ constructors and destructors with incorrect scopes can break
6006     // our AST invariants by having the wrong underlying types. If
6007     // that's the case, then drop this declaration entirely.
6008     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6009          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6010         !Context.hasSameType(Name.getCXXNameType(),
6011                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6012       return true;
6013 
6014     return false;
6015   }
6016 
6017   // C++11 [dcl.meaning]p1:
6018   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6019   //   not begin with a decltype-specifer"
6020   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6021   while (SpecLoc.getPrefix())
6022     SpecLoc = SpecLoc.getPrefix();
6023   if (isa_and_nonnull<DecltypeType>(
6024           SpecLoc.getNestedNameSpecifier()->getAsType()))
6025     Diag(Loc, diag::err_decltype_in_declarator)
6026       << SpecLoc.getTypeLoc().getSourceRange();
6027 
6028   return false;
6029 }
6030 
6031 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6032                                   MultiTemplateParamsArg TemplateParamLists) {
6033   // TODO: consider using NameInfo for diagnostic.
6034   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6035   DeclarationName Name = NameInfo.getName();
6036 
6037   // All of these full declarators require an identifier.  If it doesn't have
6038   // one, the ParsedFreeStandingDeclSpec action should be used.
6039   if (D.isDecompositionDeclarator()) {
6040     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6041   } else if (!Name) {
6042     if (!D.isInvalidType())  // Reject this if we think it is valid.
6043       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6044           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6045     return nullptr;
6046   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6047     return nullptr;
6048 
6049   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6050   // we find one that is.
6051   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6052          (S->getFlags() & Scope::TemplateParamScope) != 0)
6053     S = S->getParent();
6054 
6055   DeclContext *DC = CurContext;
6056   if (D.getCXXScopeSpec().isInvalid())
6057     D.setInvalidType();
6058   else if (D.getCXXScopeSpec().isSet()) {
6059     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6060                                         UPPC_DeclarationQualifier))
6061       return nullptr;
6062 
6063     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6064     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6065     if (!DC || isa<EnumDecl>(DC)) {
6066       // If we could not compute the declaration context, it's because the
6067       // declaration context is dependent but does not refer to a class,
6068       // class template, or class template partial specialization. Complain
6069       // and return early, to avoid the coming semantic disaster.
6070       Diag(D.getIdentifierLoc(),
6071            diag::err_template_qualified_declarator_no_match)
6072         << D.getCXXScopeSpec().getScopeRep()
6073         << D.getCXXScopeSpec().getRange();
6074       return nullptr;
6075     }
6076     bool IsDependentContext = DC->isDependentContext();
6077 
6078     if (!IsDependentContext &&
6079         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6080       return nullptr;
6081 
6082     // If a class is incomplete, do not parse entities inside it.
6083     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6084       Diag(D.getIdentifierLoc(),
6085            diag::err_member_def_undefined_record)
6086         << Name << DC << D.getCXXScopeSpec().getRange();
6087       return nullptr;
6088     }
6089     if (!D.getDeclSpec().isFriendSpecified()) {
6090       if (diagnoseQualifiedDeclaration(
6091               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6092               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6093         if (DC->isRecord())
6094           return nullptr;
6095 
6096         D.setInvalidType();
6097       }
6098     }
6099 
6100     // Check whether we need to rebuild the type of the given
6101     // declaration in the current instantiation.
6102     if (EnteringContext && IsDependentContext &&
6103         TemplateParamLists.size() != 0) {
6104       ContextRAII SavedContext(*this, DC);
6105       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6106         D.setInvalidType();
6107     }
6108   }
6109 
6110   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6111   QualType R = TInfo->getType();
6112 
6113   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6114                                       UPPC_DeclarationType))
6115     D.setInvalidType();
6116 
6117   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6118                         forRedeclarationInCurContext());
6119 
6120   // See if this is a redefinition of a variable in the same scope.
6121   if (!D.getCXXScopeSpec().isSet()) {
6122     bool IsLinkageLookup = false;
6123     bool CreateBuiltins = false;
6124 
6125     // If the declaration we're planning to build will be a function
6126     // or object with linkage, then look for another declaration with
6127     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6128     //
6129     // If the declaration we're planning to build will be declared with
6130     // external linkage in the translation unit, create any builtin with
6131     // the same name.
6132     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6133       /* Do nothing*/;
6134     else if (CurContext->isFunctionOrMethod() &&
6135              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6136               R->isFunctionType())) {
6137       IsLinkageLookup = true;
6138       CreateBuiltins =
6139           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6140     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6141                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6142       CreateBuiltins = true;
6143 
6144     if (IsLinkageLookup) {
6145       Previous.clear(LookupRedeclarationWithLinkage);
6146       Previous.setRedeclarationKind(ForExternalRedeclaration);
6147     }
6148 
6149     LookupName(Previous, S, CreateBuiltins);
6150   } else { // Something like "int foo::x;"
6151     LookupQualifiedName(Previous, DC);
6152 
6153     // C++ [dcl.meaning]p1:
6154     //   When the declarator-id is qualified, the declaration shall refer to a
6155     //  previously declared member of the class or namespace to which the
6156     //  qualifier refers (or, in the case of a namespace, of an element of the
6157     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6158     //  thereof; [...]
6159     //
6160     // Note that we already checked the context above, and that we do not have
6161     // enough information to make sure that Previous contains the declaration
6162     // we want to match. For example, given:
6163     //
6164     //   class X {
6165     //     void f();
6166     //     void f(float);
6167     //   };
6168     //
6169     //   void X::f(int) { } // ill-formed
6170     //
6171     // In this case, Previous will point to the overload set
6172     // containing the two f's declared in X, but neither of them
6173     // matches.
6174 
6175     // C++ [dcl.meaning]p1:
6176     //   [...] the member shall not merely have been introduced by a
6177     //   using-declaration in the scope of the class or namespace nominated by
6178     //   the nested-name-specifier of the declarator-id.
6179     RemoveUsingDecls(Previous);
6180   }
6181 
6182   if (Previous.isSingleResult() &&
6183       Previous.getFoundDecl()->isTemplateParameter()) {
6184     // Maybe we will complain about the shadowed template parameter.
6185     if (!D.isInvalidType())
6186       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6187                                       Previous.getFoundDecl());
6188 
6189     // Just pretend that we didn't see the previous declaration.
6190     Previous.clear();
6191   }
6192 
6193   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6194     // Forget that the previous declaration is the injected-class-name.
6195     Previous.clear();
6196 
6197   // In C++, the previous declaration we find might be a tag type
6198   // (class or enum). In this case, the new declaration will hide the
6199   // tag type. Note that this applies to functions, function templates, and
6200   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6201   if (Previous.isSingleTagDecl() &&
6202       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6203       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6204     Previous.clear();
6205 
6206   // Check that there are no default arguments other than in the parameters
6207   // of a function declaration (C++ only).
6208   if (getLangOpts().CPlusPlus)
6209     CheckExtraCXXDefaultArguments(D);
6210 
6211   NamedDecl *New;
6212 
6213   bool AddToScope = true;
6214   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6215     if (TemplateParamLists.size()) {
6216       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6217       return nullptr;
6218     }
6219 
6220     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6221   } else if (R->isFunctionType()) {
6222     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6223                                   TemplateParamLists,
6224                                   AddToScope);
6225   } else {
6226     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6227                                   AddToScope);
6228   }
6229 
6230   if (!New)
6231     return nullptr;
6232 
6233   // If this has an identifier and is not a function template specialization,
6234   // add it to the scope stack.
6235   if (New->getDeclName() && AddToScope)
6236     PushOnScopeChains(New, S);
6237 
6238   if (isInOpenMPDeclareTargetContext())
6239     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6240 
6241   return New;
6242 }
6243 
6244 /// Helper method to turn variable array types into constant array
6245 /// types in certain situations which would otherwise be errors (for
6246 /// GCC compatibility).
6247 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6248                                                     ASTContext &Context,
6249                                                     bool &SizeIsNegative,
6250                                                     llvm::APSInt &Oversized) {
6251   // This method tries to turn a variable array into a constant
6252   // array even when the size isn't an ICE.  This is necessary
6253   // for compatibility with code that depends on gcc's buggy
6254   // constant expression folding, like struct {char x[(int)(char*)2];}
6255   SizeIsNegative = false;
6256   Oversized = 0;
6257 
6258   if (T->isDependentType())
6259     return QualType();
6260 
6261   QualifierCollector Qs;
6262   const Type *Ty = Qs.strip(T);
6263 
6264   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6265     QualType Pointee = PTy->getPointeeType();
6266     QualType FixedType =
6267         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6268                                             Oversized);
6269     if (FixedType.isNull()) return FixedType;
6270     FixedType = Context.getPointerType(FixedType);
6271     return Qs.apply(Context, FixedType);
6272   }
6273   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6274     QualType Inner = PTy->getInnerType();
6275     QualType FixedType =
6276         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6277                                             Oversized);
6278     if (FixedType.isNull()) return FixedType;
6279     FixedType = Context.getParenType(FixedType);
6280     return Qs.apply(Context, FixedType);
6281   }
6282 
6283   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6284   if (!VLATy)
6285     return QualType();
6286 
6287   QualType ElemTy = VLATy->getElementType();
6288   if (ElemTy->isVariablyModifiedType()) {
6289     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6290                                                  SizeIsNegative, Oversized);
6291     if (ElemTy.isNull())
6292       return QualType();
6293   }
6294 
6295   Expr::EvalResult Result;
6296   if (!VLATy->getSizeExpr() ||
6297       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6298     return QualType();
6299 
6300   llvm::APSInt Res = Result.Val.getInt();
6301 
6302   // Check whether the array size is negative.
6303   if (Res.isSigned() && Res.isNegative()) {
6304     SizeIsNegative = true;
6305     return QualType();
6306   }
6307 
6308   // Check whether the array is too large to be addressed.
6309   unsigned ActiveSizeBits =
6310       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6311        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6312           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6313           : Res.getActiveBits();
6314   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6315     Oversized = Res;
6316     return QualType();
6317   }
6318 
6319   QualType FoldedArrayType = Context.getConstantArrayType(
6320       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6321   return Qs.apply(Context, FoldedArrayType);
6322 }
6323 
6324 static void
6325 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6326   SrcTL = SrcTL.getUnqualifiedLoc();
6327   DstTL = DstTL.getUnqualifiedLoc();
6328   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6329     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6330     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6331                                       DstPTL.getPointeeLoc());
6332     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6333     return;
6334   }
6335   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6336     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6337     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6338                                       DstPTL.getInnerLoc());
6339     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6340     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6341     return;
6342   }
6343   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6344   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6345   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6346   TypeLoc DstElemTL = DstATL.getElementLoc();
6347   if (VariableArrayTypeLoc SrcElemATL =
6348           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6349     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6350     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6351   } else {
6352     DstElemTL.initializeFullCopy(SrcElemTL);
6353   }
6354   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6355   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6356   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6357 }
6358 
6359 /// Helper method to turn variable array types into constant array
6360 /// types in certain situations which would otherwise be errors (for
6361 /// GCC compatibility).
6362 static TypeSourceInfo*
6363 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6364                                               ASTContext &Context,
6365                                               bool &SizeIsNegative,
6366                                               llvm::APSInt &Oversized) {
6367   QualType FixedTy
6368     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6369                                           SizeIsNegative, Oversized);
6370   if (FixedTy.isNull())
6371     return nullptr;
6372   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6373   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6374                                     FixedTInfo->getTypeLoc());
6375   return FixedTInfo;
6376 }
6377 
6378 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6379 /// true if we were successful.
6380 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6381                                            QualType &T, SourceLocation Loc,
6382                                            unsigned FailedFoldDiagID) {
6383   bool SizeIsNegative;
6384   llvm::APSInt Oversized;
6385   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6386       TInfo, Context, SizeIsNegative, Oversized);
6387   if (FixedTInfo) {
6388     Diag(Loc, diag::ext_vla_folded_to_constant);
6389     TInfo = FixedTInfo;
6390     T = FixedTInfo->getType();
6391     return true;
6392   }
6393 
6394   if (SizeIsNegative)
6395     Diag(Loc, diag::err_typecheck_negative_array_size);
6396   else if (Oversized.getBoolValue())
6397     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6398   else if (FailedFoldDiagID)
6399     Diag(Loc, FailedFoldDiagID);
6400   return false;
6401 }
6402 
6403 /// Register the given locally-scoped extern "C" declaration so
6404 /// that it can be found later for redeclarations. We include any extern "C"
6405 /// declaration that is not visible in the translation unit here, not just
6406 /// function-scope declarations.
6407 void
6408 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6409   if (!getLangOpts().CPlusPlus &&
6410       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6411     // Don't need to track declarations in the TU in C.
6412     return;
6413 
6414   // Note that we have a locally-scoped external with this name.
6415   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6416 }
6417 
6418 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6419   // FIXME: We can have multiple results via __attribute__((overloadable)).
6420   auto Result = Context.getExternCContextDecl()->lookup(Name);
6421   return Result.empty() ? nullptr : *Result.begin();
6422 }
6423 
6424 /// Diagnose function specifiers on a declaration of an identifier that
6425 /// does not identify a function.
6426 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6427   // FIXME: We should probably indicate the identifier in question to avoid
6428   // confusion for constructs like "virtual int a(), b;"
6429   if (DS.isVirtualSpecified())
6430     Diag(DS.getVirtualSpecLoc(),
6431          diag::err_virtual_non_function);
6432 
6433   if (DS.hasExplicitSpecifier())
6434     Diag(DS.getExplicitSpecLoc(),
6435          diag::err_explicit_non_function);
6436 
6437   if (DS.isNoreturnSpecified())
6438     Diag(DS.getNoreturnSpecLoc(),
6439          diag::err_noreturn_non_function);
6440 }
6441 
6442 NamedDecl*
6443 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6444                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6445   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6446   if (D.getCXXScopeSpec().isSet()) {
6447     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6448       << D.getCXXScopeSpec().getRange();
6449     D.setInvalidType();
6450     // Pretend we didn't see the scope specifier.
6451     DC = CurContext;
6452     Previous.clear();
6453   }
6454 
6455   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6456 
6457   if (D.getDeclSpec().isInlineSpecified())
6458     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6459         << getLangOpts().CPlusPlus17;
6460   if (D.getDeclSpec().hasConstexprSpecifier())
6461     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6462         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6463 
6464   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6465     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6466       Diag(D.getName().StartLocation,
6467            diag::err_deduction_guide_invalid_specifier)
6468           << "typedef";
6469     else
6470       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6471           << D.getName().getSourceRange();
6472     return nullptr;
6473   }
6474 
6475   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6476   if (!NewTD) return nullptr;
6477 
6478   // Handle attributes prior to checking for duplicates in MergeVarDecl
6479   ProcessDeclAttributes(S, NewTD, D);
6480 
6481   CheckTypedefForVariablyModifiedType(S, NewTD);
6482 
6483   bool Redeclaration = D.isRedeclaration();
6484   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6485   D.setRedeclaration(Redeclaration);
6486   return ND;
6487 }
6488 
6489 void
6490 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6491   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6492   // then it shall have block scope.
6493   // Note that variably modified types must be fixed before merging the decl so
6494   // that redeclarations will match.
6495   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6496   QualType T = TInfo->getType();
6497   if (T->isVariablyModifiedType()) {
6498     setFunctionHasBranchProtectedScope();
6499 
6500     if (S->getFnParent() == nullptr) {
6501       bool SizeIsNegative;
6502       llvm::APSInt Oversized;
6503       TypeSourceInfo *FixedTInfo =
6504         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6505                                                       SizeIsNegative,
6506                                                       Oversized);
6507       if (FixedTInfo) {
6508         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6509         NewTD->setTypeSourceInfo(FixedTInfo);
6510       } else {
6511         if (SizeIsNegative)
6512           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6513         else if (T->isVariableArrayType())
6514           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6515         else if (Oversized.getBoolValue())
6516           Diag(NewTD->getLocation(), diag::err_array_too_large)
6517             << toString(Oversized, 10);
6518         else
6519           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6520         NewTD->setInvalidDecl();
6521       }
6522     }
6523   }
6524 }
6525 
6526 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6527 /// declares a typedef-name, either using the 'typedef' type specifier or via
6528 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6529 NamedDecl*
6530 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6531                            LookupResult &Previous, bool &Redeclaration) {
6532 
6533   // Find the shadowed declaration before filtering for scope.
6534   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6535 
6536   // Merge the decl with the existing one if appropriate. If the decl is
6537   // in an outer scope, it isn't the same thing.
6538   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6539                        /*AllowInlineNamespace*/false);
6540   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6541   if (!Previous.empty()) {
6542     Redeclaration = true;
6543     MergeTypedefNameDecl(S, NewTD, Previous);
6544   } else {
6545     inferGslPointerAttribute(NewTD);
6546   }
6547 
6548   if (ShadowedDecl && !Redeclaration)
6549     CheckShadow(NewTD, ShadowedDecl, Previous);
6550 
6551   // If this is the C FILE type, notify the AST context.
6552   if (IdentifierInfo *II = NewTD->getIdentifier())
6553     if (!NewTD->isInvalidDecl() &&
6554         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6555       if (II->isStr("FILE"))
6556         Context.setFILEDecl(NewTD);
6557       else if (II->isStr("jmp_buf"))
6558         Context.setjmp_bufDecl(NewTD);
6559       else if (II->isStr("sigjmp_buf"))
6560         Context.setsigjmp_bufDecl(NewTD);
6561       else if (II->isStr("ucontext_t"))
6562         Context.setucontext_tDecl(NewTD);
6563     }
6564 
6565   return NewTD;
6566 }
6567 
6568 /// Determines whether the given declaration is an out-of-scope
6569 /// previous declaration.
6570 ///
6571 /// This routine should be invoked when name lookup has found a
6572 /// previous declaration (PrevDecl) that is not in the scope where a
6573 /// new declaration by the same name is being introduced. If the new
6574 /// declaration occurs in a local scope, previous declarations with
6575 /// linkage may still be considered previous declarations (C99
6576 /// 6.2.2p4-5, C++ [basic.link]p6).
6577 ///
6578 /// \param PrevDecl the previous declaration found by name
6579 /// lookup
6580 ///
6581 /// \param DC the context in which the new declaration is being
6582 /// declared.
6583 ///
6584 /// \returns true if PrevDecl is an out-of-scope previous declaration
6585 /// for a new delcaration with the same name.
6586 static bool
6587 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6588                                 ASTContext &Context) {
6589   if (!PrevDecl)
6590     return false;
6591 
6592   if (!PrevDecl->hasLinkage())
6593     return false;
6594 
6595   if (Context.getLangOpts().CPlusPlus) {
6596     // C++ [basic.link]p6:
6597     //   If there is a visible declaration of an entity with linkage
6598     //   having the same name and type, ignoring entities declared
6599     //   outside the innermost enclosing namespace scope, the block
6600     //   scope declaration declares that same entity and receives the
6601     //   linkage of the previous declaration.
6602     DeclContext *OuterContext = DC->getRedeclContext();
6603     if (!OuterContext->isFunctionOrMethod())
6604       // This rule only applies to block-scope declarations.
6605       return false;
6606 
6607     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6608     if (PrevOuterContext->isRecord())
6609       // We found a member function: ignore it.
6610       return false;
6611 
6612     // Find the innermost enclosing namespace for the new and
6613     // previous declarations.
6614     OuterContext = OuterContext->getEnclosingNamespaceContext();
6615     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6616 
6617     // The previous declaration is in a different namespace, so it
6618     // isn't the same function.
6619     if (!OuterContext->Equals(PrevOuterContext))
6620       return false;
6621   }
6622 
6623   return true;
6624 }
6625 
6626 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6627   CXXScopeSpec &SS = D.getCXXScopeSpec();
6628   if (!SS.isSet()) return;
6629   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6630 }
6631 
6632 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6633   QualType type = decl->getType();
6634   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6635   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6636     // Various kinds of declaration aren't allowed to be __autoreleasing.
6637     unsigned kind = -1U;
6638     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6639       if (var->hasAttr<BlocksAttr>())
6640         kind = 0; // __block
6641       else if (!var->hasLocalStorage())
6642         kind = 1; // global
6643     } else if (isa<ObjCIvarDecl>(decl)) {
6644       kind = 3; // ivar
6645     } else if (isa<FieldDecl>(decl)) {
6646       kind = 2; // field
6647     }
6648 
6649     if (kind != -1U) {
6650       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6651         << kind;
6652     }
6653   } else if (lifetime == Qualifiers::OCL_None) {
6654     // Try to infer lifetime.
6655     if (!type->isObjCLifetimeType())
6656       return false;
6657 
6658     lifetime = type->getObjCARCImplicitLifetime();
6659     type = Context.getLifetimeQualifiedType(type, lifetime);
6660     decl->setType(type);
6661   }
6662 
6663   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6664     // Thread-local variables cannot have lifetime.
6665     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6666         var->getTLSKind()) {
6667       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6668         << var->getType();
6669       return true;
6670     }
6671   }
6672 
6673   return false;
6674 }
6675 
6676 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6677   if (Decl->getType().hasAddressSpace())
6678     return;
6679   if (Decl->getType()->isDependentType())
6680     return;
6681   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6682     QualType Type = Var->getType();
6683     if (Type->isSamplerT() || Type->isVoidType())
6684       return;
6685     LangAS ImplAS = LangAS::opencl_private;
6686     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6687     // __opencl_c_program_scope_global_variables feature, the address space
6688     // for a variable at program scope or a static or extern variable inside
6689     // a function are inferred to be __global.
6690     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6691         Var->hasGlobalStorage())
6692       ImplAS = LangAS::opencl_global;
6693     // If the original type from a decayed type is an array type and that array
6694     // type has no address space yet, deduce it now.
6695     if (auto DT = dyn_cast<DecayedType>(Type)) {
6696       auto OrigTy = DT->getOriginalType();
6697       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6698         // Add the address space to the original array type and then propagate
6699         // that to the element type through `getAsArrayType`.
6700         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6701         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6702         // Re-generate the decayed type.
6703         Type = Context.getDecayedType(OrigTy);
6704       }
6705     }
6706     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6707     // Apply any qualifiers (including address space) from the array type to
6708     // the element type. This implements C99 6.7.3p8: "If the specification of
6709     // an array type includes any type qualifiers, the element type is so
6710     // qualified, not the array type."
6711     if (Type->isArrayType())
6712       Type = QualType(Context.getAsArrayType(Type), 0);
6713     Decl->setType(Type);
6714   }
6715 }
6716 
6717 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6718   // Ensure that an auto decl is deduced otherwise the checks below might cache
6719   // the wrong linkage.
6720   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6721 
6722   // 'weak' only applies to declarations with external linkage.
6723   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6724     if (!ND.isExternallyVisible()) {
6725       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6726       ND.dropAttr<WeakAttr>();
6727     }
6728   }
6729   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6730     if (ND.isExternallyVisible()) {
6731       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6732       ND.dropAttr<WeakRefAttr>();
6733       ND.dropAttr<AliasAttr>();
6734     }
6735   }
6736 
6737   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6738     if (VD->hasInit()) {
6739       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6740         assert(VD->isThisDeclarationADefinition() &&
6741                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6742         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6743         VD->dropAttr<AliasAttr>();
6744       }
6745     }
6746   }
6747 
6748   // 'selectany' only applies to externally visible variable declarations.
6749   // It does not apply to functions.
6750   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6751     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6752       S.Diag(Attr->getLocation(),
6753              diag::err_attribute_selectany_non_extern_data);
6754       ND.dropAttr<SelectAnyAttr>();
6755     }
6756   }
6757 
6758   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6759     auto *VD = dyn_cast<VarDecl>(&ND);
6760     bool IsAnonymousNS = false;
6761     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6762     if (VD) {
6763       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6764       while (NS && !IsAnonymousNS) {
6765         IsAnonymousNS = NS->isAnonymousNamespace();
6766         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6767       }
6768     }
6769     // dll attributes require external linkage. Static locals may have external
6770     // linkage but still cannot be explicitly imported or exported.
6771     // In Microsoft mode, a variable defined in anonymous namespace must have
6772     // external linkage in order to be exported.
6773     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6774     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6775         (!AnonNSInMicrosoftMode &&
6776          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6777       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6778         << &ND << Attr;
6779       ND.setInvalidDecl();
6780     }
6781   }
6782 
6783   // Check the attributes on the function type, if any.
6784   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6785     // Don't declare this variable in the second operand of the for-statement;
6786     // GCC miscompiles that by ending its lifetime before evaluating the
6787     // third operand. See gcc.gnu.org/PR86769.
6788     AttributedTypeLoc ATL;
6789     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6790          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6791          TL = ATL.getModifiedLoc()) {
6792       // The [[lifetimebound]] attribute can be applied to the implicit object
6793       // parameter of a non-static member function (other than a ctor or dtor)
6794       // by applying it to the function type.
6795       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6796         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6797         if (!MD || MD->isStatic()) {
6798           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6799               << !MD << A->getRange();
6800         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6801           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6802               << isa<CXXDestructorDecl>(MD) << A->getRange();
6803         }
6804       }
6805     }
6806   }
6807 }
6808 
6809 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6810                                            NamedDecl *NewDecl,
6811                                            bool IsSpecialization,
6812                                            bool IsDefinition) {
6813   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6814     return;
6815 
6816   bool IsTemplate = false;
6817   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6818     OldDecl = OldTD->getTemplatedDecl();
6819     IsTemplate = true;
6820     if (!IsSpecialization)
6821       IsDefinition = false;
6822   }
6823   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6824     NewDecl = NewTD->getTemplatedDecl();
6825     IsTemplate = true;
6826   }
6827 
6828   if (!OldDecl || !NewDecl)
6829     return;
6830 
6831   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6832   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6833   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6834   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6835 
6836   // dllimport and dllexport are inheritable attributes so we have to exclude
6837   // inherited attribute instances.
6838   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6839                     (NewExportAttr && !NewExportAttr->isInherited());
6840 
6841   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6842   // the only exception being explicit specializations.
6843   // Implicitly generated declarations are also excluded for now because there
6844   // is no other way to switch these to use dllimport or dllexport.
6845   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6846 
6847   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6848     // Allow with a warning for free functions and global variables.
6849     bool JustWarn = false;
6850     if (!OldDecl->isCXXClassMember()) {
6851       auto *VD = dyn_cast<VarDecl>(OldDecl);
6852       if (VD && !VD->getDescribedVarTemplate())
6853         JustWarn = true;
6854       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6855       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6856         JustWarn = true;
6857     }
6858 
6859     // We cannot change a declaration that's been used because IR has already
6860     // been emitted. Dllimported functions will still work though (modulo
6861     // address equality) as they can use the thunk.
6862     if (OldDecl->isUsed())
6863       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6864         JustWarn = false;
6865 
6866     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6867                                : diag::err_attribute_dll_redeclaration;
6868     S.Diag(NewDecl->getLocation(), DiagID)
6869         << NewDecl
6870         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6871     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6872     if (!JustWarn) {
6873       NewDecl->setInvalidDecl();
6874       return;
6875     }
6876   }
6877 
6878   // A redeclaration is not allowed to drop a dllimport attribute, the only
6879   // exceptions being inline function definitions (except for function
6880   // templates), local extern declarations, qualified friend declarations or
6881   // special MSVC extension: in the last case, the declaration is treated as if
6882   // it were marked dllexport.
6883   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6884   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6885   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6886     // Ignore static data because out-of-line definitions are diagnosed
6887     // separately.
6888     IsStaticDataMember = VD->isStaticDataMember();
6889     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6890                    VarDecl::DeclarationOnly;
6891   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6892     IsInline = FD->isInlined();
6893     IsQualifiedFriend = FD->getQualifier() &&
6894                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6895   }
6896 
6897   if (OldImportAttr && !HasNewAttr &&
6898       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6899       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6900     if (IsMicrosoftABI && IsDefinition) {
6901       S.Diag(NewDecl->getLocation(),
6902              diag::warn_redeclaration_without_import_attribute)
6903           << NewDecl;
6904       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6905       NewDecl->dropAttr<DLLImportAttr>();
6906       NewDecl->addAttr(
6907           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6908     } else {
6909       S.Diag(NewDecl->getLocation(),
6910              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6911           << NewDecl << OldImportAttr;
6912       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6913       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6914       OldDecl->dropAttr<DLLImportAttr>();
6915       NewDecl->dropAttr<DLLImportAttr>();
6916     }
6917   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6918     // In MinGW, seeing a function declared inline drops the dllimport
6919     // attribute.
6920     OldDecl->dropAttr<DLLImportAttr>();
6921     NewDecl->dropAttr<DLLImportAttr>();
6922     S.Diag(NewDecl->getLocation(),
6923            diag::warn_dllimport_dropped_from_inline_function)
6924         << NewDecl << OldImportAttr;
6925   }
6926 
6927   // A specialization of a class template member function is processed here
6928   // since it's a redeclaration. If the parent class is dllexport, the
6929   // specialization inherits that attribute. This doesn't happen automatically
6930   // since the parent class isn't instantiated until later.
6931   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6932     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6933         !NewImportAttr && !NewExportAttr) {
6934       if (const DLLExportAttr *ParentExportAttr =
6935               MD->getParent()->getAttr<DLLExportAttr>()) {
6936         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6937         NewAttr->setInherited(true);
6938         NewDecl->addAttr(NewAttr);
6939       }
6940     }
6941   }
6942 }
6943 
6944 /// Given that we are within the definition of the given function,
6945 /// will that definition behave like C99's 'inline', where the
6946 /// definition is discarded except for optimization purposes?
6947 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6948   // Try to avoid calling GetGVALinkageForFunction.
6949 
6950   // All cases of this require the 'inline' keyword.
6951   if (!FD->isInlined()) return false;
6952 
6953   // This is only possible in C++ with the gnu_inline attribute.
6954   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6955     return false;
6956 
6957   // Okay, go ahead and call the relatively-more-expensive function.
6958   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6959 }
6960 
6961 /// Determine whether a variable is extern "C" prior to attaching
6962 /// an initializer. We can't just call isExternC() here, because that
6963 /// will also compute and cache whether the declaration is externally
6964 /// visible, which might change when we attach the initializer.
6965 ///
6966 /// This can only be used if the declaration is known to not be a
6967 /// redeclaration of an internal linkage declaration.
6968 ///
6969 /// For instance:
6970 ///
6971 ///   auto x = []{};
6972 ///
6973 /// Attaching the initializer here makes this declaration not externally
6974 /// visible, because its type has internal linkage.
6975 ///
6976 /// FIXME: This is a hack.
6977 template<typename T>
6978 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6979   if (S.getLangOpts().CPlusPlus) {
6980     // In C++, the overloadable attribute negates the effects of extern "C".
6981     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6982       return false;
6983 
6984     // So do CUDA's host/device attributes.
6985     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6986                                  D->template hasAttr<CUDAHostAttr>()))
6987       return false;
6988   }
6989   return D->isExternC();
6990 }
6991 
6992 static bool shouldConsiderLinkage(const VarDecl *VD) {
6993   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6994   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6995       isa<OMPDeclareMapperDecl>(DC))
6996     return VD->hasExternalStorage();
6997   if (DC->isFileContext())
6998     return true;
6999   if (DC->isRecord())
7000     return false;
7001   if (isa<RequiresExprBodyDecl>(DC))
7002     return false;
7003   llvm_unreachable("Unexpected context");
7004 }
7005 
7006 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7007   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7008   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7009       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7010     return true;
7011   if (DC->isRecord())
7012     return false;
7013   llvm_unreachable("Unexpected context");
7014 }
7015 
7016 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7017                           ParsedAttr::Kind Kind) {
7018   // Check decl attributes on the DeclSpec.
7019   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7020     return true;
7021 
7022   // Walk the declarator structure, checking decl attributes that were in a type
7023   // position to the decl itself.
7024   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7025     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7026       return true;
7027   }
7028 
7029   // Finally, check attributes on the decl itself.
7030   return PD.getAttributes().hasAttribute(Kind);
7031 }
7032 
7033 /// Adjust the \c DeclContext for a function or variable that might be a
7034 /// function-local external declaration.
7035 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7036   if (!DC->isFunctionOrMethod())
7037     return false;
7038 
7039   // If this is a local extern function or variable declared within a function
7040   // template, don't add it into the enclosing namespace scope until it is
7041   // instantiated; it might have a dependent type right now.
7042   if (DC->isDependentContext())
7043     return true;
7044 
7045   // C++11 [basic.link]p7:
7046   //   When a block scope declaration of an entity with linkage is not found to
7047   //   refer to some other declaration, then that entity is a member of the
7048   //   innermost enclosing namespace.
7049   //
7050   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7051   // semantically-enclosing namespace, not a lexically-enclosing one.
7052   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7053     DC = DC->getParent();
7054   return true;
7055 }
7056 
7057 /// Returns true if given declaration has external C language linkage.
7058 static bool isDeclExternC(const Decl *D) {
7059   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7060     return FD->isExternC();
7061   if (const auto *VD = dyn_cast<VarDecl>(D))
7062     return VD->isExternC();
7063 
7064   llvm_unreachable("Unknown type of decl!");
7065 }
7066 
7067 /// Returns true if there hasn't been any invalid type diagnosed.
7068 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7069   DeclContext *DC = NewVD->getDeclContext();
7070   QualType R = NewVD->getType();
7071 
7072   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7073   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7074   // argument.
7075   if (R->isImageType() || R->isPipeType()) {
7076     Se.Diag(NewVD->getLocation(),
7077             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7078         << R;
7079     NewVD->setInvalidDecl();
7080     return false;
7081   }
7082 
7083   // OpenCL v1.2 s6.9.r:
7084   // The event type cannot be used to declare a program scope variable.
7085   // OpenCL v2.0 s6.9.q:
7086   // The clk_event_t and reserve_id_t types cannot be declared in program
7087   // scope.
7088   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7089     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7090       Se.Diag(NewVD->getLocation(),
7091               diag::err_invalid_type_for_program_scope_var)
7092           << R;
7093       NewVD->setInvalidDecl();
7094       return false;
7095     }
7096   }
7097 
7098   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7099   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7100                                                Se.getLangOpts())) {
7101     QualType NR = R.getCanonicalType();
7102     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7103            NR->isReferenceType()) {
7104       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7105           NR->isFunctionReferenceType()) {
7106         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7107             << NR->isReferenceType();
7108         NewVD->setInvalidDecl();
7109         return false;
7110       }
7111       NR = NR->getPointeeType();
7112     }
7113   }
7114 
7115   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7116                                                Se.getLangOpts())) {
7117     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7118     // half array type (unless the cl_khr_fp16 extension is enabled).
7119     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7120       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7121       NewVD->setInvalidDecl();
7122       return false;
7123     }
7124   }
7125 
7126   // OpenCL v1.2 s6.9.r:
7127   // The event type cannot be used with the __local, __constant and __global
7128   // address space qualifiers.
7129   if (R->isEventT()) {
7130     if (R.getAddressSpace() != LangAS::opencl_private) {
7131       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7132       NewVD->setInvalidDecl();
7133       return false;
7134     }
7135   }
7136 
7137   if (R->isSamplerT()) {
7138     // OpenCL v1.2 s6.9.b p4:
7139     // The sampler type cannot be used with the __local and __global address
7140     // space qualifiers.
7141     if (R.getAddressSpace() == LangAS::opencl_local ||
7142         R.getAddressSpace() == LangAS::opencl_global) {
7143       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7144       NewVD->setInvalidDecl();
7145     }
7146 
7147     // OpenCL v1.2 s6.12.14.1:
7148     // A global sampler must be declared with either the constant address
7149     // space qualifier or with the const qualifier.
7150     if (DC->isTranslationUnit() &&
7151         !(R.getAddressSpace() == LangAS::opencl_constant ||
7152           R.isConstQualified())) {
7153       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7154       NewVD->setInvalidDecl();
7155     }
7156     if (NewVD->isInvalidDecl())
7157       return false;
7158   }
7159 
7160   return true;
7161 }
7162 
7163 template <typename AttrTy>
7164 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7165   const TypedefNameDecl *TND = TT->getDecl();
7166   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7167     AttrTy *Clone = Attribute->clone(S.Context);
7168     Clone->setInherited(true);
7169     D->addAttr(Clone);
7170   }
7171 }
7172 
7173 NamedDecl *Sema::ActOnVariableDeclarator(
7174     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7175     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7176     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7177   QualType R = TInfo->getType();
7178   DeclarationName Name = GetNameForDeclarator(D).getName();
7179 
7180   IdentifierInfo *II = Name.getAsIdentifierInfo();
7181 
7182   if (D.isDecompositionDeclarator()) {
7183     // Take the name of the first declarator as our name for diagnostic
7184     // purposes.
7185     auto &Decomp = D.getDecompositionDeclarator();
7186     if (!Decomp.bindings().empty()) {
7187       II = Decomp.bindings()[0].Name;
7188       Name = II;
7189     }
7190   } else if (!II) {
7191     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7192     return nullptr;
7193   }
7194 
7195 
7196   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7197   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7198 
7199   // dllimport globals without explicit storage class are treated as extern. We
7200   // have to change the storage class this early to get the right DeclContext.
7201   if (SC == SC_None && !DC->isRecord() &&
7202       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7203       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7204     SC = SC_Extern;
7205 
7206   DeclContext *OriginalDC = DC;
7207   bool IsLocalExternDecl = SC == SC_Extern &&
7208                            adjustContextForLocalExternDecl(DC);
7209 
7210   if (SCSpec == DeclSpec::SCS_mutable) {
7211     // mutable can only appear on non-static class members, so it's always
7212     // an error here
7213     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7214     D.setInvalidType();
7215     SC = SC_None;
7216   }
7217 
7218   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7219       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7220                               D.getDeclSpec().getStorageClassSpecLoc())) {
7221     // In C++11, the 'register' storage class specifier is deprecated.
7222     // Suppress the warning in system macros, it's used in macros in some
7223     // popular C system headers, such as in glibc's htonl() macro.
7224     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7225          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7226                                    : diag::warn_deprecated_register)
7227       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7228   }
7229 
7230   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7231 
7232   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7233     // C99 6.9p2: The storage-class specifiers auto and register shall not
7234     // appear in the declaration specifiers in an external declaration.
7235     // Global Register+Asm is a GNU extension we support.
7236     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7237       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7238       D.setInvalidType();
7239     }
7240   }
7241 
7242   // If this variable has a VLA type and an initializer, try to
7243   // fold to a constant-sized type. This is otherwise invalid.
7244   if (D.hasInitializer() && R->isVariableArrayType())
7245     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7246                                     /*DiagID=*/0);
7247 
7248   bool IsMemberSpecialization = false;
7249   bool IsVariableTemplateSpecialization = false;
7250   bool IsPartialSpecialization = false;
7251   bool IsVariableTemplate = false;
7252   VarDecl *NewVD = nullptr;
7253   VarTemplateDecl *NewTemplate = nullptr;
7254   TemplateParameterList *TemplateParams = nullptr;
7255   if (!getLangOpts().CPlusPlus) {
7256     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7257                             II, R, TInfo, SC);
7258 
7259     if (R->getContainedDeducedType())
7260       ParsingInitForAutoVars.insert(NewVD);
7261 
7262     if (D.isInvalidType())
7263       NewVD->setInvalidDecl();
7264 
7265     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7266         NewVD->hasLocalStorage())
7267       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7268                             NTCUC_AutoVar, NTCUK_Destruct);
7269   } else {
7270     bool Invalid = false;
7271 
7272     if (DC->isRecord() && !CurContext->isRecord()) {
7273       // This is an out-of-line definition of a static data member.
7274       switch (SC) {
7275       case SC_None:
7276         break;
7277       case SC_Static:
7278         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7279              diag::err_static_out_of_line)
7280           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7281         break;
7282       case SC_Auto:
7283       case SC_Register:
7284       case SC_Extern:
7285         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7286         // to names of variables declared in a block or to function parameters.
7287         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7288         // of class members
7289 
7290         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7291              diag::err_storage_class_for_static_member)
7292           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7293         break;
7294       case SC_PrivateExtern:
7295         llvm_unreachable("C storage class in c++!");
7296       }
7297     }
7298 
7299     if (SC == SC_Static && CurContext->isRecord()) {
7300       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7301         // Walk up the enclosing DeclContexts to check for any that are
7302         // incompatible with static data members.
7303         const DeclContext *FunctionOrMethod = nullptr;
7304         const CXXRecordDecl *AnonStruct = nullptr;
7305         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7306           if (Ctxt->isFunctionOrMethod()) {
7307             FunctionOrMethod = Ctxt;
7308             break;
7309           }
7310           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7311           if (ParentDecl && !ParentDecl->getDeclName()) {
7312             AnonStruct = ParentDecl;
7313             break;
7314           }
7315         }
7316         if (FunctionOrMethod) {
7317           // C++ [class.static.data]p5: A local class shall not have static data
7318           // members.
7319           Diag(D.getIdentifierLoc(),
7320                diag::err_static_data_member_not_allowed_in_local_class)
7321             << Name << RD->getDeclName() << RD->getTagKind();
7322         } else if (AnonStruct) {
7323           // C++ [class.static.data]p4: Unnamed classes and classes contained
7324           // directly or indirectly within unnamed classes shall not contain
7325           // static data members.
7326           Diag(D.getIdentifierLoc(),
7327                diag::err_static_data_member_not_allowed_in_anon_struct)
7328             << Name << AnonStruct->getTagKind();
7329           Invalid = true;
7330         } else if (RD->isUnion()) {
7331           // C++98 [class.union]p1: If a union contains a static data member,
7332           // the program is ill-formed. C++11 drops this restriction.
7333           Diag(D.getIdentifierLoc(),
7334                getLangOpts().CPlusPlus11
7335                  ? diag::warn_cxx98_compat_static_data_member_in_union
7336                  : diag::ext_static_data_member_in_union) << Name;
7337         }
7338       }
7339     }
7340 
7341     // Match up the template parameter lists with the scope specifier, then
7342     // determine whether we have a template or a template specialization.
7343     bool InvalidScope = false;
7344     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7345         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7346         D.getCXXScopeSpec(),
7347         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7348             ? D.getName().TemplateId
7349             : nullptr,
7350         TemplateParamLists,
7351         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7352     Invalid |= InvalidScope;
7353 
7354     if (TemplateParams) {
7355       if (!TemplateParams->size() &&
7356           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7357         // There is an extraneous 'template<>' for this variable. Complain
7358         // about it, but allow the declaration of the variable.
7359         Diag(TemplateParams->getTemplateLoc(),
7360              diag::err_template_variable_noparams)
7361           << II
7362           << SourceRange(TemplateParams->getTemplateLoc(),
7363                          TemplateParams->getRAngleLoc());
7364         TemplateParams = nullptr;
7365       } else {
7366         // Check that we can declare a template here.
7367         if (CheckTemplateDeclScope(S, TemplateParams))
7368           return nullptr;
7369 
7370         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7371           // This is an explicit specialization or a partial specialization.
7372           IsVariableTemplateSpecialization = true;
7373           IsPartialSpecialization = TemplateParams->size() > 0;
7374         } else { // if (TemplateParams->size() > 0)
7375           // This is a template declaration.
7376           IsVariableTemplate = true;
7377 
7378           // Only C++1y supports variable templates (N3651).
7379           Diag(D.getIdentifierLoc(),
7380                getLangOpts().CPlusPlus14
7381                    ? diag::warn_cxx11_compat_variable_template
7382                    : diag::ext_variable_template);
7383         }
7384       }
7385     } else {
7386       // Check that we can declare a member specialization here.
7387       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7388           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7389         return nullptr;
7390       assert((Invalid ||
7391               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7392              "should have a 'template<>' for this decl");
7393     }
7394 
7395     if (IsVariableTemplateSpecialization) {
7396       SourceLocation TemplateKWLoc =
7397           TemplateParamLists.size() > 0
7398               ? TemplateParamLists[0]->getTemplateLoc()
7399               : SourceLocation();
7400       DeclResult Res = ActOnVarTemplateSpecialization(
7401           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7402           IsPartialSpecialization);
7403       if (Res.isInvalid())
7404         return nullptr;
7405       NewVD = cast<VarDecl>(Res.get());
7406       AddToScope = false;
7407     } else if (D.isDecompositionDeclarator()) {
7408       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7409                                         D.getIdentifierLoc(), R, TInfo, SC,
7410                                         Bindings);
7411     } else
7412       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7413                               D.getIdentifierLoc(), II, R, TInfo, SC);
7414 
7415     // If this is supposed to be a variable template, create it as such.
7416     if (IsVariableTemplate) {
7417       NewTemplate =
7418           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7419                                   TemplateParams, NewVD);
7420       NewVD->setDescribedVarTemplate(NewTemplate);
7421     }
7422 
7423     // If this decl has an auto type in need of deduction, make a note of the
7424     // Decl so we can diagnose uses of it in its own initializer.
7425     if (R->getContainedDeducedType())
7426       ParsingInitForAutoVars.insert(NewVD);
7427 
7428     if (D.isInvalidType() || Invalid) {
7429       NewVD->setInvalidDecl();
7430       if (NewTemplate)
7431         NewTemplate->setInvalidDecl();
7432     }
7433 
7434     SetNestedNameSpecifier(*this, NewVD, D);
7435 
7436     // If we have any template parameter lists that don't directly belong to
7437     // the variable (matching the scope specifier), store them.
7438     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7439     if (TemplateParamLists.size() > VDTemplateParamLists)
7440       NewVD->setTemplateParameterListsInfo(
7441           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7442   }
7443 
7444   if (D.getDeclSpec().isInlineSpecified()) {
7445     if (!getLangOpts().CPlusPlus) {
7446       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7447           << 0;
7448     } else if (CurContext->isFunctionOrMethod()) {
7449       // 'inline' is not allowed on block scope variable declaration.
7450       Diag(D.getDeclSpec().getInlineSpecLoc(),
7451            diag::err_inline_declaration_block_scope) << Name
7452         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7453     } else {
7454       Diag(D.getDeclSpec().getInlineSpecLoc(),
7455            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7456                                      : diag::ext_inline_variable);
7457       NewVD->setInlineSpecified();
7458     }
7459   }
7460 
7461   // Set the lexical context. If the declarator has a C++ scope specifier, the
7462   // lexical context will be different from the semantic context.
7463   NewVD->setLexicalDeclContext(CurContext);
7464   if (NewTemplate)
7465     NewTemplate->setLexicalDeclContext(CurContext);
7466 
7467   if (IsLocalExternDecl) {
7468     if (D.isDecompositionDeclarator())
7469       for (auto *B : Bindings)
7470         B->setLocalExternDecl();
7471     else
7472       NewVD->setLocalExternDecl();
7473   }
7474 
7475   bool EmitTLSUnsupportedError = false;
7476   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7477     // C++11 [dcl.stc]p4:
7478     //   When thread_local is applied to a variable of block scope the
7479     //   storage-class-specifier static is implied if it does not appear
7480     //   explicitly.
7481     // Core issue: 'static' is not implied if the variable is declared
7482     //   'extern'.
7483     if (NewVD->hasLocalStorage() &&
7484         (SCSpec != DeclSpec::SCS_unspecified ||
7485          TSCS != DeclSpec::TSCS_thread_local ||
7486          !DC->isFunctionOrMethod()))
7487       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7488            diag::err_thread_non_global)
7489         << DeclSpec::getSpecifierName(TSCS);
7490     else if (!Context.getTargetInfo().isTLSSupported()) {
7491       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7492           getLangOpts().SYCLIsDevice) {
7493         // Postpone error emission until we've collected attributes required to
7494         // figure out whether it's a host or device variable and whether the
7495         // error should be ignored.
7496         EmitTLSUnsupportedError = true;
7497         // We still need to mark the variable as TLS so it shows up in AST with
7498         // proper storage class for other tools to use even if we're not going
7499         // to emit any code for it.
7500         NewVD->setTSCSpec(TSCS);
7501       } else
7502         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7503              diag::err_thread_unsupported);
7504     } else
7505       NewVD->setTSCSpec(TSCS);
7506   }
7507 
7508   switch (D.getDeclSpec().getConstexprSpecifier()) {
7509   case ConstexprSpecKind::Unspecified:
7510     break;
7511 
7512   case ConstexprSpecKind::Consteval:
7513     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7514          diag::err_constexpr_wrong_decl_kind)
7515         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7516     LLVM_FALLTHROUGH;
7517 
7518   case ConstexprSpecKind::Constexpr:
7519     NewVD->setConstexpr(true);
7520     // C++1z [dcl.spec.constexpr]p1:
7521     //   A static data member declared with the constexpr specifier is
7522     //   implicitly an inline variable.
7523     if (NewVD->isStaticDataMember() &&
7524         (getLangOpts().CPlusPlus17 ||
7525          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7526       NewVD->setImplicitlyInline();
7527     break;
7528 
7529   case ConstexprSpecKind::Constinit:
7530     if (!NewVD->hasGlobalStorage())
7531       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7532            diag::err_constinit_local_variable);
7533     else
7534       NewVD->addAttr(ConstInitAttr::Create(
7535           Context, D.getDeclSpec().getConstexprSpecLoc(),
7536           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7537     break;
7538   }
7539 
7540   // C99 6.7.4p3
7541   //   An inline definition of a function with external linkage shall
7542   //   not contain a definition of a modifiable object with static or
7543   //   thread storage duration...
7544   // We only apply this when the function is required to be defined
7545   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7546   // that a local variable with thread storage duration still has to
7547   // be marked 'static'.  Also note that it's possible to get these
7548   // semantics in C++ using __attribute__((gnu_inline)).
7549   if (SC == SC_Static && S->getFnParent() != nullptr &&
7550       !NewVD->getType().isConstQualified()) {
7551     FunctionDecl *CurFD = getCurFunctionDecl();
7552     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7553       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7554            diag::warn_static_local_in_extern_inline);
7555       MaybeSuggestAddingStaticToDecl(CurFD);
7556     }
7557   }
7558 
7559   if (D.getDeclSpec().isModulePrivateSpecified()) {
7560     if (IsVariableTemplateSpecialization)
7561       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7562           << (IsPartialSpecialization ? 1 : 0)
7563           << FixItHint::CreateRemoval(
7564                  D.getDeclSpec().getModulePrivateSpecLoc());
7565     else if (IsMemberSpecialization)
7566       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7567         << 2
7568         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7569     else if (NewVD->hasLocalStorage())
7570       Diag(NewVD->getLocation(), diag::err_module_private_local)
7571           << 0 << NewVD
7572           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7573           << FixItHint::CreateRemoval(
7574                  D.getDeclSpec().getModulePrivateSpecLoc());
7575     else {
7576       NewVD->setModulePrivate();
7577       if (NewTemplate)
7578         NewTemplate->setModulePrivate();
7579       for (auto *B : Bindings)
7580         B->setModulePrivate();
7581     }
7582   }
7583 
7584   if (getLangOpts().OpenCL) {
7585     deduceOpenCLAddressSpace(NewVD);
7586 
7587     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7588     if (TSC != TSCS_unspecified) {
7589       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7590            diag::err_opencl_unknown_type_specifier)
7591           << getLangOpts().getOpenCLVersionString()
7592           << DeclSpec::getSpecifierName(TSC) << 1;
7593       NewVD->setInvalidDecl();
7594     }
7595   }
7596 
7597   // Handle attributes prior to checking for duplicates in MergeVarDecl
7598   ProcessDeclAttributes(S, NewVD, D);
7599 
7600   // FIXME: This is probably the wrong location to be doing this and we should
7601   // probably be doing this for more attributes (especially for function
7602   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7603   // the code to copy attributes would be generated by TableGen.
7604   if (R->isFunctionPointerType())
7605     if (const auto *TT = R->getAs<TypedefType>())
7606       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7607 
7608   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7609       getLangOpts().SYCLIsDevice) {
7610     if (EmitTLSUnsupportedError &&
7611         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7612          (getLangOpts().OpenMPIsDevice &&
7613           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7614       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7615            diag::err_thread_unsupported);
7616 
7617     if (EmitTLSUnsupportedError &&
7618         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7619       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7620     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7621     // storage [duration]."
7622     if (SC == SC_None && S->getFnParent() != nullptr &&
7623         (NewVD->hasAttr<CUDASharedAttr>() ||
7624          NewVD->hasAttr<CUDAConstantAttr>())) {
7625       NewVD->setStorageClass(SC_Static);
7626     }
7627   }
7628 
7629   // Ensure that dllimport globals without explicit storage class are treated as
7630   // extern. The storage class is set above using parsed attributes. Now we can
7631   // check the VarDecl itself.
7632   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7633          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7634          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7635 
7636   // In auto-retain/release, infer strong retension for variables of
7637   // retainable type.
7638   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7639     NewVD->setInvalidDecl();
7640 
7641   // Handle GNU asm-label extension (encoded as an attribute).
7642   if (Expr *E = (Expr*)D.getAsmLabel()) {
7643     // The parser guarantees this is a string.
7644     StringLiteral *SE = cast<StringLiteral>(E);
7645     StringRef Label = SE->getString();
7646     if (S->getFnParent() != nullptr) {
7647       switch (SC) {
7648       case SC_None:
7649       case SC_Auto:
7650         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7651         break;
7652       case SC_Register:
7653         // Local Named register
7654         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7655             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7656           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7657         break;
7658       case SC_Static:
7659       case SC_Extern:
7660       case SC_PrivateExtern:
7661         break;
7662       }
7663     } else if (SC == SC_Register) {
7664       // Global Named register
7665       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7666         const auto &TI = Context.getTargetInfo();
7667         bool HasSizeMismatch;
7668 
7669         if (!TI.isValidGCCRegisterName(Label))
7670           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7671         else if (!TI.validateGlobalRegisterVariable(Label,
7672                                                     Context.getTypeSize(R),
7673                                                     HasSizeMismatch))
7674           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7675         else if (HasSizeMismatch)
7676           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7677       }
7678 
7679       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7680         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7681         NewVD->setInvalidDecl(true);
7682       }
7683     }
7684 
7685     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7686                                         /*IsLiteralLabel=*/true,
7687                                         SE->getStrTokenLoc(0)));
7688   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7689     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7690       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7691     if (I != ExtnameUndeclaredIdentifiers.end()) {
7692       if (isDeclExternC(NewVD)) {
7693         NewVD->addAttr(I->second);
7694         ExtnameUndeclaredIdentifiers.erase(I);
7695       } else
7696         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7697             << /*Variable*/1 << NewVD;
7698     }
7699   }
7700 
7701   // Find the shadowed declaration before filtering for scope.
7702   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7703                                 ? getShadowedDeclaration(NewVD, Previous)
7704                                 : nullptr;
7705 
7706   // Don't consider existing declarations that are in a different
7707   // scope and are out-of-semantic-context declarations (if the new
7708   // declaration has linkage).
7709   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7710                        D.getCXXScopeSpec().isNotEmpty() ||
7711                        IsMemberSpecialization ||
7712                        IsVariableTemplateSpecialization);
7713 
7714   // Check whether the previous declaration is in the same block scope. This
7715   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7716   if (getLangOpts().CPlusPlus &&
7717       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7718     NewVD->setPreviousDeclInSameBlockScope(
7719         Previous.isSingleResult() && !Previous.isShadowed() &&
7720         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7721 
7722   if (!getLangOpts().CPlusPlus) {
7723     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7724   } else {
7725     // If this is an explicit specialization of a static data member, check it.
7726     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7727         CheckMemberSpecialization(NewVD, Previous))
7728       NewVD->setInvalidDecl();
7729 
7730     // Merge the decl with the existing one if appropriate.
7731     if (!Previous.empty()) {
7732       if (Previous.isSingleResult() &&
7733           isa<FieldDecl>(Previous.getFoundDecl()) &&
7734           D.getCXXScopeSpec().isSet()) {
7735         // The user tried to define a non-static data member
7736         // out-of-line (C++ [dcl.meaning]p1).
7737         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7738           << D.getCXXScopeSpec().getRange();
7739         Previous.clear();
7740         NewVD->setInvalidDecl();
7741       }
7742     } else if (D.getCXXScopeSpec().isSet()) {
7743       // No previous declaration in the qualifying scope.
7744       Diag(D.getIdentifierLoc(), diag::err_no_member)
7745         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7746         << D.getCXXScopeSpec().getRange();
7747       NewVD->setInvalidDecl();
7748     }
7749 
7750     if (!IsVariableTemplateSpecialization)
7751       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7752 
7753     if (NewTemplate) {
7754       VarTemplateDecl *PrevVarTemplate =
7755           NewVD->getPreviousDecl()
7756               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7757               : nullptr;
7758 
7759       // Check the template parameter list of this declaration, possibly
7760       // merging in the template parameter list from the previous variable
7761       // template declaration.
7762       if (CheckTemplateParameterList(
7763               TemplateParams,
7764               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7765                               : nullptr,
7766               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7767                DC->isDependentContext())
7768                   ? TPC_ClassTemplateMember
7769                   : TPC_VarTemplate))
7770         NewVD->setInvalidDecl();
7771 
7772       // If we are providing an explicit specialization of a static variable
7773       // template, make a note of that.
7774       if (PrevVarTemplate &&
7775           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7776         PrevVarTemplate->setMemberSpecialization();
7777     }
7778   }
7779 
7780   // Diagnose shadowed variables iff this isn't a redeclaration.
7781   if (ShadowedDecl && !D.isRedeclaration())
7782     CheckShadow(NewVD, ShadowedDecl, Previous);
7783 
7784   ProcessPragmaWeak(S, NewVD);
7785 
7786   // If this is the first declaration of an extern C variable, update
7787   // the map of such variables.
7788   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7789       isIncompleteDeclExternC(*this, NewVD))
7790     RegisterLocallyScopedExternCDecl(NewVD, S);
7791 
7792   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7793     MangleNumberingContext *MCtx;
7794     Decl *ManglingContextDecl;
7795     std::tie(MCtx, ManglingContextDecl) =
7796         getCurrentMangleNumberContext(NewVD->getDeclContext());
7797     if (MCtx) {
7798       Context.setManglingNumber(
7799           NewVD, MCtx->getManglingNumber(
7800                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7801       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7802     }
7803   }
7804 
7805   // Special handling of variable named 'main'.
7806   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7807       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7808       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7809 
7810     // C++ [basic.start.main]p3
7811     // A program that declares a variable main at global scope is ill-formed.
7812     if (getLangOpts().CPlusPlus)
7813       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7814 
7815     // In C, and external-linkage variable named main results in undefined
7816     // behavior.
7817     else if (NewVD->hasExternalFormalLinkage())
7818       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7819   }
7820 
7821   if (D.isRedeclaration() && !Previous.empty()) {
7822     NamedDecl *Prev = Previous.getRepresentativeDecl();
7823     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7824                                    D.isFunctionDefinition());
7825   }
7826 
7827   if (NewTemplate) {
7828     if (NewVD->isInvalidDecl())
7829       NewTemplate->setInvalidDecl();
7830     ActOnDocumentableDecl(NewTemplate);
7831     return NewTemplate;
7832   }
7833 
7834   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7835     CompleteMemberSpecialization(NewVD, Previous);
7836 
7837   return NewVD;
7838 }
7839 
7840 /// Enum describing the %select options in diag::warn_decl_shadow.
7841 enum ShadowedDeclKind {
7842   SDK_Local,
7843   SDK_Global,
7844   SDK_StaticMember,
7845   SDK_Field,
7846   SDK_Typedef,
7847   SDK_Using,
7848   SDK_StructuredBinding
7849 };
7850 
7851 /// Determine what kind of declaration we're shadowing.
7852 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7853                                                 const DeclContext *OldDC) {
7854   if (isa<TypeAliasDecl>(ShadowedDecl))
7855     return SDK_Using;
7856   else if (isa<TypedefDecl>(ShadowedDecl))
7857     return SDK_Typedef;
7858   else if (isa<BindingDecl>(ShadowedDecl))
7859     return SDK_StructuredBinding;
7860   else if (isa<RecordDecl>(OldDC))
7861     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7862 
7863   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7864 }
7865 
7866 /// Return the location of the capture if the given lambda captures the given
7867 /// variable \p VD, or an invalid source location otherwise.
7868 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7869                                          const VarDecl *VD) {
7870   for (const Capture &Capture : LSI->Captures) {
7871     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7872       return Capture.getLocation();
7873   }
7874   return SourceLocation();
7875 }
7876 
7877 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7878                                      const LookupResult &R) {
7879   // Only diagnose if we're shadowing an unambiguous field or variable.
7880   if (R.getResultKind() != LookupResult::Found)
7881     return false;
7882 
7883   // Return false if warning is ignored.
7884   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7885 }
7886 
7887 /// Return the declaration shadowed by the given variable \p D, or null
7888 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7889 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7890                                         const LookupResult &R) {
7891   if (!shouldWarnIfShadowedDecl(Diags, R))
7892     return nullptr;
7893 
7894   // Don't diagnose declarations at file scope.
7895   if (D->hasGlobalStorage())
7896     return nullptr;
7897 
7898   NamedDecl *ShadowedDecl = R.getFoundDecl();
7899   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7900                                                             : nullptr;
7901 }
7902 
7903 /// Return the declaration shadowed by the given typedef \p D, or null
7904 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7905 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7906                                         const LookupResult &R) {
7907   // Don't warn if typedef declaration is part of a class
7908   if (D->getDeclContext()->isRecord())
7909     return nullptr;
7910 
7911   if (!shouldWarnIfShadowedDecl(Diags, R))
7912     return nullptr;
7913 
7914   NamedDecl *ShadowedDecl = R.getFoundDecl();
7915   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7916 }
7917 
7918 /// Return the declaration shadowed by the given variable \p D, or null
7919 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7920 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7921                                         const LookupResult &R) {
7922   if (!shouldWarnIfShadowedDecl(Diags, R))
7923     return nullptr;
7924 
7925   NamedDecl *ShadowedDecl = R.getFoundDecl();
7926   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7927                                                             : nullptr;
7928 }
7929 
7930 /// Diagnose variable or built-in function shadowing.  Implements
7931 /// -Wshadow.
7932 ///
7933 /// This method is called whenever a VarDecl is added to a "useful"
7934 /// scope.
7935 ///
7936 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7937 /// \param R the lookup of the name
7938 ///
7939 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7940                        const LookupResult &R) {
7941   DeclContext *NewDC = D->getDeclContext();
7942 
7943   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7944     // Fields are not shadowed by variables in C++ static methods.
7945     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7946       if (MD->isStatic())
7947         return;
7948 
7949     // Fields shadowed by constructor parameters are a special case. Usually
7950     // the constructor initializes the field with the parameter.
7951     if (isa<CXXConstructorDecl>(NewDC))
7952       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7953         // Remember that this was shadowed so we can either warn about its
7954         // modification or its existence depending on warning settings.
7955         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7956         return;
7957       }
7958   }
7959 
7960   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7961     if (shadowedVar->isExternC()) {
7962       // For shadowing external vars, make sure that we point to the global
7963       // declaration, not a locally scoped extern declaration.
7964       for (auto I : shadowedVar->redecls())
7965         if (I->isFileVarDecl()) {
7966           ShadowedDecl = I;
7967           break;
7968         }
7969     }
7970 
7971   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7972 
7973   unsigned WarningDiag = diag::warn_decl_shadow;
7974   SourceLocation CaptureLoc;
7975   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7976       isa<CXXMethodDecl>(NewDC)) {
7977     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7978       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7979         if (RD->getLambdaCaptureDefault() == LCD_None) {
7980           // Try to avoid warnings for lambdas with an explicit capture list.
7981           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7982           // Warn only when the lambda captures the shadowed decl explicitly.
7983           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7984           if (CaptureLoc.isInvalid())
7985             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7986         } else {
7987           // Remember that this was shadowed so we can avoid the warning if the
7988           // shadowed decl isn't captured and the warning settings allow it.
7989           cast<LambdaScopeInfo>(getCurFunction())
7990               ->ShadowingDecls.push_back(
7991                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7992           return;
7993         }
7994       }
7995 
7996       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7997         // A variable can't shadow a local variable in an enclosing scope, if
7998         // they are separated by a non-capturing declaration context.
7999         for (DeclContext *ParentDC = NewDC;
8000              ParentDC && !ParentDC->Equals(OldDC);
8001              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8002           // Only block literals, captured statements, and lambda expressions
8003           // can capture; other scopes don't.
8004           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8005               !isLambdaCallOperator(ParentDC)) {
8006             return;
8007           }
8008         }
8009       }
8010     }
8011   }
8012 
8013   // Only warn about certain kinds of shadowing for class members.
8014   if (NewDC && NewDC->isRecord()) {
8015     // In particular, don't warn about shadowing non-class members.
8016     if (!OldDC->isRecord())
8017       return;
8018 
8019     // TODO: should we warn about static data members shadowing
8020     // static data members from base classes?
8021 
8022     // TODO: don't diagnose for inaccessible shadowed members.
8023     // This is hard to do perfectly because we might friend the
8024     // shadowing context, but that's just a false negative.
8025   }
8026 
8027 
8028   DeclarationName Name = R.getLookupName();
8029 
8030   // Emit warning and note.
8031   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8032   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8033   if (!CaptureLoc.isInvalid())
8034     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8035         << Name << /*explicitly*/ 1;
8036   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8037 }
8038 
8039 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8040 /// when these variables are captured by the lambda.
8041 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8042   for (const auto &Shadow : LSI->ShadowingDecls) {
8043     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8044     // Try to avoid the warning when the shadowed decl isn't captured.
8045     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8046     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8047     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8048                                        ? diag::warn_decl_shadow_uncaptured_local
8049                                        : diag::warn_decl_shadow)
8050         << Shadow.VD->getDeclName()
8051         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8052     if (!CaptureLoc.isInvalid())
8053       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8054           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8055     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8056   }
8057 }
8058 
8059 /// Check -Wshadow without the advantage of a previous lookup.
8060 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8061   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8062     return;
8063 
8064   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8065                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8066   LookupName(R, S);
8067   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8068     CheckShadow(D, ShadowedDecl, R);
8069 }
8070 
8071 /// Check if 'E', which is an expression that is about to be modified, refers
8072 /// to a constructor parameter that shadows a field.
8073 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8074   // Quickly ignore expressions that can't be shadowing ctor parameters.
8075   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8076     return;
8077   E = E->IgnoreParenImpCasts();
8078   auto *DRE = dyn_cast<DeclRefExpr>(E);
8079   if (!DRE)
8080     return;
8081   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8082   auto I = ShadowingDecls.find(D);
8083   if (I == ShadowingDecls.end())
8084     return;
8085   const NamedDecl *ShadowedDecl = I->second;
8086   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8087   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8088   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8089   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8090 
8091   // Avoid issuing multiple warnings about the same decl.
8092   ShadowingDecls.erase(I);
8093 }
8094 
8095 /// Check for conflict between this global or extern "C" declaration and
8096 /// previous global or extern "C" declarations. This is only used in C++.
8097 template<typename T>
8098 static bool checkGlobalOrExternCConflict(
8099     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8100   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8101   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8102 
8103   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8104     // The common case: this global doesn't conflict with any extern "C"
8105     // declaration.
8106     return false;
8107   }
8108 
8109   if (Prev) {
8110     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8111       // Both the old and new declarations have C language linkage. This is a
8112       // redeclaration.
8113       Previous.clear();
8114       Previous.addDecl(Prev);
8115       return true;
8116     }
8117 
8118     // This is a global, non-extern "C" declaration, and there is a previous
8119     // non-global extern "C" declaration. Diagnose if this is a variable
8120     // declaration.
8121     if (!isa<VarDecl>(ND))
8122       return false;
8123   } else {
8124     // The declaration is extern "C". Check for any declaration in the
8125     // translation unit which might conflict.
8126     if (IsGlobal) {
8127       // We have already performed the lookup into the translation unit.
8128       IsGlobal = false;
8129       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8130            I != E; ++I) {
8131         if (isa<VarDecl>(*I)) {
8132           Prev = *I;
8133           break;
8134         }
8135       }
8136     } else {
8137       DeclContext::lookup_result R =
8138           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8139       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8140            I != E; ++I) {
8141         if (isa<VarDecl>(*I)) {
8142           Prev = *I;
8143           break;
8144         }
8145         // FIXME: If we have any other entity with this name in global scope,
8146         // the declaration is ill-formed, but that is a defect: it breaks the
8147         // 'stat' hack, for instance. Only variables can have mangled name
8148         // clashes with extern "C" declarations, so only they deserve a
8149         // diagnostic.
8150       }
8151     }
8152 
8153     if (!Prev)
8154       return false;
8155   }
8156 
8157   // Use the first declaration's location to ensure we point at something which
8158   // is lexically inside an extern "C" linkage-spec.
8159   assert(Prev && "should have found a previous declaration to diagnose");
8160   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8161     Prev = FD->getFirstDecl();
8162   else
8163     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8164 
8165   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8166     << IsGlobal << ND;
8167   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8168     << IsGlobal;
8169   return false;
8170 }
8171 
8172 /// Apply special rules for handling extern "C" declarations. Returns \c true
8173 /// if we have found that this is a redeclaration of some prior entity.
8174 ///
8175 /// Per C++ [dcl.link]p6:
8176 ///   Two declarations [for a function or variable] with C language linkage
8177 ///   with the same name that appear in different scopes refer to the same
8178 ///   [entity]. An entity with C language linkage shall not be declared with
8179 ///   the same name as an entity in global scope.
8180 template<typename T>
8181 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8182                                                   LookupResult &Previous) {
8183   if (!S.getLangOpts().CPlusPlus) {
8184     // In C, when declaring a global variable, look for a corresponding 'extern'
8185     // variable declared in function scope. We don't need this in C++, because
8186     // we find local extern decls in the surrounding file-scope DeclContext.
8187     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8188       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8189         Previous.clear();
8190         Previous.addDecl(Prev);
8191         return true;
8192       }
8193     }
8194     return false;
8195   }
8196 
8197   // A declaration in the translation unit can conflict with an extern "C"
8198   // declaration.
8199   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8200     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8201 
8202   // An extern "C" declaration can conflict with a declaration in the
8203   // translation unit or can be a redeclaration of an extern "C" declaration
8204   // in another scope.
8205   if (isIncompleteDeclExternC(S,ND))
8206     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8207 
8208   // Neither global nor extern "C": nothing to do.
8209   return false;
8210 }
8211 
8212 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8213   // If the decl is already known invalid, don't check it.
8214   if (NewVD->isInvalidDecl())
8215     return;
8216 
8217   QualType T = NewVD->getType();
8218 
8219   // Defer checking an 'auto' type until its initializer is attached.
8220   if (T->isUndeducedType())
8221     return;
8222 
8223   if (NewVD->hasAttrs())
8224     CheckAlignasUnderalignment(NewVD);
8225 
8226   if (T->isObjCObjectType()) {
8227     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8228       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8229     T = Context.getObjCObjectPointerType(T);
8230     NewVD->setType(T);
8231   }
8232 
8233   // Emit an error if an address space was applied to decl with local storage.
8234   // This includes arrays of objects with address space qualifiers, but not
8235   // automatic variables that point to other address spaces.
8236   // ISO/IEC TR 18037 S5.1.2
8237   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8238       T.getAddressSpace() != LangAS::Default) {
8239     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8240     NewVD->setInvalidDecl();
8241     return;
8242   }
8243 
8244   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8245   // scope.
8246   if (getLangOpts().OpenCLVersion == 120 &&
8247       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8248                                             getLangOpts()) &&
8249       NewVD->isStaticLocal()) {
8250     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8251     NewVD->setInvalidDecl();
8252     return;
8253   }
8254 
8255   if (getLangOpts().OpenCL) {
8256     if (!diagnoseOpenCLTypes(*this, NewVD))
8257       return;
8258 
8259     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8260     if (NewVD->hasAttr<BlocksAttr>()) {
8261       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8262       return;
8263     }
8264 
8265     if (T->isBlockPointerType()) {
8266       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8267       // can't use 'extern' storage class.
8268       if (!T.isConstQualified()) {
8269         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8270             << 0 /*const*/;
8271         NewVD->setInvalidDecl();
8272         return;
8273       }
8274       if (NewVD->hasExternalStorage()) {
8275         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8276         NewVD->setInvalidDecl();
8277         return;
8278       }
8279     }
8280 
8281     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8282     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8283         NewVD->hasExternalStorage()) {
8284       if (!T->isSamplerT() && !T->isDependentType() &&
8285           !(T.getAddressSpace() == LangAS::opencl_constant ||
8286             (T.getAddressSpace() == LangAS::opencl_global &&
8287              getOpenCLOptions().areProgramScopeVariablesSupported(
8288                  getLangOpts())))) {
8289         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8290         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8291           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8292               << Scope << "global or constant";
8293         else
8294           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8295               << Scope << "constant";
8296         NewVD->setInvalidDecl();
8297         return;
8298       }
8299     } else {
8300       if (T.getAddressSpace() == LangAS::opencl_global) {
8301         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8302             << 1 /*is any function*/ << "global";
8303         NewVD->setInvalidDecl();
8304         return;
8305       }
8306       if (T.getAddressSpace() == LangAS::opencl_constant ||
8307           T.getAddressSpace() == LangAS::opencl_local) {
8308         FunctionDecl *FD = getCurFunctionDecl();
8309         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8310         // in functions.
8311         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8312           if (T.getAddressSpace() == LangAS::opencl_constant)
8313             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8314                 << 0 /*non-kernel only*/ << "constant";
8315           else
8316             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8317                 << 0 /*non-kernel only*/ << "local";
8318           NewVD->setInvalidDecl();
8319           return;
8320         }
8321         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8322         // in the outermost scope of a kernel function.
8323         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8324           if (!getCurScope()->isFunctionScope()) {
8325             if (T.getAddressSpace() == LangAS::opencl_constant)
8326               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8327                   << "constant";
8328             else
8329               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8330                   << "local";
8331             NewVD->setInvalidDecl();
8332             return;
8333           }
8334         }
8335       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8336                  // If we are parsing a template we didn't deduce an addr
8337                  // space yet.
8338                  T.getAddressSpace() != LangAS::Default) {
8339         // Do not allow other address spaces on automatic variable.
8340         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8341         NewVD->setInvalidDecl();
8342         return;
8343       }
8344     }
8345   }
8346 
8347   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8348       && !NewVD->hasAttr<BlocksAttr>()) {
8349     if (getLangOpts().getGC() != LangOptions::NonGC)
8350       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8351     else {
8352       assert(!getLangOpts().ObjCAutoRefCount);
8353       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8354     }
8355   }
8356 
8357   bool isVM = T->isVariablyModifiedType();
8358   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8359       NewVD->hasAttr<BlocksAttr>())
8360     setFunctionHasBranchProtectedScope();
8361 
8362   if ((isVM && NewVD->hasLinkage()) ||
8363       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8364     bool SizeIsNegative;
8365     llvm::APSInt Oversized;
8366     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8367         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8368     QualType FixedT;
8369     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8370       FixedT = FixedTInfo->getType();
8371     else if (FixedTInfo) {
8372       // Type and type-as-written are canonically different. We need to fix up
8373       // both types separately.
8374       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8375                                                    Oversized);
8376     }
8377     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8378       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8379       // FIXME: This won't give the correct result for
8380       // int a[10][n];
8381       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8382 
8383       if (NewVD->isFileVarDecl())
8384         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8385         << SizeRange;
8386       else if (NewVD->isStaticLocal())
8387         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8388         << SizeRange;
8389       else
8390         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8391         << SizeRange;
8392       NewVD->setInvalidDecl();
8393       return;
8394     }
8395 
8396     if (!FixedTInfo) {
8397       if (NewVD->isFileVarDecl())
8398         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8399       else
8400         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8401       NewVD->setInvalidDecl();
8402       return;
8403     }
8404 
8405     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8406     NewVD->setType(FixedT);
8407     NewVD->setTypeSourceInfo(FixedTInfo);
8408   }
8409 
8410   if (T->isVoidType()) {
8411     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8412     //                    of objects and functions.
8413     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8414       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8415         << T;
8416       NewVD->setInvalidDecl();
8417       return;
8418     }
8419   }
8420 
8421   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8422     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8423     NewVD->setInvalidDecl();
8424     return;
8425   }
8426 
8427   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8428     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8429     NewVD->setInvalidDecl();
8430     return;
8431   }
8432 
8433   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8434     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8435     NewVD->setInvalidDecl();
8436     return;
8437   }
8438 
8439   if (NewVD->isConstexpr() && !T->isDependentType() &&
8440       RequireLiteralType(NewVD->getLocation(), T,
8441                          diag::err_constexpr_var_non_literal)) {
8442     NewVD->setInvalidDecl();
8443     return;
8444   }
8445 
8446   // PPC MMA non-pointer types are not allowed as non-local variable types.
8447   if (Context.getTargetInfo().getTriple().isPPC64() &&
8448       !NewVD->isLocalVarDecl() &&
8449       CheckPPCMMAType(T, NewVD->getLocation())) {
8450     NewVD->setInvalidDecl();
8451     return;
8452   }
8453 }
8454 
8455 /// Perform semantic checking on a newly-created variable
8456 /// declaration.
8457 ///
8458 /// This routine performs all of the type-checking required for a
8459 /// variable declaration once it has been built. It is used both to
8460 /// check variables after they have been parsed and their declarators
8461 /// have been translated into a declaration, and to check variables
8462 /// that have been instantiated from a template.
8463 ///
8464 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8465 ///
8466 /// Returns true if the variable declaration is a redeclaration.
8467 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8468   CheckVariableDeclarationType(NewVD);
8469 
8470   // If the decl is already known invalid, don't check it.
8471   if (NewVD->isInvalidDecl())
8472     return false;
8473 
8474   // If we did not find anything by this name, look for a non-visible
8475   // extern "C" declaration with the same name.
8476   if (Previous.empty() &&
8477       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8478     Previous.setShadowed();
8479 
8480   if (!Previous.empty()) {
8481     MergeVarDecl(NewVD, Previous);
8482     return true;
8483   }
8484   return false;
8485 }
8486 
8487 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8488 /// and if so, check that it's a valid override and remember it.
8489 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8490   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8491 
8492   // Look for methods in base classes that this method might override.
8493   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8494                      /*DetectVirtual=*/false);
8495   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8496     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8497     DeclarationName Name = MD->getDeclName();
8498 
8499     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8500       // We really want to find the base class destructor here.
8501       QualType T = Context.getTypeDeclType(BaseRecord);
8502       CanQualType CT = Context.getCanonicalType(T);
8503       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8504     }
8505 
8506     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8507       CXXMethodDecl *BaseMD =
8508           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8509       if (!BaseMD || !BaseMD->isVirtual() ||
8510           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8511                      /*ConsiderCudaAttrs=*/true,
8512                      // C++2a [class.virtual]p2 does not consider requires
8513                      // clauses when overriding.
8514                      /*ConsiderRequiresClauses=*/false))
8515         continue;
8516 
8517       if (Overridden.insert(BaseMD).second) {
8518         MD->addOverriddenMethod(BaseMD);
8519         CheckOverridingFunctionReturnType(MD, BaseMD);
8520         CheckOverridingFunctionAttributes(MD, BaseMD);
8521         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8522         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8523       }
8524 
8525       // A method can only override one function from each base class. We
8526       // don't track indirectly overridden methods from bases of bases.
8527       return true;
8528     }
8529 
8530     return false;
8531   };
8532 
8533   DC->lookupInBases(VisitBase, Paths);
8534   return !Overridden.empty();
8535 }
8536 
8537 namespace {
8538   // Struct for holding all of the extra arguments needed by
8539   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8540   struct ActOnFDArgs {
8541     Scope *S;
8542     Declarator &D;
8543     MultiTemplateParamsArg TemplateParamLists;
8544     bool AddToScope;
8545   };
8546 } // end anonymous namespace
8547 
8548 namespace {
8549 
8550 // Callback to only accept typo corrections that have a non-zero edit distance.
8551 // Also only accept corrections that have the same parent decl.
8552 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8553  public:
8554   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8555                             CXXRecordDecl *Parent)
8556       : Context(Context), OriginalFD(TypoFD),
8557         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8558 
8559   bool ValidateCandidate(const TypoCorrection &candidate) override {
8560     if (candidate.getEditDistance() == 0)
8561       return false;
8562 
8563     SmallVector<unsigned, 1> MismatchedParams;
8564     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8565                                           CDeclEnd = candidate.end();
8566          CDecl != CDeclEnd; ++CDecl) {
8567       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8568 
8569       if (FD && !FD->hasBody() &&
8570           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8571         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8572           CXXRecordDecl *Parent = MD->getParent();
8573           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8574             return true;
8575         } else if (!ExpectedParent) {
8576           return true;
8577         }
8578       }
8579     }
8580 
8581     return false;
8582   }
8583 
8584   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8585     return std::make_unique<DifferentNameValidatorCCC>(*this);
8586   }
8587 
8588  private:
8589   ASTContext &Context;
8590   FunctionDecl *OriginalFD;
8591   CXXRecordDecl *ExpectedParent;
8592 };
8593 
8594 } // end anonymous namespace
8595 
8596 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8597   TypoCorrectedFunctionDefinitions.insert(F);
8598 }
8599 
8600 /// Generate diagnostics for an invalid function redeclaration.
8601 ///
8602 /// This routine handles generating the diagnostic messages for an invalid
8603 /// function redeclaration, including finding possible similar declarations
8604 /// or performing typo correction if there are no previous declarations with
8605 /// the same name.
8606 ///
8607 /// Returns a NamedDecl iff typo correction was performed and substituting in
8608 /// the new declaration name does not cause new errors.
8609 static NamedDecl *DiagnoseInvalidRedeclaration(
8610     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8611     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8612   DeclarationName Name = NewFD->getDeclName();
8613   DeclContext *NewDC = NewFD->getDeclContext();
8614   SmallVector<unsigned, 1> MismatchedParams;
8615   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8616   TypoCorrection Correction;
8617   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8618   unsigned DiagMsg =
8619     IsLocalFriend ? diag::err_no_matching_local_friend :
8620     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8621     diag::err_member_decl_does_not_match;
8622   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8623                     IsLocalFriend ? Sema::LookupLocalFriendName
8624                                   : Sema::LookupOrdinaryName,
8625                     Sema::ForVisibleRedeclaration);
8626 
8627   NewFD->setInvalidDecl();
8628   if (IsLocalFriend)
8629     SemaRef.LookupName(Prev, S);
8630   else
8631     SemaRef.LookupQualifiedName(Prev, NewDC);
8632   assert(!Prev.isAmbiguous() &&
8633          "Cannot have an ambiguity in previous-declaration lookup");
8634   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8635   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8636                                 MD ? MD->getParent() : nullptr);
8637   if (!Prev.empty()) {
8638     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8639          Func != FuncEnd; ++Func) {
8640       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8641       if (FD &&
8642           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8643         // Add 1 to the index so that 0 can mean the mismatch didn't
8644         // involve a parameter
8645         unsigned ParamNum =
8646             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8647         NearMatches.push_back(std::make_pair(FD, ParamNum));
8648       }
8649     }
8650   // If the qualified name lookup yielded nothing, try typo correction
8651   } else if ((Correction = SemaRef.CorrectTypo(
8652                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8653                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8654                   IsLocalFriend ? nullptr : NewDC))) {
8655     // Set up everything for the call to ActOnFunctionDeclarator
8656     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8657                               ExtraArgs.D.getIdentifierLoc());
8658     Previous.clear();
8659     Previous.setLookupName(Correction.getCorrection());
8660     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8661                                     CDeclEnd = Correction.end();
8662          CDecl != CDeclEnd; ++CDecl) {
8663       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8664       if (FD && !FD->hasBody() &&
8665           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8666         Previous.addDecl(FD);
8667       }
8668     }
8669     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8670 
8671     NamedDecl *Result;
8672     // Retry building the function declaration with the new previous
8673     // declarations, and with errors suppressed.
8674     {
8675       // Trap errors.
8676       Sema::SFINAETrap Trap(SemaRef);
8677 
8678       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8679       // pieces need to verify the typo-corrected C++ declaration and hopefully
8680       // eliminate the need for the parameter pack ExtraArgs.
8681       Result = SemaRef.ActOnFunctionDeclarator(
8682           ExtraArgs.S, ExtraArgs.D,
8683           Correction.getCorrectionDecl()->getDeclContext(),
8684           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8685           ExtraArgs.AddToScope);
8686 
8687       if (Trap.hasErrorOccurred())
8688         Result = nullptr;
8689     }
8690 
8691     if (Result) {
8692       // Determine which correction we picked.
8693       Decl *Canonical = Result->getCanonicalDecl();
8694       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8695            I != E; ++I)
8696         if ((*I)->getCanonicalDecl() == Canonical)
8697           Correction.setCorrectionDecl(*I);
8698 
8699       // Let Sema know about the correction.
8700       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8701       SemaRef.diagnoseTypo(
8702           Correction,
8703           SemaRef.PDiag(IsLocalFriend
8704                           ? diag::err_no_matching_local_friend_suggest
8705                           : diag::err_member_decl_does_not_match_suggest)
8706             << Name << NewDC << IsDefinition);
8707       return Result;
8708     }
8709 
8710     // Pretend the typo correction never occurred
8711     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8712                               ExtraArgs.D.getIdentifierLoc());
8713     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8714     Previous.clear();
8715     Previous.setLookupName(Name);
8716   }
8717 
8718   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8719       << Name << NewDC << IsDefinition << NewFD->getLocation();
8720 
8721   bool NewFDisConst = false;
8722   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8723     NewFDisConst = NewMD->isConst();
8724 
8725   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8726        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8727        NearMatch != NearMatchEnd; ++NearMatch) {
8728     FunctionDecl *FD = NearMatch->first;
8729     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8730     bool FDisConst = MD && MD->isConst();
8731     bool IsMember = MD || !IsLocalFriend;
8732 
8733     // FIXME: These notes are poorly worded for the local friend case.
8734     if (unsigned Idx = NearMatch->second) {
8735       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8736       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8737       if (Loc.isInvalid()) Loc = FD->getLocation();
8738       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8739                                  : diag::note_local_decl_close_param_match)
8740         << Idx << FDParam->getType()
8741         << NewFD->getParamDecl(Idx - 1)->getType();
8742     } else if (FDisConst != NewFDisConst) {
8743       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8744           << NewFDisConst << FD->getSourceRange().getEnd()
8745           << (NewFDisConst
8746                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8747                                                  .getConstQualifierLoc())
8748                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8749                                                    .getRParenLoc()
8750                                                    .getLocWithOffset(1),
8751                                                " const"));
8752     } else
8753       SemaRef.Diag(FD->getLocation(),
8754                    IsMember ? diag::note_member_def_close_match
8755                             : diag::note_local_decl_close_match);
8756   }
8757   return nullptr;
8758 }
8759 
8760 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8761   switch (D.getDeclSpec().getStorageClassSpec()) {
8762   default: llvm_unreachable("Unknown storage class!");
8763   case DeclSpec::SCS_auto:
8764   case DeclSpec::SCS_register:
8765   case DeclSpec::SCS_mutable:
8766     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8767                  diag::err_typecheck_sclass_func);
8768     D.getMutableDeclSpec().ClearStorageClassSpecs();
8769     D.setInvalidType();
8770     break;
8771   case DeclSpec::SCS_unspecified: break;
8772   case DeclSpec::SCS_extern:
8773     if (D.getDeclSpec().isExternInLinkageSpec())
8774       return SC_None;
8775     return SC_Extern;
8776   case DeclSpec::SCS_static: {
8777     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8778       // C99 6.7.1p5:
8779       //   The declaration of an identifier for a function that has
8780       //   block scope shall have no explicit storage-class specifier
8781       //   other than extern
8782       // See also (C++ [dcl.stc]p4).
8783       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8784                    diag::err_static_block_func);
8785       break;
8786     } else
8787       return SC_Static;
8788   }
8789   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8790   }
8791 
8792   // No explicit storage class has already been returned
8793   return SC_None;
8794 }
8795 
8796 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8797                                            DeclContext *DC, QualType &R,
8798                                            TypeSourceInfo *TInfo,
8799                                            StorageClass SC,
8800                                            bool &IsVirtualOkay) {
8801   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8802   DeclarationName Name = NameInfo.getName();
8803 
8804   FunctionDecl *NewFD = nullptr;
8805   bool isInline = D.getDeclSpec().isInlineSpecified();
8806 
8807   if (!SemaRef.getLangOpts().CPlusPlus) {
8808     // Determine whether the function was written with a prototype. This is
8809     // true when:
8810     //   - there is a prototype in the declarator, or
8811     //   - the type R of the function is some kind of typedef or other non-
8812     //     attributed reference to a type name (which eventually refers to a
8813     //     function type). Note, we can't always look at the adjusted type to
8814     //     check this case because attributes may cause a non-function
8815     //     declarator to still have a function type. e.g.,
8816     //       typedef void func(int a);
8817     //       __attribute__((noreturn)) func other_func; // This has a prototype
8818     bool HasPrototype =
8819         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8820         (D.getDeclSpec().isTypeRep() &&
8821          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8822         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8823     assert(
8824         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8825         "Strict prototypes are required");
8826 
8827     NewFD = FunctionDecl::Create(
8828         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8829         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8830         ConstexprSpecKind::Unspecified,
8831         /*TrailingRequiresClause=*/nullptr);
8832     if (D.isInvalidType())
8833       NewFD->setInvalidDecl();
8834 
8835     return NewFD;
8836   }
8837 
8838   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8839 
8840   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8841   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8842     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8843                  diag::err_constexpr_wrong_decl_kind)
8844         << static_cast<int>(ConstexprKind);
8845     ConstexprKind = ConstexprSpecKind::Unspecified;
8846     D.getMutableDeclSpec().ClearConstexprSpec();
8847   }
8848   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8849 
8850   // Check that the return type is not an abstract class type.
8851   // For record types, this is done by the AbstractClassUsageDiagnoser once
8852   // the class has been completely parsed.
8853   if (!DC->isRecord() &&
8854       SemaRef.RequireNonAbstractType(
8855           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8856           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8857     D.setInvalidType();
8858 
8859   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8860     // This is a C++ constructor declaration.
8861     assert(DC->isRecord() &&
8862            "Constructors can only be declared in a member context");
8863 
8864     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8865     return CXXConstructorDecl::Create(
8866         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8867         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8868         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8869         InheritedConstructor(), TrailingRequiresClause);
8870 
8871   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8872     // This is a C++ destructor declaration.
8873     if (DC->isRecord()) {
8874       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8875       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8876       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8877           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8878           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8879           /*isImplicitlyDeclared=*/false, ConstexprKind,
8880           TrailingRequiresClause);
8881 
8882       // If the destructor needs an implicit exception specification, set it
8883       // now. FIXME: It'd be nice to be able to create the right type to start
8884       // with, but the type needs to reference the destructor declaration.
8885       if (SemaRef.getLangOpts().CPlusPlus11)
8886         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8887 
8888       IsVirtualOkay = true;
8889       return NewDD;
8890 
8891     } else {
8892       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8893       D.setInvalidType();
8894 
8895       // Create a FunctionDecl to satisfy the function definition parsing
8896       // code path.
8897       return FunctionDecl::Create(
8898           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8899           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8900           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8901     }
8902 
8903   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8904     if (!DC->isRecord()) {
8905       SemaRef.Diag(D.getIdentifierLoc(),
8906            diag::err_conv_function_not_member);
8907       return nullptr;
8908     }
8909 
8910     SemaRef.CheckConversionDeclarator(D, R, SC);
8911     if (D.isInvalidType())
8912       return nullptr;
8913 
8914     IsVirtualOkay = true;
8915     return CXXConversionDecl::Create(
8916         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8917         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8918         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8919         TrailingRequiresClause);
8920 
8921   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8922     if (TrailingRequiresClause)
8923       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8924                    diag::err_trailing_requires_clause_on_deduction_guide)
8925           << TrailingRequiresClause->getSourceRange();
8926     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8927 
8928     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8929                                          ExplicitSpecifier, NameInfo, R, TInfo,
8930                                          D.getEndLoc());
8931   } else if (DC->isRecord()) {
8932     // If the name of the function is the same as the name of the record,
8933     // then this must be an invalid constructor that has a return type.
8934     // (The parser checks for a return type and makes the declarator a
8935     // constructor if it has no return type).
8936     if (Name.getAsIdentifierInfo() &&
8937         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8938       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8939         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8940         << SourceRange(D.getIdentifierLoc());
8941       return nullptr;
8942     }
8943 
8944     // This is a C++ method declaration.
8945     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8946         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8947         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8948         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8949     IsVirtualOkay = !Ret->isStatic();
8950     return Ret;
8951   } else {
8952     bool isFriend =
8953         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8954     if (!isFriend && SemaRef.CurContext->isRecord())
8955       return nullptr;
8956 
8957     // Determine whether the function was written with a
8958     // prototype. This true when:
8959     //   - we're in C++ (where every function has a prototype),
8960     return FunctionDecl::Create(
8961         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8962         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8963         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8964   }
8965 }
8966 
8967 enum OpenCLParamType {
8968   ValidKernelParam,
8969   PtrPtrKernelParam,
8970   PtrKernelParam,
8971   InvalidAddrSpacePtrKernelParam,
8972   InvalidKernelParam,
8973   RecordKernelParam
8974 };
8975 
8976 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8977   // Size dependent types are just typedefs to normal integer types
8978   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8979   // integers other than by their names.
8980   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8981 
8982   // Remove typedefs one by one until we reach a typedef
8983   // for a size dependent type.
8984   QualType DesugaredTy = Ty;
8985   do {
8986     ArrayRef<StringRef> Names(SizeTypeNames);
8987     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8988     if (Names.end() != Match)
8989       return true;
8990 
8991     Ty = DesugaredTy;
8992     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8993   } while (DesugaredTy != Ty);
8994 
8995   return false;
8996 }
8997 
8998 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8999   if (PT->isDependentType())
9000     return InvalidKernelParam;
9001 
9002   if (PT->isPointerType() || PT->isReferenceType()) {
9003     QualType PointeeType = PT->getPointeeType();
9004     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9005         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9006         PointeeType.getAddressSpace() == LangAS::Default)
9007       return InvalidAddrSpacePtrKernelParam;
9008 
9009     if (PointeeType->isPointerType()) {
9010       // This is a pointer to pointer parameter.
9011       // Recursively check inner type.
9012       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9013       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9014           ParamKind == InvalidKernelParam)
9015         return ParamKind;
9016 
9017       return PtrPtrKernelParam;
9018     }
9019 
9020     // C++ for OpenCL v1.0 s2.4:
9021     // Moreover the types used in parameters of the kernel functions must be:
9022     // Standard layout types for pointer parameters. The same applies to
9023     // reference if an implementation supports them in kernel parameters.
9024     if (S.getLangOpts().OpenCLCPlusPlus &&
9025         !S.getOpenCLOptions().isAvailableOption(
9026             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9027         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9028         !PointeeType->isStandardLayoutType())
9029       return InvalidKernelParam;
9030 
9031     return PtrKernelParam;
9032   }
9033 
9034   // OpenCL v1.2 s6.9.k:
9035   // Arguments to kernel functions in a program cannot be declared with the
9036   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9037   // uintptr_t or a struct and/or union that contain fields declared to be one
9038   // of these built-in scalar types.
9039   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9040     return InvalidKernelParam;
9041 
9042   if (PT->isImageType())
9043     return PtrKernelParam;
9044 
9045   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9046     return InvalidKernelParam;
9047 
9048   // OpenCL extension spec v1.2 s9.5:
9049   // This extension adds support for half scalar and vector types as built-in
9050   // types that can be used for arithmetic operations, conversions etc.
9051   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9052       PT->isHalfType())
9053     return InvalidKernelParam;
9054 
9055   // Look into an array argument to check if it has a forbidden type.
9056   if (PT->isArrayType()) {
9057     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9058     // Call ourself to check an underlying type of an array. Since the
9059     // getPointeeOrArrayElementType returns an innermost type which is not an
9060     // array, this recursive call only happens once.
9061     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9062   }
9063 
9064   // C++ for OpenCL v1.0 s2.4:
9065   // Moreover the types used in parameters of the kernel functions must be:
9066   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9067   // types) for parameters passed by value;
9068   if (S.getLangOpts().OpenCLCPlusPlus &&
9069       !S.getOpenCLOptions().isAvailableOption(
9070           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9071       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9072     return InvalidKernelParam;
9073 
9074   if (PT->isRecordType())
9075     return RecordKernelParam;
9076 
9077   return ValidKernelParam;
9078 }
9079 
9080 static void checkIsValidOpenCLKernelParameter(
9081   Sema &S,
9082   Declarator &D,
9083   ParmVarDecl *Param,
9084   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9085   QualType PT = Param->getType();
9086 
9087   // Cache the valid types we encounter to avoid rechecking structs that are
9088   // used again
9089   if (ValidTypes.count(PT.getTypePtr()))
9090     return;
9091 
9092   switch (getOpenCLKernelParameterType(S, PT)) {
9093   case PtrPtrKernelParam:
9094     // OpenCL v3.0 s6.11.a:
9095     // A kernel function argument cannot be declared as a pointer to a pointer
9096     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9097     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9098       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9099       D.setInvalidType();
9100       return;
9101     }
9102 
9103     ValidTypes.insert(PT.getTypePtr());
9104     return;
9105 
9106   case InvalidAddrSpacePtrKernelParam:
9107     // OpenCL v1.0 s6.5:
9108     // __kernel function arguments declared to be a pointer of a type can point
9109     // to one of the following address spaces only : __global, __local or
9110     // __constant.
9111     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9112     D.setInvalidType();
9113     return;
9114 
9115     // OpenCL v1.2 s6.9.k:
9116     // Arguments to kernel functions in a program cannot be declared with the
9117     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9118     // uintptr_t or a struct and/or union that contain fields declared to be
9119     // one of these built-in scalar types.
9120 
9121   case InvalidKernelParam:
9122     // OpenCL v1.2 s6.8 n:
9123     // A kernel function argument cannot be declared
9124     // of event_t type.
9125     // Do not diagnose half type since it is diagnosed as invalid argument
9126     // type for any function elsewhere.
9127     if (!PT->isHalfType()) {
9128       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9129 
9130       // Explain what typedefs are involved.
9131       const TypedefType *Typedef = nullptr;
9132       while ((Typedef = PT->getAs<TypedefType>())) {
9133         SourceLocation Loc = Typedef->getDecl()->getLocation();
9134         // SourceLocation may be invalid for a built-in type.
9135         if (Loc.isValid())
9136           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9137         PT = Typedef->desugar();
9138       }
9139     }
9140 
9141     D.setInvalidType();
9142     return;
9143 
9144   case PtrKernelParam:
9145   case ValidKernelParam:
9146     ValidTypes.insert(PT.getTypePtr());
9147     return;
9148 
9149   case RecordKernelParam:
9150     break;
9151   }
9152 
9153   // Track nested structs we will inspect
9154   SmallVector<const Decl *, 4> VisitStack;
9155 
9156   // Track where we are in the nested structs. Items will migrate from
9157   // VisitStack to HistoryStack as we do the DFS for bad field.
9158   SmallVector<const FieldDecl *, 4> HistoryStack;
9159   HistoryStack.push_back(nullptr);
9160 
9161   // At this point we already handled everything except of a RecordType or
9162   // an ArrayType of a RecordType.
9163   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9164   const RecordType *RecTy =
9165       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9166   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9167 
9168   VisitStack.push_back(RecTy->getDecl());
9169   assert(VisitStack.back() && "First decl null?");
9170 
9171   do {
9172     const Decl *Next = VisitStack.pop_back_val();
9173     if (!Next) {
9174       assert(!HistoryStack.empty());
9175       // Found a marker, we have gone up a level
9176       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9177         ValidTypes.insert(Hist->getType().getTypePtr());
9178 
9179       continue;
9180     }
9181 
9182     // Adds everything except the original parameter declaration (which is not a
9183     // field itself) to the history stack.
9184     const RecordDecl *RD;
9185     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9186       HistoryStack.push_back(Field);
9187 
9188       QualType FieldTy = Field->getType();
9189       // Other field types (known to be valid or invalid) are handled while we
9190       // walk around RecordDecl::fields().
9191       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9192              "Unexpected type.");
9193       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9194 
9195       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9196     } else {
9197       RD = cast<RecordDecl>(Next);
9198     }
9199 
9200     // Add a null marker so we know when we've gone back up a level
9201     VisitStack.push_back(nullptr);
9202 
9203     for (const auto *FD : RD->fields()) {
9204       QualType QT = FD->getType();
9205 
9206       if (ValidTypes.count(QT.getTypePtr()))
9207         continue;
9208 
9209       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9210       if (ParamType == ValidKernelParam)
9211         continue;
9212 
9213       if (ParamType == RecordKernelParam) {
9214         VisitStack.push_back(FD);
9215         continue;
9216       }
9217 
9218       // OpenCL v1.2 s6.9.p:
9219       // Arguments to kernel functions that are declared to be a struct or union
9220       // do not allow OpenCL objects to be passed as elements of the struct or
9221       // union.
9222       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9223           ParamType == InvalidAddrSpacePtrKernelParam) {
9224         S.Diag(Param->getLocation(),
9225                diag::err_record_with_pointers_kernel_param)
9226           << PT->isUnionType()
9227           << PT;
9228       } else {
9229         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9230       }
9231 
9232       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9233           << OrigRecDecl->getDeclName();
9234 
9235       // We have an error, now let's go back up through history and show where
9236       // the offending field came from
9237       for (ArrayRef<const FieldDecl *>::const_iterator
9238                I = HistoryStack.begin() + 1,
9239                E = HistoryStack.end();
9240            I != E; ++I) {
9241         const FieldDecl *OuterField = *I;
9242         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9243           << OuterField->getType();
9244       }
9245 
9246       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9247         << QT->isPointerType()
9248         << QT;
9249       D.setInvalidType();
9250       return;
9251     }
9252   } while (!VisitStack.empty());
9253 }
9254 
9255 /// Find the DeclContext in which a tag is implicitly declared if we see an
9256 /// elaborated type specifier in the specified context, and lookup finds
9257 /// nothing.
9258 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9259   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9260     DC = DC->getParent();
9261   return DC;
9262 }
9263 
9264 /// Find the Scope in which a tag is implicitly declared if we see an
9265 /// elaborated type specifier in the specified context, and lookup finds
9266 /// nothing.
9267 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9268   while (S->isClassScope() ||
9269          (LangOpts.CPlusPlus &&
9270           S->isFunctionPrototypeScope()) ||
9271          ((S->getFlags() & Scope::DeclScope) == 0) ||
9272          (S->getEntity() && S->getEntity()->isTransparentContext()))
9273     S = S->getParent();
9274   return S;
9275 }
9276 
9277 /// Determine whether a declaration matches a known function in namespace std.
9278 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9279                          unsigned BuiltinID) {
9280   switch (BuiltinID) {
9281   case Builtin::BI__GetExceptionInfo:
9282     // No type checking whatsoever.
9283     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9284 
9285   case Builtin::BIaddressof:
9286   case Builtin::BI__addressof:
9287   case Builtin::BIforward:
9288   case Builtin::BImove:
9289   case Builtin::BImove_if_noexcept:
9290   case Builtin::BIas_const: {
9291     // Ensure that we don't treat the algorithm
9292     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9293     // as the builtin std::move.
9294     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9295     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9296   }
9297 
9298   default:
9299     return false;
9300   }
9301 }
9302 
9303 NamedDecl*
9304 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9305                               TypeSourceInfo *TInfo, LookupResult &Previous,
9306                               MultiTemplateParamsArg TemplateParamListsRef,
9307                               bool &AddToScope) {
9308   QualType R = TInfo->getType();
9309 
9310   assert(R->isFunctionType());
9311   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9312     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9313 
9314   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9315   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9316   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9317     if (!TemplateParamLists.empty() &&
9318         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9319       TemplateParamLists.back() = Invented;
9320     else
9321       TemplateParamLists.push_back(Invented);
9322   }
9323 
9324   // TODO: consider using NameInfo for diagnostic.
9325   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9326   DeclarationName Name = NameInfo.getName();
9327   StorageClass SC = getFunctionStorageClass(*this, D);
9328 
9329   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9330     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9331          diag::err_invalid_thread)
9332       << DeclSpec::getSpecifierName(TSCS);
9333 
9334   if (D.isFirstDeclarationOfMember())
9335     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9336                            D.getIdentifierLoc());
9337 
9338   bool isFriend = false;
9339   FunctionTemplateDecl *FunctionTemplate = nullptr;
9340   bool isMemberSpecialization = false;
9341   bool isFunctionTemplateSpecialization = false;
9342 
9343   bool isDependentClassScopeExplicitSpecialization = false;
9344   bool HasExplicitTemplateArgs = false;
9345   TemplateArgumentListInfo TemplateArgs;
9346 
9347   bool isVirtualOkay = false;
9348 
9349   DeclContext *OriginalDC = DC;
9350   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9351 
9352   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9353                                               isVirtualOkay);
9354   if (!NewFD) return nullptr;
9355 
9356   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9357     NewFD->setTopLevelDeclInObjCContainer();
9358 
9359   // Set the lexical context. If this is a function-scope declaration, or has a
9360   // C++ scope specifier, or is the object of a friend declaration, the lexical
9361   // context will be different from the semantic context.
9362   NewFD->setLexicalDeclContext(CurContext);
9363 
9364   if (IsLocalExternDecl)
9365     NewFD->setLocalExternDecl();
9366 
9367   if (getLangOpts().CPlusPlus) {
9368     bool isInline = D.getDeclSpec().isInlineSpecified();
9369     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9370     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9371     isFriend = D.getDeclSpec().isFriendSpecified();
9372     if (isFriend && !isInline && D.isFunctionDefinition()) {
9373       // C++ [class.friend]p5
9374       //   A function can be defined in a friend declaration of a
9375       //   class . . . . Such a function is implicitly inline.
9376       NewFD->setImplicitlyInline();
9377     }
9378 
9379     // If this is a method defined in an __interface, and is not a constructor
9380     // or an overloaded operator, then set the pure flag (isVirtual will already
9381     // return true).
9382     if (const CXXRecordDecl *Parent =
9383           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9384       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9385         NewFD->setPure(true);
9386 
9387       // C++ [class.union]p2
9388       //   A union can have member functions, but not virtual functions.
9389       if (isVirtual && Parent->isUnion()) {
9390         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9391         NewFD->setInvalidDecl();
9392       }
9393       if ((Parent->isClass() || Parent->isStruct()) &&
9394           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9395           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9396           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9397         if (auto *Def = Parent->getDefinition())
9398           Def->setInitMethod(true);
9399       }
9400     }
9401 
9402     SetNestedNameSpecifier(*this, NewFD, D);
9403     isMemberSpecialization = false;
9404     isFunctionTemplateSpecialization = false;
9405     if (D.isInvalidType())
9406       NewFD->setInvalidDecl();
9407 
9408     // Match up the template parameter lists with the scope specifier, then
9409     // determine whether we have a template or a template specialization.
9410     bool Invalid = false;
9411     TemplateParameterList *TemplateParams =
9412         MatchTemplateParametersToScopeSpecifier(
9413             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9414             D.getCXXScopeSpec(),
9415             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9416                 ? D.getName().TemplateId
9417                 : nullptr,
9418             TemplateParamLists, isFriend, isMemberSpecialization,
9419             Invalid);
9420     if (TemplateParams) {
9421       // Check that we can declare a template here.
9422       if (CheckTemplateDeclScope(S, TemplateParams))
9423         NewFD->setInvalidDecl();
9424 
9425       if (TemplateParams->size() > 0) {
9426         // This is a function template
9427 
9428         // A destructor cannot be a template.
9429         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9430           Diag(NewFD->getLocation(), diag::err_destructor_template);
9431           NewFD->setInvalidDecl();
9432         }
9433 
9434         // If we're adding a template to a dependent context, we may need to
9435         // rebuilding some of the types used within the template parameter list,
9436         // now that we know what the current instantiation is.
9437         if (DC->isDependentContext()) {
9438           ContextRAII SavedContext(*this, DC);
9439           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9440             Invalid = true;
9441         }
9442 
9443         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9444                                                         NewFD->getLocation(),
9445                                                         Name, TemplateParams,
9446                                                         NewFD);
9447         FunctionTemplate->setLexicalDeclContext(CurContext);
9448         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9449 
9450         // For source fidelity, store the other template param lists.
9451         if (TemplateParamLists.size() > 1) {
9452           NewFD->setTemplateParameterListsInfo(Context,
9453               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9454                   .drop_back(1));
9455         }
9456       } else {
9457         // This is a function template specialization.
9458         isFunctionTemplateSpecialization = true;
9459         // For source fidelity, store all the template param lists.
9460         if (TemplateParamLists.size() > 0)
9461           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9462 
9463         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9464         if (isFriend) {
9465           // We want to remove the "template<>", found here.
9466           SourceRange RemoveRange = TemplateParams->getSourceRange();
9467 
9468           // If we remove the template<> and the name is not a
9469           // template-id, we're actually silently creating a problem:
9470           // the friend declaration will refer to an untemplated decl,
9471           // and clearly the user wants a template specialization.  So
9472           // we need to insert '<>' after the name.
9473           SourceLocation InsertLoc;
9474           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9475             InsertLoc = D.getName().getSourceRange().getEnd();
9476             InsertLoc = getLocForEndOfToken(InsertLoc);
9477           }
9478 
9479           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9480             << Name << RemoveRange
9481             << FixItHint::CreateRemoval(RemoveRange)
9482             << FixItHint::CreateInsertion(InsertLoc, "<>");
9483           Invalid = true;
9484         }
9485       }
9486     } else {
9487       // Check that we can declare a template here.
9488       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9489           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9490         NewFD->setInvalidDecl();
9491 
9492       // All template param lists were matched against the scope specifier:
9493       // this is NOT (an explicit specialization of) a template.
9494       if (TemplateParamLists.size() > 0)
9495         // For source fidelity, store all the template param lists.
9496         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9497     }
9498 
9499     if (Invalid) {
9500       NewFD->setInvalidDecl();
9501       if (FunctionTemplate)
9502         FunctionTemplate->setInvalidDecl();
9503     }
9504 
9505     // C++ [dcl.fct.spec]p5:
9506     //   The virtual specifier shall only be used in declarations of
9507     //   nonstatic class member functions that appear within a
9508     //   member-specification of a class declaration; see 10.3.
9509     //
9510     if (isVirtual && !NewFD->isInvalidDecl()) {
9511       if (!isVirtualOkay) {
9512         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9513              diag::err_virtual_non_function);
9514       } else if (!CurContext->isRecord()) {
9515         // 'virtual' was specified outside of the class.
9516         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9517              diag::err_virtual_out_of_class)
9518           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9519       } else if (NewFD->getDescribedFunctionTemplate()) {
9520         // C++ [temp.mem]p3:
9521         //  A member function template shall not be virtual.
9522         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9523              diag::err_virtual_member_function_template)
9524           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9525       } else {
9526         // Okay: Add virtual to the method.
9527         NewFD->setVirtualAsWritten(true);
9528       }
9529 
9530       if (getLangOpts().CPlusPlus14 &&
9531           NewFD->getReturnType()->isUndeducedType())
9532         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9533     }
9534 
9535     if (getLangOpts().CPlusPlus14 &&
9536         (NewFD->isDependentContext() ||
9537          (isFriend && CurContext->isDependentContext())) &&
9538         NewFD->getReturnType()->isUndeducedType()) {
9539       // If the function template is referenced directly (for instance, as a
9540       // member of the current instantiation), pretend it has a dependent type.
9541       // This is not really justified by the standard, but is the only sane
9542       // thing to do.
9543       // FIXME: For a friend function, we have not marked the function as being
9544       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9545       const FunctionProtoType *FPT =
9546           NewFD->getType()->castAs<FunctionProtoType>();
9547       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9548       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9549                                              FPT->getExtProtoInfo()));
9550     }
9551 
9552     // C++ [dcl.fct.spec]p3:
9553     //  The inline specifier shall not appear on a block scope function
9554     //  declaration.
9555     if (isInline && !NewFD->isInvalidDecl()) {
9556       if (CurContext->isFunctionOrMethod()) {
9557         // 'inline' is not allowed on block scope function declaration.
9558         Diag(D.getDeclSpec().getInlineSpecLoc(),
9559              diag::err_inline_declaration_block_scope) << Name
9560           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9561       }
9562     }
9563 
9564     // C++ [dcl.fct.spec]p6:
9565     //  The explicit specifier shall be used only in the declaration of a
9566     //  constructor or conversion function within its class definition;
9567     //  see 12.3.1 and 12.3.2.
9568     if (hasExplicit && !NewFD->isInvalidDecl() &&
9569         !isa<CXXDeductionGuideDecl>(NewFD)) {
9570       if (!CurContext->isRecord()) {
9571         // 'explicit' was specified outside of the class.
9572         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9573              diag::err_explicit_out_of_class)
9574             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9575       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9576                  !isa<CXXConversionDecl>(NewFD)) {
9577         // 'explicit' was specified on a function that wasn't a constructor
9578         // or conversion function.
9579         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9580              diag::err_explicit_non_ctor_or_conv_function)
9581             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9582       }
9583     }
9584 
9585     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9586     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9587       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9588       // are implicitly inline.
9589       NewFD->setImplicitlyInline();
9590 
9591       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9592       // be either constructors or to return a literal type. Therefore,
9593       // destructors cannot be declared constexpr.
9594       if (isa<CXXDestructorDecl>(NewFD) &&
9595           (!getLangOpts().CPlusPlus20 ||
9596            ConstexprKind == ConstexprSpecKind::Consteval)) {
9597         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9598             << static_cast<int>(ConstexprKind);
9599         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9600                                     ? ConstexprSpecKind::Unspecified
9601                                     : ConstexprSpecKind::Constexpr);
9602       }
9603       // C++20 [dcl.constexpr]p2: An allocation function, or a
9604       // deallocation function shall not be declared with the consteval
9605       // specifier.
9606       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9607           (NewFD->getOverloadedOperator() == OO_New ||
9608            NewFD->getOverloadedOperator() == OO_Array_New ||
9609            NewFD->getOverloadedOperator() == OO_Delete ||
9610            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9611         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9612              diag::err_invalid_consteval_decl_kind)
9613             << NewFD;
9614         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9615       }
9616     }
9617 
9618     // If __module_private__ was specified, mark the function accordingly.
9619     if (D.getDeclSpec().isModulePrivateSpecified()) {
9620       if (isFunctionTemplateSpecialization) {
9621         SourceLocation ModulePrivateLoc
9622           = D.getDeclSpec().getModulePrivateSpecLoc();
9623         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9624           << 0
9625           << FixItHint::CreateRemoval(ModulePrivateLoc);
9626       } else {
9627         NewFD->setModulePrivate();
9628         if (FunctionTemplate)
9629           FunctionTemplate->setModulePrivate();
9630       }
9631     }
9632 
9633     if (isFriend) {
9634       if (FunctionTemplate) {
9635         FunctionTemplate->setObjectOfFriendDecl();
9636         FunctionTemplate->setAccess(AS_public);
9637       }
9638       NewFD->setObjectOfFriendDecl();
9639       NewFD->setAccess(AS_public);
9640     }
9641 
9642     // If a function is defined as defaulted or deleted, mark it as such now.
9643     // We'll do the relevant checks on defaulted / deleted functions later.
9644     switch (D.getFunctionDefinitionKind()) {
9645     case FunctionDefinitionKind::Declaration:
9646     case FunctionDefinitionKind::Definition:
9647       break;
9648 
9649     case FunctionDefinitionKind::Defaulted:
9650       NewFD->setDefaulted();
9651       break;
9652 
9653     case FunctionDefinitionKind::Deleted:
9654       NewFD->setDeletedAsWritten();
9655       break;
9656     }
9657 
9658     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9659         D.isFunctionDefinition()) {
9660       // C++ [class.mfct]p2:
9661       //   A member function may be defined (8.4) in its class definition, in
9662       //   which case it is an inline member function (7.1.2)
9663       NewFD->setImplicitlyInline();
9664     }
9665 
9666     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9667         !CurContext->isRecord()) {
9668       // C++ [class.static]p1:
9669       //   A data or function member of a class may be declared static
9670       //   in a class definition, in which case it is a static member of
9671       //   the class.
9672 
9673       // Complain about the 'static' specifier if it's on an out-of-line
9674       // member function definition.
9675 
9676       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9677       // member function template declaration and class member template
9678       // declaration (MSVC versions before 2015), warn about this.
9679       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9680            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9681              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9682            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9683            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9684         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9685     }
9686 
9687     // C++11 [except.spec]p15:
9688     //   A deallocation function with no exception-specification is treated
9689     //   as if it were specified with noexcept(true).
9690     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9691     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9692          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9693         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9694       NewFD->setType(Context.getFunctionType(
9695           FPT->getReturnType(), FPT->getParamTypes(),
9696           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9697   }
9698 
9699   // Filter out previous declarations that don't match the scope.
9700   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9701                        D.getCXXScopeSpec().isNotEmpty() ||
9702                        isMemberSpecialization ||
9703                        isFunctionTemplateSpecialization);
9704 
9705   // Handle GNU asm-label extension (encoded as an attribute).
9706   if (Expr *E = (Expr*) D.getAsmLabel()) {
9707     // The parser guarantees this is a string.
9708     StringLiteral *SE = cast<StringLiteral>(E);
9709     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9710                                         /*IsLiteralLabel=*/true,
9711                                         SE->getStrTokenLoc(0)));
9712   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9713     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9714       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9715     if (I != ExtnameUndeclaredIdentifiers.end()) {
9716       if (isDeclExternC(NewFD)) {
9717         NewFD->addAttr(I->second);
9718         ExtnameUndeclaredIdentifiers.erase(I);
9719       } else
9720         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9721             << /*Variable*/0 << NewFD;
9722     }
9723   }
9724 
9725   // Copy the parameter declarations from the declarator D to the function
9726   // declaration NewFD, if they are available.  First scavenge them into Params.
9727   SmallVector<ParmVarDecl*, 16> Params;
9728   unsigned FTIIdx;
9729   if (D.isFunctionDeclarator(FTIIdx)) {
9730     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9731 
9732     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9733     // function that takes no arguments, not a function that takes a
9734     // single void argument.
9735     // We let through "const void" here because Sema::GetTypeForDeclarator
9736     // already checks for that case.
9737     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9738       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9739         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9740         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9741         Param->setDeclContext(NewFD);
9742         Params.push_back(Param);
9743 
9744         if (Param->isInvalidDecl())
9745           NewFD->setInvalidDecl();
9746       }
9747     }
9748 
9749     if (!getLangOpts().CPlusPlus) {
9750       // In C, find all the tag declarations from the prototype and move them
9751       // into the function DeclContext. Remove them from the surrounding tag
9752       // injection context of the function, which is typically but not always
9753       // the TU.
9754       DeclContext *PrototypeTagContext =
9755           getTagInjectionContext(NewFD->getLexicalDeclContext());
9756       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9757         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9758 
9759         // We don't want to reparent enumerators. Look at their parent enum
9760         // instead.
9761         if (!TD) {
9762           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9763             TD = cast<EnumDecl>(ECD->getDeclContext());
9764         }
9765         if (!TD)
9766           continue;
9767         DeclContext *TagDC = TD->getLexicalDeclContext();
9768         if (!TagDC->containsDecl(TD))
9769           continue;
9770         TagDC->removeDecl(TD);
9771         TD->setDeclContext(NewFD);
9772         NewFD->addDecl(TD);
9773 
9774         // Preserve the lexical DeclContext if it is not the surrounding tag
9775         // injection context of the FD. In this example, the semantic context of
9776         // E will be f and the lexical context will be S, while both the
9777         // semantic and lexical contexts of S will be f:
9778         //   void f(struct S { enum E { a } f; } s);
9779         if (TagDC != PrototypeTagContext)
9780           TD->setLexicalDeclContext(TagDC);
9781       }
9782     }
9783   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9784     // When we're declaring a function with a typedef, typeof, etc as in the
9785     // following example, we'll need to synthesize (unnamed)
9786     // parameters for use in the declaration.
9787     //
9788     // @code
9789     // typedef void fn(int);
9790     // fn f;
9791     // @endcode
9792 
9793     // Synthesize a parameter for each argument type.
9794     for (const auto &AI : FT->param_types()) {
9795       ParmVarDecl *Param =
9796           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9797       Param->setScopeInfo(0, Params.size());
9798       Params.push_back(Param);
9799     }
9800   } else {
9801     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9802            "Should not need args for typedef of non-prototype fn");
9803   }
9804 
9805   // Finally, we know we have the right number of parameters, install them.
9806   NewFD->setParams(Params);
9807 
9808   if (D.getDeclSpec().isNoreturnSpecified())
9809     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9810                                            D.getDeclSpec().getNoreturnSpecLoc(),
9811                                            AttributeCommonInfo::AS_Keyword));
9812 
9813   // Functions returning a variably modified type violate C99 6.7.5.2p2
9814   // because all functions have linkage.
9815   if (!NewFD->isInvalidDecl() &&
9816       NewFD->getReturnType()->isVariablyModifiedType()) {
9817     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9818     NewFD->setInvalidDecl();
9819   }
9820 
9821   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9822   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9823       !NewFD->hasAttr<SectionAttr>())
9824     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9825         Context, PragmaClangTextSection.SectionName,
9826         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9827 
9828   // Apply an implicit SectionAttr if #pragma code_seg is active.
9829   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9830       !NewFD->hasAttr<SectionAttr>()) {
9831     NewFD->addAttr(SectionAttr::CreateImplicit(
9832         Context, CodeSegStack.CurrentValue->getString(),
9833         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9834         SectionAttr::Declspec_allocate));
9835     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9836                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9837                          ASTContext::PSF_Read,
9838                      NewFD))
9839       NewFD->dropAttr<SectionAttr>();
9840   }
9841 
9842   // Apply an implicit CodeSegAttr from class declspec or
9843   // apply an implicit SectionAttr from #pragma code_seg if active.
9844   if (!NewFD->hasAttr<CodeSegAttr>()) {
9845     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9846                                                                  D.isFunctionDefinition())) {
9847       NewFD->addAttr(SAttr);
9848     }
9849   }
9850 
9851   // Handle attributes.
9852   ProcessDeclAttributes(S, NewFD, D);
9853 
9854   if (getLangOpts().OpenCL) {
9855     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9856     // type declaration will generate a compilation error.
9857     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9858     if (AddressSpace != LangAS::Default) {
9859       Diag(NewFD->getLocation(),
9860            diag::err_opencl_return_value_with_address_space);
9861       NewFD->setInvalidDecl();
9862     }
9863   }
9864 
9865   if (!getLangOpts().CPlusPlus) {
9866     // Perform semantic checking on the function declaration.
9867     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9868       CheckMain(NewFD, D.getDeclSpec());
9869 
9870     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9871       CheckMSVCRTEntryPoint(NewFD);
9872 
9873     if (!NewFD->isInvalidDecl())
9874       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9875                                                   isMemberSpecialization,
9876                                                   D.isFunctionDefinition()));
9877     else if (!Previous.empty())
9878       // Recover gracefully from an invalid redeclaration.
9879       D.setRedeclaration(true);
9880     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9881             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9882            "previous declaration set still overloaded");
9883 
9884     // Diagnose no-prototype function declarations with calling conventions that
9885     // don't support variadic calls. Only do this in C and do it after merging
9886     // possibly prototyped redeclarations.
9887     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9888     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9889       CallingConv CC = FT->getExtInfo().getCC();
9890       if (!supportsVariadicCall(CC)) {
9891         // Windows system headers sometimes accidentally use stdcall without
9892         // (void) parameters, so we relax this to a warning.
9893         int DiagID =
9894             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9895         Diag(NewFD->getLocation(), DiagID)
9896             << FunctionType::getNameForCallConv(CC);
9897       }
9898     }
9899 
9900    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9901        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9902      checkNonTrivialCUnion(NewFD->getReturnType(),
9903                            NewFD->getReturnTypeSourceRange().getBegin(),
9904                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9905   } else {
9906     // C++11 [replacement.functions]p3:
9907     //  The program's definitions shall not be specified as inline.
9908     //
9909     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9910     //
9911     // Suppress the diagnostic if the function is __attribute__((used)), since
9912     // that forces an external definition to be emitted.
9913     if (D.getDeclSpec().isInlineSpecified() &&
9914         NewFD->isReplaceableGlobalAllocationFunction() &&
9915         !NewFD->hasAttr<UsedAttr>())
9916       Diag(D.getDeclSpec().getInlineSpecLoc(),
9917            diag::ext_operator_new_delete_declared_inline)
9918         << NewFD->getDeclName();
9919 
9920     // If the declarator is a template-id, translate the parser's template
9921     // argument list into our AST format.
9922     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9923       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9924       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9925       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9926       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9927                                          TemplateId->NumArgs);
9928       translateTemplateArguments(TemplateArgsPtr,
9929                                  TemplateArgs);
9930 
9931       HasExplicitTemplateArgs = true;
9932 
9933       if (NewFD->isInvalidDecl()) {
9934         HasExplicitTemplateArgs = false;
9935       } else if (FunctionTemplate) {
9936         // Function template with explicit template arguments.
9937         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9938           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9939 
9940         HasExplicitTemplateArgs = false;
9941       } else {
9942         assert((isFunctionTemplateSpecialization ||
9943                 D.getDeclSpec().isFriendSpecified()) &&
9944                "should have a 'template<>' for this decl");
9945         // "friend void foo<>(int);" is an implicit specialization decl.
9946         isFunctionTemplateSpecialization = true;
9947       }
9948     } else if (isFriend && isFunctionTemplateSpecialization) {
9949       // This combination is only possible in a recovery case;  the user
9950       // wrote something like:
9951       //   template <> friend void foo(int);
9952       // which we're recovering from as if the user had written:
9953       //   friend void foo<>(int);
9954       // Go ahead and fake up a template id.
9955       HasExplicitTemplateArgs = true;
9956       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9957       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9958     }
9959 
9960     // We do not add HD attributes to specializations here because
9961     // they may have different constexpr-ness compared to their
9962     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9963     // may end up with different effective targets. Instead, a
9964     // specialization inherits its target attributes from its template
9965     // in the CheckFunctionTemplateSpecialization() call below.
9966     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9967       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9968 
9969     // If it's a friend (and only if it's a friend), it's possible
9970     // that either the specialized function type or the specialized
9971     // template is dependent, and therefore matching will fail.  In
9972     // this case, don't check the specialization yet.
9973     if (isFunctionTemplateSpecialization && isFriend &&
9974         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9975          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9976              TemplateArgs.arguments()))) {
9977       assert(HasExplicitTemplateArgs &&
9978              "friend function specialization without template args");
9979       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9980                                                        Previous))
9981         NewFD->setInvalidDecl();
9982     } else if (isFunctionTemplateSpecialization) {
9983       if (CurContext->isDependentContext() && CurContext->isRecord()
9984           && !isFriend) {
9985         isDependentClassScopeExplicitSpecialization = true;
9986       } else if (!NewFD->isInvalidDecl() &&
9987                  CheckFunctionTemplateSpecialization(
9988                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9989                      Previous))
9990         NewFD->setInvalidDecl();
9991 
9992       // C++ [dcl.stc]p1:
9993       //   A storage-class-specifier shall not be specified in an explicit
9994       //   specialization (14.7.3)
9995       FunctionTemplateSpecializationInfo *Info =
9996           NewFD->getTemplateSpecializationInfo();
9997       if (Info && SC != SC_None) {
9998         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9999           Diag(NewFD->getLocation(),
10000                diag::err_explicit_specialization_inconsistent_storage_class)
10001             << SC
10002             << FixItHint::CreateRemoval(
10003                                       D.getDeclSpec().getStorageClassSpecLoc());
10004 
10005         else
10006           Diag(NewFD->getLocation(),
10007                diag::ext_explicit_specialization_storage_class)
10008             << FixItHint::CreateRemoval(
10009                                       D.getDeclSpec().getStorageClassSpecLoc());
10010       }
10011     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10012       if (CheckMemberSpecialization(NewFD, Previous))
10013           NewFD->setInvalidDecl();
10014     }
10015 
10016     // Perform semantic checking on the function declaration.
10017     if (!isDependentClassScopeExplicitSpecialization) {
10018       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10019         CheckMain(NewFD, D.getDeclSpec());
10020 
10021       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10022         CheckMSVCRTEntryPoint(NewFD);
10023 
10024       if (!NewFD->isInvalidDecl())
10025         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10026                                                     isMemberSpecialization,
10027                                                     D.isFunctionDefinition()));
10028       else if (!Previous.empty())
10029         // Recover gracefully from an invalid redeclaration.
10030         D.setRedeclaration(true);
10031     }
10032 
10033     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10034             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10035            "previous declaration set still overloaded");
10036 
10037     NamedDecl *PrincipalDecl = (FunctionTemplate
10038                                 ? cast<NamedDecl>(FunctionTemplate)
10039                                 : NewFD);
10040 
10041     if (isFriend && NewFD->getPreviousDecl()) {
10042       AccessSpecifier Access = AS_public;
10043       if (!NewFD->isInvalidDecl())
10044         Access = NewFD->getPreviousDecl()->getAccess();
10045 
10046       NewFD->setAccess(Access);
10047       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10048     }
10049 
10050     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10051         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10052       PrincipalDecl->setNonMemberOperator();
10053 
10054     // If we have a function template, check the template parameter
10055     // list. This will check and merge default template arguments.
10056     if (FunctionTemplate) {
10057       FunctionTemplateDecl *PrevTemplate =
10058                                      FunctionTemplate->getPreviousDecl();
10059       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10060                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10061                                     : nullptr,
10062                             D.getDeclSpec().isFriendSpecified()
10063                               ? (D.isFunctionDefinition()
10064                                    ? TPC_FriendFunctionTemplateDefinition
10065                                    : TPC_FriendFunctionTemplate)
10066                               : (D.getCXXScopeSpec().isSet() &&
10067                                  DC && DC->isRecord() &&
10068                                  DC->isDependentContext())
10069                                   ? TPC_ClassTemplateMember
10070                                   : TPC_FunctionTemplate);
10071     }
10072 
10073     if (NewFD->isInvalidDecl()) {
10074       // Ignore all the rest of this.
10075     } else if (!D.isRedeclaration()) {
10076       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10077                                        AddToScope };
10078       // Fake up an access specifier if it's supposed to be a class member.
10079       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10080         NewFD->setAccess(AS_public);
10081 
10082       // Qualified decls generally require a previous declaration.
10083       if (D.getCXXScopeSpec().isSet()) {
10084         // ...with the major exception of templated-scope or
10085         // dependent-scope friend declarations.
10086 
10087         // TODO: we currently also suppress this check in dependent
10088         // contexts because (1) the parameter depth will be off when
10089         // matching friend templates and (2) we might actually be
10090         // selecting a friend based on a dependent factor.  But there
10091         // are situations where these conditions don't apply and we
10092         // can actually do this check immediately.
10093         //
10094         // Unless the scope is dependent, it's always an error if qualified
10095         // redeclaration lookup found nothing at all. Diagnose that now;
10096         // nothing will diagnose that error later.
10097         if (isFriend &&
10098             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10099              (!Previous.empty() && CurContext->isDependentContext()))) {
10100           // ignore these
10101         } else if (NewFD->isCPUDispatchMultiVersion() ||
10102                    NewFD->isCPUSpecificMultiVersion()) {
10103           // ignore this, we allow the redeclaration behavior here to create new
10104           // versions of the function.
10105         } else {
10106           // The user tried to provide an out-of-line definition for a
10107           // function that is a member of a class or namespace, but there
10108           // was no such member function declared (C++ [class.mfct]p2,
10109           // C++ [namespace.memdef]p2). For example:
10110           //
10111           // class X {
10112           //   void f() const;
10113           // };
10114           //
10115           // void X::f() { } // ill-formed
10116           //
10117           // Complain about this problem, and attempt to suggest close
10118           // matches (e.g., those that differ only in cv-qualifiers and
10119           // whether the parameter types are references).
10120 
10121           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10122                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10123             AddToScope = ExtraArgs.AddToScope;
10124             return Result;
10125           }
10126         }
10127 
10128         // Unqualified local friend declarations are required to resolve
10129         // to something.
10130       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10131         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10132                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10133           AddToScope = ExtraArgs.AddToScope;
10134           return Result;
10135         }
10136       }
10137     } else if (!D.isFunctionDefinition() &&
10138                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10139                !isFriend && !isFunctionTemplateSpecialization &&
10140                !isMemberSpecialization) {
10141       // An out-of-line member function declaration must also be a
10142       // definition (C++ [class.mfct]p2).
10143       // Note that this is not the case for explicit specializations of
10144       // function templates or member functions of class templates, per
10145       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10146       // extension for compatibility with old SWIG code which likes to
10147       // generate them.
10148       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10149         << D.getCXXScopeSpec().getRange();
10150     }
10151   }
10152 
10153   // If this is the first declaration of a library builtin function, add
10154   // attributes as appropriate.
10155   if (!D.isRedeclaration()) {
10156     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10157       if (unsigned BuiltinID = II->getBuiltinID()) {
10158         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10159         if (!InStdNamespace &&
10160             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10161           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10162             // Validate the type matches unless this builtin is specified as
10163             // matching regardless of its declared type.
10164             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10165               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10166             } else {
10167               ASTContext::GetBuiltinTypeError Error;
10168               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10169               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10170 
10171               if (!Error && !BuiltinType.isNull() &&
10172                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10173                       NewFD->getType(), BuiltinType))
10174                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10175             }
10176           }
10177         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10178                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10179           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10180         }
10181       }
10182     }
10183   }
10184 
10185   ProcessPragmaWeak(S, NewFD);
10186   checkAttributesAfterMerging(*this, *NewFD);
10187 
10188   AddKnownFunctionAttributes(NewFD);
10189 
10190   if (NewFD->hasAttr<OverloadableAttr>() &&
10191       !NewFD->getType()->getAs<FunctionProtoType>()) {
10192     Diag(NewFD->getLocation(),
10193          diag::err_attribute_overloadable_no_prototype)
10194       << NewFD;
10195 
10196     // Turn this into a variadic function with no parameters.
10197     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10198     FunctionProtoType::ExtProtoInfo EPI(
10199         Context.getDefaultCallingConvention(true, false));
10200     EPI.Variadic = true;
10201     EPI.ExtInfo = FT->getExtInfo();
10202 
10203     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10204     NewFD->setType(R);
10205   }
10206 
10207   // If there's a #pragma GCC visibility in scope, and this isn't a class
10208   // member, set the visibility of this function.
10209   if (!DC->isRecord() && NewFD->isExternallyVisible())
10210     AddPushedVisibilityAttribute(NewFD);
10211 
10212   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10213   // marking the function.
10214   AddCFAuditedAttribute(NewFD);
10215 
10216   // If this is a function definition, check if we have to apply optnone due to
10217   // a pragma.
10218   if(D.isFunctionDefinition())
10219     AddRangeBasedOptnone(NewFD);
10220 
10221   // If this is the first declaration of an extern C variable, update
10222   // the map of such variables.
10223   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10224       isIncompleteDeclExternC(*this, NewFD))
10225     RegisterLocallyScopedExternCDecl(NewFD, S);
10226 
10227   // Set this FunctionDecl's range up to the right paren.
10228   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10229 
10230   if (D.isRedeclaration() && !Previous.empty()) {
10231     NamedDecl *Prev = Previous.getRepresentativeDecl();
10232     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10233                                    isMemberSpecialization ||
10234                                        isFunctionTemplateSpecialization,
10235                                    D.isFunctionDefinition());
10236   }
10237 
10238   if (getLangOpts().CUDA) {
10239     IdentifierInfo *II = NewFD->getIdentifier();
10240     if (II && II->isStr(getCudaConfigureFuncName()) &&
10241         !NewFD->isInvalidDecl() &&
10242         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10243       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10244         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10245             << getCudaConfigureFuncName();
10246       Context.setcudaConfigureCallDecl(NewFD);
10247     }
10248 
10249     // Variadic functions, other than a *declaration* of printf, are not allowed
10250     // in device-side CUDA code, unless someone passed
10251     // -fcuda-allow-variadic-functions.
10252     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10253         (NewFD->hasAttr<CUDADeviceAttr>() ||
10254          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10255         !(II && II->isStr("printf") && NewFD->isExternC() &&
10256           !D.isFunctionDefinition())) {
10257       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10258     }
10259   }
10260 
10261   MarkUnusedFileScopedDecl(NewFD);
10262 
10263 
10264 
10265   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10266     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10267     if (SC == SC_Static) {
10268       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10269       D.setInvalidType();
10270     }
10271 
10272     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10273     if (!NewFD->getReturnType()->isVoidType()) {
10274       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10275       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10276           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10277                                 : FixItHint());
10278       D.setInvalidType();
10279     }
10280 
10281     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10282     for (auto Param : NewFD->parameters())
10283       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10284 
10285     if (getLangOpts().OpenCLCPlusPlus) {
10286       if (DC->isRecord()) {
10287         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10288         D.setInvalidType();
10289       }
10290       if (FunctionTemplate) {
10291         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10292         D.setInvalidType();
10293       }
10294     }
10295   }
10296 
10297   if (getLangOpts().CPlusPlus) {
10298     if (FunctionTemplate) {
10299       if (NewFD->isInvalidDecl())
10300         FunctionTemplate->setInvalidDecl();
10301       return FunctionTemplate;
10302     }
10303 
10304     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10305       CompleteMemberSpecialization(NewFD, Previous);
10306   }
10307 
10308   for (const ParmVarDecl *Param : NewFD->parameters()) {
10309     QualType PT = Param->getType();
10310 
10311     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10312     // types.
10313     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10314       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10315         QualType ElemTy = PipeTy->getElementType();
10316           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10317             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10318             D.setInvalidType();
10319           }
10320       }
10321     }
10322   }
10323 
10324   // Here we have an function template explicit specialization at class scope.
10325   // The actual specialization will be postponed to template instatiation
10326   // time via the ClassScopeFunctionSpecializationDecl node.
10327   if (isDependentClassScopeExplicitSpecialization) {
10328     ClassScopeFunctionSpecializationDecl *NewSpec =
10329                          ClassScopeFunctionSpecializationDecl::Create(
10330                                 Context, CurContext, NewFD->getLocation(),
10331                                 cast<CXXMethodDecl>(NewFD),
10332                                 HasExplicitTemplateArgs, TemplateArgs);
10333     CurContext->addDecl(NewSpec);
10334     AddToScope = false;
10335   }
10336 
10337   // Diagnose availability attributes. Availability cannot be used on functions
10338   // that are run during load/unload.
10339   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10340     if (NewFD->hasAttr<ConstructorAttr>()) {
10341       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10342           << 1;
10343       NewFD->dropAttr<AvailabilityAttr>();
10344     }
10345     if (NewFD->hasAttr<DestructorAttr>()) {
10346       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10347           << 2;
10348       NewFD->dropAttr<AvailabilityAttr>();
10349     }
10350   }
10351 
10352   // Diagnose no_builtin attribute on function declaration that are not a
10353   // definition.
10354   // FIXME: We should really be doing this in
10355   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10356   // the FunctionDecl and at this point of the code
10357   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10358   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10359   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10360     switch (D.getFunctionDefinitionKind()) {
10361     case FunctionDefinitionKind::Defaulted:
10362     case FunctionDefinitionKind::Deleted:
10363       Diag(NBA->getLocation(),
10364            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10365           << NBA->getSpelling();
10366       break;
10367     case FunctionDefinitionKind::Declaration:
10368       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10369           << NBA->getSpelling();
10370       break;
10371     case FunctionDefinitionKind::Definition:
10372       break;
10373     }
10374 
10375   return NewFD;
10376 }
10377 
10378 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10379 /// when __declspec(code_seg) "is applied to a class, all member functions of
10380 /// the class and nested classes -- this includes compiler-generated special
10381 /// member functions -- are put in the specified segment."
10382 /// The actual behavior is a little more complicated. The Microsoft compiler
10383 /// won't check outer classes if there is an active value from #pragma code_seg.
10384 /// The CodeSeg is always applied from the direct parent but only from outer
10385 /// classes when the #pragma code_seg stack is empty. See:
10386 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10387 /// available since MS has removed the page.
10388 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10389   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10390   if (!Method)
10391     return nullptr;
10392   const CXXRecordDecl *Parent = Method->getParent();
10393   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10394     Attr *NewAttr = SAttr->clone(S.getASTContext());
10395     NewAttr->setImplicit(true);
10396     return NewAttr;
10397   }
10398 
10399   // The Microsoft compiler won't check outer classes for the CodeSeg
10400   // when the #pragma code_seg stack is active.
10401   if (S.CodeSegStack.CurrentValue)
10402    return nullptr;
10403 
10404   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10405     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10406       Attr *NewAttr = SAttr->clone(S.getASTContext());
10407       NewAttr->setImplicit(true);
10408       return NewAttr;
10409     }
10410   }
10411   return nullptr;
10412 }
10413 
10414 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10415 /// containing class. Otherwise it will return implicit SectionAttr if the
10416 /// function is a definition and there is an active value on CodeSegStack
10417 /// (from the current #pragma code-seg value).
10418 ///
10419 /// \param FD Function being declared.
10420 /// \param IsDefinition Whether it is a definition or just a declarartion.
10421 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10422 ///          nullptr if no attribute should be added.
10423 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10424                                                        bool IsDefinition) {
10425   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10426     return A;
10427   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10428       CodeSegStack.CurrentValue)
10429     return SectionAttr::CreateImplicit(
10430         getASTContext(), CodeSegStack.CurrentValue->getString(),
10431         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10432         SectionAttr::Declspec_allocate);
10433   return nullptr;
10434 }
10435 
10436 /// Determines if we can perform a correct type check for \p D as a
10437 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10438 /// best-effort check.
10439 ///
10440 /// \param NewD The new declaration.
10441 /// \param OldD The old declaration.
10442 /// \param NewT The portion of the type of the new declaration to check.
10443 /// \param OldT The portion of the type of the old declaration to check.
10444 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10445                                           QualType NewT, QualType OldT) {
10446   if (!NewD->getLexicalDeclContext()->isDependentContext())
10447     return true;
10448 
10449   // For dependently-typed local extern declarations and friends, we can't
10450   // perform a correct type check in general until instantiation:
10451   //
10452   //   int f();
10453   //   template<typename T> void g() { T f(); }
10454   //
10455   // (valid if g() is only instantiated with T = int).
10456   if (NewT->isDependentType() &&
10457       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10458     return false;
10459 
10460   // Similarly, if the previous declaration was a dependent local extern
10461   // declaration, we don't really know its type yet.
10462   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10463     return false;
10464 
10465   return true;
10466 }
10467 
10468 /// Checks if the new declaration declared in dependent context must be
10469 /// put in the same redeclaration chain as the specified declaration.
10470 ///
10471 /// \param D Declaration that is checked.
10472 /// \param PrevDecl Previous declaration found with proper lookup method for the
10473 ///                 same declaration name.
10474 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10475 ///          belongs to.
10476 ///
10477 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10478   if (!D->getLexicalDeclContext()->isDependentContext())
10479     return true;
10480 
10481   // Don't chain dependent friend function definitions until instantiation, to
10482   // permit cases like
10483   //
10484   //   void func();
10485   //   template<typename T> class C1 { friend void func() {} };
10486   //   template<typename T> class C2 { friend void func() {} };
10487   //
10488   // ... which is valid if only one of C1 and C2 is ever instantiated.
10489   //
10490   // FIXME: This need only apply to function definitions. For now, we proxy
10491   // this by checking for a file-scope function. We do not want this to apply
10492   // to friend declarations nominating member functions, because that gets in
10493   // the way of access checks.
10494   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10495     return false;
10496 
10497   auto *VD = dyn_cast<ValueDecl>(D);
10498   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10499   return !VD || !PrevVD ||
10500          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10501                                         PrevVD->getType());
10502 }
10503 
10504 /// Check the target attribute of the function for MultiVersion
10505 /// validity.
10506 ///
10507 /// Returns true if there was an error, false otherwise.
10508 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10509   const auto *TA = FD->getAttr<TargetAttr>();
10510   assert(TA && "MultiVersion Candidate requires a target attribute");
10511   ParsedTargetAttr ParseInfo = TA->parse();
10512   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10513   enum ErrType { Feature = 0, Architecture = 1 };
10514 
10515   if (!ParseInfo.Architecture.empty() &&
10516       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10517     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10518         << Architecture << ParseInfo.Architecture;
10519     return true;
10520   }
10521 
10522   for (const auto &Feat : ParseInfo.Features) {
10523     auto BareFeat = StringRef{Feat}.substr(1);
10524     if (Feat[0] == '-') {
10525       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10526           << Feature << ("no-" + BareFeat).str();
10527       return true;
10528     }
10529 
10530     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10531         !TargetInfo.isValidFeatureName(BareFeat)) {
10532       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10533           << Feature << BareFeat;
10534       return true;
10535     }
10536   }
10537   return false;
10538 }
10539 
10540 // Provide a white-list of attributes that are allowed to be combined with
10541 // multiversion functions.
10542 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10543                                            MultiVersionKind MVKind) {
10544   // Note: this list/diagnosis must match the list in
10545   // checkMultiversionAttributesAllSame.
10546   switch (Kind) {
10547   default:
10548     return false;
10549   case attr::Used:
10550     return MVKind == MultiVersionKind::Target;
10551   case attr::NonNull:
10552   case attr::NoThrow:
10553     return true;
10554   }
10555 }
10556 
10557 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10558                                                  const FunctionDecl *FD,
10559                                                  const FunctionDecl *CausedFD,
10560                                                  MultiVersionKind MVKind) {
10561   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10562     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10563         << static_cast<unsigned>(MVKind) << A;
10564     if (CausedFD)
10565       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10566     return true;
10567   };
10568 
10569   for (const Attr *A : FD->attrs()) {
10570     switch (A->getKind()) {
10571     case attr::CPUDispatch:
10572     case attr::CPUSpecific:
10573       if (MVKind != MultiVersionKind::CPUDispatch &&
10574           MVKind != MultiVersionKind::CPUSpecific)
10575         return Diagnose(S, A);
10576       break;
10577     case attr::Target:
10578       if (MVKind != MultiVersionKind::Target)
10579         return Diagnose(S, A);
10580       break;
10581     case attr::TargetClones:
10582       if (MVKind != MultiVersionKind::TargetClones)
10583         return Diagnose(S, A);
10584       break;
10585     default:
10586       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10587         return Diagnose(S, A);
10588       break;
10589     }
10590   }
10591   return false;
10592 }
10593 
10594 bool Sema::areMultiversionVariantFunctionsCompatible(
10595     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10596     const PartialDiagnostic &NoProtoDiagID,
10597     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10598     const PartialDiagnosticAt &NoSupportDiagIDAt,
10599     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10600     bool ConstexprSupported, bool CLinkageMayDiffer) {
10601   enum DoesntSupport {
10602     FuncTemplates = 0,
10603     VirtFuncs = 1,
10604     DeducedReturn = 2,
10605     Constructors = 3,
10606     Destructors = 4,
10607     DeletedFuncs = 5,
10608     DefaultedFuncs = 6,
10609     ConstexprFuncs = 7,
10610     ConstevalFuncs = 8,
10611     Lambda = 9,
10612   };
10613   enum Different {
10614     CallingConv = 0,
10615     ReturnType = 1,
10616     ConstexprSpec = 2,
10617     InlineSpec = 3,
10618     Linkage = 4,
10619     LanguageLinkage = 5,
10620   };
10621 
10622   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10623       !OldFD->getType()->getAs<FunctionProtoType>()) {
10624     Diag(OldFD->getLocation(), NoProtoDiagID);
10625     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10626     return true;
10627   }
10628 
10629   if (NoProtoDiagID.getDiagID() != 0 &&
10630       !NewFD->getType()->getAs<FunctionProtoType>())
10631     return Diag(NewFD->getLocation(), NoProtoDiagID);
10632 
10633   if (!TemplatesSupported &&
10634       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10635     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10636            << FuncTemplates;
10637 
10638   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10639     if (NewCXXFD->isVirtual())
10640       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10641              << VirtFuncs;
10642 
10643     if (isa<CXXConstructorDecl>(NewCXXFD))
10644       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10645              << Constructors;
10646 
10647     if (isa<CXXDestructorDecl>(NewCXXFD))
10648       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10649              << Destructors;
10650   }
10651 
10652   if (NewFD->isDeleted())
10653     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10654            << DeletedFuncs;
10655 
10656   if (NewFD->isDefaulted())
10657     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10658            << DefaultedFuncs;
10659 
10660   if (!ConstexprSupported && NewFD->isConstexpr())
10661     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10662            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10663 
10664   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10665   const auto *NewType = cast<FunctionType>(NewQType);
10666   QualType NewReturnType = NewType->getReturnType();
10667 
10668   if (NewReturnType->isUndeducedType())
10669     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10670            << DeducedReturn;
10671 
10672   // Ensure the return type is identical.
10673   if (OldFD) {
10674     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10675     const auto *OldType = cast<FunctionType>(OldQType);
10676     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10677     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10678 
10679     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10680       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10681 
10682     QualType OldReturnType = OldType->getReturnType();
10683 
10684     if (OldReturnType != NewReturnType)
10685       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10686 
10687     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10688       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10689 
10690     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10691       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10692 
10693     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10694       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10695 
10696     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10697       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10698 
10699     if (CheckEquivalentExceptionSpec(
10700             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10701             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10702       return true;
10703   }
10704   return false;
10705 }
10706 
10707 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10708                                              const FunctionDecl *NewFD,
10709                                              bool CausesMV,
10710                                              MultiVersionKind MVKind) {
10711   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10712     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10713     if (OldFD)
10714       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10715     return true;
10716   }
10717 
10718   bool IsCPUSpecificCPUDispatchMVKind =
10719       MVKind == MultiVersionKind::CPUDispatch ||
10720       MVKind == MultiVersionKind::CPUSpecific;
10721 
10722   if (CausesMV && OldFD &&
10723       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10724     return true;
10725 
10726   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10727     return true;
10728 
10729   // Only allow transition to MultiVersion if it hasn't been used.
10730   if (OldFD && CausesMV && OldFD->isUsed(false))
10731     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10732 
10733   return S.areMultiversionVariantFunctionsCompatible(
10734       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10735       PartialDiagnosticAt(NewFD->getLocation(),
10736                           S.PDiag(diag::note_multiversioning_caused_here)),
10737       PartialDiagnosticAt(NewFD->getLocation(),
10738                           S.PDiag(diag::err_multiversion_doesnt_support)
10739                               << static_cast<unsigned>(MVKind)),
10740       PartialDiagnosticAt(NewFD->getLocation(),
10741                           S.PDiag(diag::err_multiversion_diff)),
10742       /*TemplatesSupported=*/false,
10743       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10744       /*CLinkageMayDiffer=*/false);
10745 }
10746 
10747 /// Check the validity of a multiversion function declaration that is the
10748 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10749 ///
10750 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10751 ///
10752 /// Returns true if there was an error, false otherwise.
10753 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10754                                            MultiVersionKind MVKind,
10755                                            const TargetAttr *TA) {
10756   assert(MVKind != MultiVersionKind::None &&
10757          "Function lacks multiversion attribute");
10758 
10759   // Target only causes MV if it is default, otherwise this is a normal
10760   // function.
10761   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10762     return false;
10763 
10764   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10765     FD->setInvalidDecl();
10766     return true;
10767   }
10768 
10769   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10770     FD->setInvalidDecl();
10771     return true;
10772   }
10773 
10774   FD->setIsMultiVersion();
10775   return false;
10776 }
10777 
10778 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10779   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10780     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10781       return true;
10782   }
10783 
10784   return false;
10785 }
10786 
10787 static bool CheckTargetCausesMultiVersioning(
10788     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10789     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10790   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10791   ParsedTargetAttr NewParsed = NewTA->parse();
10792   // Sort order doesn't matter, it just needs to be consistent.
10793   llvm::sort(NewParsed.Features);
10794 
10795   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10796   // to change, this is a simple redeclaration.
10797   if (!NewTA->isDefaultVersion() &&
10798       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10799     return false;
10800 
10801   // Otherwise, this decl causes MultiVersioning.
10802   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10803                                        MultiVersionKind::Target)) {
10804     NewFD->setInvalidDecl();
10805     return true;
10806   }
10807 
10808   if (CheckMultiVersionValue(S, NewFD)) {
10809     NewFD->setInvalidDecl();
10810     return true;
10811   }
10812 
10813   // If this is 'default', permit the forward declaration.
10814   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10815     Redeclaration = true;
10816     OldDecl = OldFD;
10817     OldFD->setIsMultiVersion();
10818     NewFD->setIsMultiVersion();
10819     return false;
10820   }
10821 
10822   if (CheckMultiVersionValue(S, OldFD)) {
10823     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10824     NewFD->setInvalidDecl();
10825     return true;
10826   }
10827 
10828   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10829 
10830   if (OldParsed == NewParsed) {
10831     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10832     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10833     NewFD->setInvalidDecl();
10834     return true;
10835   }
10836 
10837   for (const auto *FD : OldFD->redecls()) {
10838     const auto *CurTA = FD->getAttr<TargetAttr>();
10839     // We allow forward declarations before ANY multiversioning attributes, but
10840     // nothing after the fact.
10841     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10842         (!CurTA || CurTA->isInherited())) {
10843       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10844           << 0;
10845       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10846       NewFD->setInvalidDecl();
10847       return true;
10848     }
10849   }
10850 
10851   OldFD->setIsMultiVersion();
10852   NewFD->setIsMultiVersion();
10853   Redeclaration = false;
10854   OldDecl = nullptr;
10855   Previous.clear();
10856   return false;
10857 }
10858 
10859 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10860                                         MultiVersionKind New) {
10861   if (Old == New || Old == MultiVersionKind::None ||
10862       New == MultiVersionKind::None)
10863     return true;
10864 
10865   return (Old == MultiVersionKind::CPUDispatch &&
10866           New == MultiVersionKind::CPUSpecific) ||
10867          (Old == MultiVersionKind::CPUSpecific &&
10868           New == MultiVersionKind::CPUDispatch);
10869 }
10870 
10871 /// Check the validity of a new function declaration being added to an existing
10872 /// multiversioned declaration collection.
10873 static bool CheckMultiVersionAdditionalDecl(
10874     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10875     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10876     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10877     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10878     LookupResult &Previous) {
10879 
10880   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10881   // Disallow mixing of multiversioning types.
10882   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10883     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10884     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10885     NewFD->setInvalidDecl();
10886     return true;
10887   }
10888 
10889   ParsedTargetAttr NewParsed;
10890   if (NewTA) {
10891     NewParsed = NewTA->parse();
10892     llvm::sort(NewParsed.Features);
10893   }
10894 
10895   bool UseMemberUsingDeclRules =
10896       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10897 
10898   bool MayNeedOverloadableChecks =
10899       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10900 
10901   // Next, check ALL non-overloads to see if this is a redeclaration of a
10902   // previous member of the MultiVersion set.
10903   for (NamedDecl *ND : Previous) {
10904     FunctionDecl *CurFD = ND->getAsFunction();
10905     if (!CurFD)
10906       continue;
10907     if (MayNeedOverloadableChecks &&
10908         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10909       continue;
10910 
10911     switch (NewMVKind) {
10912     case MultiVersionKind::None:
10913       assert(OldMVKind == MultiVersionKind::TargetClones &&
10914              "Only target_clones can be omitted in subsequent declarations");
10915       break;
10916     case MultiVersionKind::Target: {
10917       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10918       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10919         NewFD->setIsMultiVersion();
10920         Redeclaration = true;
10921         OldDecl = ND;
10922         return false;
10923       }
10924 
10925       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10926       if (CurParsed == NewParsed) {
10927         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10928         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10929         NewFD->setInvalidDecl();
10930         return true;
10931       }
10932       break;
10933     }
10934     case MultiVersionKind::TargetClones: {
10935       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10936       Redeclaration = true;
10937       OldDecl = CurFD;
10938       NewFD->setIsMultiVersion();
10939 
10940       if (CurClones && NewClones &&
10941           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10942            !std::equal(CurClones->featuresStrs_begin(),
10943                        CurClones->featuresStrs_end(),
10944                        NewClones->featuresStrs_begin()))) {
10945         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10946         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10947         NewFD->setInvalidDecl();
10948         return true;
10949       }
10950 
10951       return false;
10952     }
10953     case MultiVersionKind::CPUSpecific:
10954     case MultiVersionKind::CPUDispatch: {
10955       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10956       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10957       // Handle CPUDispatch/CPUSpecific versions.
10958       // Only 1 CPUDispatch function is allowed, this will make it go through
10959       // the redeclaration errors.
10960       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10961           CurFD->hasAttr<CPUDispatchAttr>()) {
10962         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10963             std::equal(
10964                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10965                 NewCPUDisp->cpus_begin(),
10966                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10967                   return Cur->getName() == New->getName();
10968                 })) {
10969           NewFD->setIsMultiVersion();
10970           Redeclaration = true;
10971           OldDecl = ND;
10972           return false;
10973         }
10974 
10975         // If the declarations don't match, this is an error condition.
10976         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10977         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10978         NewFD->setInvalidDecl();
10979         return true;
10980       }
10981       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10982         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10983             std::equal(
10984                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10985                 NewCPUSpec->cpus_begin(),
10986                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10987                   return Cur->getName() == New->getName();
10988                 })) {
10989           NewFD->setIsMultiVersion();
10990           Redeclaration = true;
10991           OldDecl = ND;
10992           return false;
10993         }
10994 
10995         // Only 1 version of CPUSpecific is allowed for each CPU.
10996         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10997           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10998             if (CurII == NewII) {
10999               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11000                   << NewII;
11001               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11002               NewFD->setInvalidDecl();
11003               return true;
11004             }
11005           }
11006         }
11007       }
11008       break;
11009     }
11010     }
11011   }
11012 
11013   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11014   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11015   // handled in the attribute adding step.
11016   if (NewMVKind == MultiVersionKind::Target &&
11017       CheckMultiVersionValue(S, NewFD)) {
11018     NewFD->setInvalidDecl();
11019     return true;
11020   }
11021 
11022   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11023                                        !OldFD->isMultiVersion(), NewMVKind)) {
11024     NewFD->setInvalidDecl();
11025     return true;
11026   }
11027 
11028   // Permit forward declarations in the case where these two are compatible.
11029   if (!OldFD->isMultiVersion()) {
11030     OldFD->setIsMultiVersion();
11031     NewFD->setIsMultiVersion();
11032     Redeclaration = true;
11033     OldDecl = OldFD;
11034     return false;
11035   }
11036 
11037   NewFD->setIsMultiVersion();
11038   Redeclaration = false;
11039   OldDecl = nullptr;
11040   Previous.clear();
11041   return false;
11042 }
11043 
11044 /// Check the validity of a mulitversion function declaration.
11045 /// Also sets the multiversion'ness' of the function itself.
11046 ///
11047 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11048 ///
11049 /// Returns true if there was an error, false otherwise.
11050 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11051                                       bool &Redeclaration, NamedDecl *&OldDecl,
11052                                       LookupResult &Previous) {
11053   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11054   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11055   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11056   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11057   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11058 
11059   // Main isn't allowed to become a multiversion function, however it IS
11060   // permitted to have 'main' be marked with the 'target' optimization hint.
11061   if (NewFD->isMain()) {
11062     if (MVKind != MultiVersionKind::None &&
11063         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11064       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11065       NewFD->setInvalidDecl();
11066       return true;
11067     }
11068     return false;
11069   }
11070 
11071   if (!OldDecl || !OldDecl->getAsFunction() ||
11072       OldDecl->getDeclContext()->getRedeclContext() !=
11073           NewFD->getDeclContext()->getRedeclContext()) {
11074     // If there's no previous declaration, AND this isn't attempting to cause
11075     // multiversioning, this isn't an error condition.
11076     if (MVKind == MultiVersionKind::None)
11077       return false;
11078     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11079   }
11080 
11081   FunctionDecl *OldFD = OldDecl->getAsFunction();
11082 
11083   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11084     return false;
11085 
11086   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11087   // for target_clones.
11088   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11089       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11090     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11091         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11092     NewFD->setInvalidDecl();
11093     return true;
11094   }
11095 
11096   if (!OldFD->isMultiVersion()) {
11097     switch (MVKind) {
11098     case MultiVersionKind::Target:
11099       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11100                                               Redeclaration, OldDecl, Previous);
11101     case MultiVersionKind::TargetClones:
11102       if (OldFD->isUsed(false)) {
11103         NewFD->setInvalidDecl();
11104         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11105       }
11106       OldFD->setIsMultiVersion();
11107       break;
11108     case MultiVersionKind::CPUDispatch:
11109     case MultiVersionKind::CPUSpecific:
11110     case MultiVersionKind::None:
11111       break;
11112     }
11113   }
11114 
11115   // At this point, we have a multiversion function decl (in OldFD) AND an
11116   // appropriate attribute in the current function decl.  Resolve that these are
11117   // still compatible with previous declarations.
11118   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11119                                          NewCPUDisp, NewCPUSpec, NewClones,
11120                                          Redeclaration, OldDecl, Previous);
11121 }
11122 
11123 /// Perform semantic checking of a new function declaration.
11124 ///
11125 /// Performs semantic analysis of the new function declaration
11126 /// NewFD. This routine performs all semantic checking that does not
11127 /// require the actual declarator involved in the declaration, and is
11128 /// used both for the declaration of functions as they are parsed
11129 /// (called via ActOnDeclarator) and for the declaration of functions
11130 /// that have been instantiated via C++ template instantiation (called
11131 /// via InstantiateDecl).
11132 ///
11133 /// \param IsMemberSpecialization whether this new function declaration is
11134 /// a member specialization (that replaces any definition provided by the
11135 /// previous declaration).
11136 ///
11137 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11138 ///
11139 /// \returns true if the function declaration is a redeclaration.
11140 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11141                                     LookupResult &Previous,
11142                                     bool IsMemberSpecialization,
11143                                     bool DeclIsDefn) {
11144   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11145          "Variably modified return types are not handled here");
11146 
11147   // Determine whether the type of this function should be merged with
11148   // a previous visible declaration. This never happens for functions in C++,
11149   // and always happens in C if the previous declaration was visible.
11150   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11151                                !Previous.isShadowed();
11152 
11153   bool Redeclaration = false;
11154   NamedDecl *OldDecl = nullptr;
11155   bool MayNeedOverloadableChecks = false;
11156 
11157   // Merge or overload the declaration with an existing declaration of
11158   // the same name, if appropriate.
11159   if (!Previous.empty()) {
11160     // Determine whether NewFD is an overload of PrevDecl or
11161     // a declaration that requires merging. If it's an overload,
11162     // there's no more work to do here; we'll just add the new
11163     // function to the scope.
11164     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11165       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11166       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11167         Redeclaration = true;
11168         OldDecl = Candidate;
11169       }
11170     } else {
11171       MayNeedOverloadableChecks = true;
11172       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11173                             /*NewIsUsingDecl*/ false)) {
11174       case Ovl_Match:
11175         Redeclaration = true;
11176         break;
11177 
11178       case Ovl_NonFunction:
11179         Redeclaration = true;
11180         break;
11181 
11182       case Ovl_Overload:
11183         Redeclaration = false;
11184         break;
11185       }
11186     }
11187   }
11188 
11189   // Check for a previous extern "C" declaration with this name.
11190   if (!Redeclaration &&
11191       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11192     if (!Previous.empty()) {
11193       // This is an extern "C" declaration with the same name as a previous
11194       // declaration, and thus redeclares that entity...
11195       Redeclaration = true;
11196       OldDecl = Previous.getFoundDecl();
11197       MergeTypeWithPrevious = false;
11198 
11199       // ... except in the presence of __attribute__((overloadable)).
11200       if (OldDecl->hasAttr<OverloadableAttr>() ||
11201           NewFD->hasAttr<OverloadableAttr>()) {
11202         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11203           MayNeedOverloadableChecks = true;
11204           Redeclaration = false;
11205           OldDecl = nullptr;
11206         }
11207       }
11208     }
11209   }
11210 
11211   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11212     return Redeclaration;
11213 
11214   // PPC MMA non-pointer types are not allowed as function return types.
11215   if (Context.getTargetInfo().getTriple().isPPC64() &&
11216       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11217     NewFD->setInvalidDecl();
11218   }
11219 
11220   // C++11 [dcl.constexpr]p8:
11221   //   A constexpr specifier for a non-static member function that is not
11222   //   a constructor declares that member function to be const.
11223   //
11224   // This needs to be delayed until we know whether this is an out-of-line
11225   // definition of a static member function.
11226   //
11227   // This rule is not present in C++1y, so we produce a backwards
11228   // compatibility warning whenever it happens in C++11.
11229   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11230   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11231       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11232       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11233     CXXMethodDecl *OldMD = nullptr;
11234     if (OldDecl)
11235       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11236     if (!OldMD || !OldMD->isStatic()) {
11237       const FunctionProtoType *FPT =
11238         MD->getType()->castAs<FunctionProtoType>();
11239       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11240       EPI.TypeQuals.addConst();
11241       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11242                                           FPT->getParamTypes(), EPI));
11243 
11244       // Warn that we did this, if we're not performing template instantiation.
11245       // In that case, we'll have warned already when the template was defined.
11246       if (!inTemplateInstantiation()) {
11247         SourceLocation AddConstLoc;
11248         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11249                 .IgnoreParens().getAs<FunctionTypeLoc>())
11250           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11251 
11252         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11253           << FixItHint::CreateInsertion(AddConstLoc, " const");
11254       }
11255     }
11256   }
11257 
11258   if (Redeclaration) {
11259     // NewFD and OldDecl represent declarations that need to be
11260     // merged.
11261     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11262                           DeclIsDefn)) {
11263       NewFD->setInvalidDecl();
11264       return Redeclaration;
11265     }
11266 
11267     Previous.clear();
11268     Previous.addDecl(OldDecl);
11269 
11270     if (FunctionTemplateDecl *OldTemplateDecl =
11271             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11272       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11273       FunctionTemplateDecl *NewTemplateDecl
11274         = NewFD->getDescribedFunctionTemplate();
11275       assert(NewTemplateDecl && "Template/non-template mismatch");
11276 
11277       // The call to MergeFunctionDecl above may have created some state in
11278       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11279       // can add it as a redeclaration.
11280       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11281 
11282       NewFD->setPreviousDeclaration(OldFD);
11283       if (NewFD->isCXXClassMember()) {
11284         NewFD->setAccess(OldTemplateDecl->getAccess());
11285         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11286       }
11287 
11288       // If this is an explicit specialization of a member that is a function
11289       // template, mark it as a member specialization.
11290       if (IsMemberSpecialization &&
11291           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11292         NewTemplateDecl->setMemberSpecialization();
11293         assert(OldTemplateDecl->isMemberSpecialization());
11294         // Explicit specializations of a member template do not inherit deleted
11295         // status from the parent member template that they are specializing.
11296         if (OldFD->isDeleted()) {
11297           // FIXME: This assert will not hold in the presence of modules.
11298           assert(OldFD->getCanonicalDecl() == OldFD);
11299           // FIXME: We need an update record for this AST mutation.
11300           OldFD->setDeletedAsWritten(false);
11301         }
11302       }
11303 
11304     } else {
11305       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11306         auto *OldFD = cast<FunctionDecl>(OldDecl);
11307         // This needs to happen first so that 'inline' propagates.
11308         NewFD->setPreviousDeclaration(OldFD);
11309         if (NewFD->isCXXClassMember())
11310           NewFD->setAccess(OldFD->getAccess());
11311       }
11312     }
11313   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11314              !NewFD->getAttr<OverloadableAttr>()) {
11315     assert((Previous.empty() ||
11316             llvm::any_of(Previous,
11317                          [](const NamedDecl *ND) {
11318                            return ND->hasAttr<OverloadableAttr>();
11319                          })) &&
11320            "Non-redecls shouldn't happen without overloadable present");
11321 
11322     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11323       const auto *FD = dyn_cast<FunctionDecl>(ND);
11324       return FD && !FD->hasAttr<OverloadableAttr>();
11325     });
11326 
11327     if (OtherUnmarkedIter != Previous.end()) {
11328       Diag(NewFD->getLocation(),
11329            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11330       Diag((*OtherUnmarkedIter)->getLocation(),
11331            diag::note_attribute_overloadable_prev_overload)
11332           << false;
11333 
11334       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11335     }
11336   }
11337 
11338   if (LangOpts.OpenMP)
11339     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11340 
11341   // Semantic checking for this function declaration (in isolation).
11342 
11343   if (getLangOpts().CPlusPlus) {
11344     // C++-specific checks.
11345     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11346       CheckConstructor(Constructor);
11347     } else if (CXXDestructorDecl *Destructor =
11348                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11349       CXXRecordDecl *Record = Destructor->getParent();
11350       QualType ClassType = Context.getTypeDeclType(Record);
11351 
11352       // FIXME: Shouldn't we be able to perform this check even when the class
11353       // type is dependent? Both gcc and edg can handle that.
11354       if (!ClassType->isDependentType()) {
11355         DeclarationName Name
11356           = Context.DeclarationNames.getCXXDestructorName(
11357                                         Context.getCanonicalType(ClassType));
11358         if (NewFD->getDeclName() != Name) {
11359           Diag(NewFD->getLocation(), diag::err_destructor_name);
11360           NewFD->setInvalidDecl();
11361           return Redeclaration;
11362         }
11363       }
11364     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11365       if (auto *TD = Guide->getDescribedFunctionTemplate())
11366         CheckDeductionGuideTemplate(TD);
11367 
11368       // A deduction guide is not on the list of entities that can be
11369       // explicitly specialized.
11370       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11371         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11372             << /*explicit specialization*/ 1;
11373     }
11374 
11375     // Find any virtual functions that this function overrides.
11376     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11377       if (!Method->isFunctionTemplateSpecialization() &&
11378           !Method->getDescribedFunctionTemplate() &&
11379           Method->isCanonicalDecl()) {
11380         AddOverriddenMethods(Method->getParent(), Method);
11381       }
11382       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11383         // C++2a [class.virtual]p6
11384         // A virtual method shall not have a requires-clause.
11385         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11386              diag::err_constrained_virtual_method);
11387 
11388       if (Method->isStatic())
11389         checkThisInStaticMemberFunctionType(Method);
11390     }
11391 
11392     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11393       ActOnConversionDeclarator(Conversion);
11394 
11395     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11396     if (NewFD->isOverloadedOperator() &&
11397         CheckOverloadedOperatorDeclaration(NewFD)) {
11398       NewFD->setInvalidDecl();
11399       return Redeclaration;
11400     }
11401 
11402     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11403     if (NewFD->getLiteralIdentifier() &&
11404         CheckLiteralOperatorDeclaration(NewFD)) {
11405       NewFD->setInvalidDecl();
11406       return Redeclaration;
11407     }
11408 
11409     // In C++, check default arguments now that we have merged decls. Unless
11410     // the lexical context is the class, because in this case this is done
11411     // during delayed parsing anyway.
11412     if (!CurContext->isRecord())
11413       CheckCXXDefaultArguments(NewFD);
11414 
11415     // If this function is declared as being extern "C", then check to see if
11416     // the function returns a UDT (class, struct, or union type) that is not C
11417     // compatible, and if it does, warn the user.
11418     // But, issue any diagnostic on the first declaration only.
11419     if (Previous.empty() && NewFD->isExternC()) {
11420       QualType R = NewFD->getReturnType();
11421       if (R->isIncompleteType() && !R->isVoidType())
11422         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11423             << NewFD << R;
11424       else if (!R.isPODType(Context) && !R->isVoidType() &&
11425                !R->isObjCObjectPointerType())
11426         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11427     }
11428 
11429     // C++1z [dcl.fct]p6:
11430     //   [...] whether the function has a non-throwing exception-specification
11431     //   [is] part of the function type
11432     //
11433     // This results in an ABI break between C++14 and C++17 for functions whose
11434     // declared type includes an exception-specification in a parameter or
11435     // return type. (Exception specifications on the function itself are OK in
11436     // most cases, and exception specifications are not permitted in most other
11437     // contexts where they could make it into a mangling.)
11438     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11439       auto HasNoexcept = [&](QualType T) -> bool {
11440         // Strip off declarator chunks that could be between us and a function
11441         // type. We don't need to look far, exception specifications are very
11442         // restricted prior to C++17.
11443         if (auto *RT = T->getAs<ReferenceType>())
11444           T = RT->getPointeeType();
11445         else if (T->isAnyPointerType())
11446           T = T->getPointeeType();
11447         else if (auto *MPT = T->getAs<MemberPointerType>())
11448           T = MPT->getPointeeType();
11449         if (auto *FPT = T->getAs<FunctionProtoType>())
11450           if (FPT->isNothrow())
11451             return true;
11452         return false;
11453       };
11454 
11455       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11456       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11457       for (QualType T : FPT->param_types())
11458         AnyNoexcept |= HasNoexcept(T);
11459       if (AnyNoexcept)
11460         Diag(NewFD->getLocation(),
11461              diag::warn_cxx17_compat_exception_spec_in_signature)
11462             << NewFD;
11463     }
11464 
11465     if (!Redeclaration && LangOpts.CUDA)
11466       checkCUDATargetOverload(NewFD, Previous);
11467   }
11468   return Redeclaration;
11469 }
11470 
11471 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11472   // C++11 [basic.start.main]p3:
11473   //   A program that [...] declares main to be inline, static or
11474   //   constexpr is ill-formed.
11475   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11476   //   appear in a declaration of main.
11477   // static main is not an error under C99, but we should warn about it.
11478   // We accept _Noreturn main as an extension.
11479   if (FD->getStorageClass() == SC_Static)
11480     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11481          ? diag::err_static_main : diag::warn_static_main)
11482       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11483   if (FD->isInlineSpecified())
11484     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11485       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11486   if (DS.isNoreturnSpecified()) {
11487     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11488     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11489     Diag(NoreturnLoc, diag::ext_noreturn_main);
11490     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11491       << FixItHint::CreateRemoval(NoreturnRange);
11492   }
11493   if (FD->isConstexpr()) {
11494     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11495         << FD->isConsteval()
11496         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11497     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11498   }
11499 
11500   if (getLangOpts().OpenCL) {
11501     Diag(FD->getLocation(), diag::err_opencl_no_main)
11502         << FD->hasAttr<OpenCLKernelAttr>();
11503     FD->setInvalidDecl();
11504     return;
11505   }
11506 
11507   // Functions named main in hlsl are default entries, but don't have specific
11508   // signatures they are required to conform to.
11509   if (getLangOpts().HLSL)
11510     return;
11511 
11512   QualType T = FD->getType();
11513   assert(T->isFunctionType() && "function decl is not of function type");
11514   const FunctionType* FT = T->castAs<FunctionType>();
11515 
11516   // Set default calling convention for main()
11517   if (FT->getCallConv() != CC_C) {
11518     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11519     FD->setType(QualType(FT, 0));
11520     T = Context.getCanonicalType(FD->getType());
11521   }
11522 
11523   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11524     // In C with GNU extensions we allow main() to have non-integer return
11525     // type, but we should warn about the extension, and we disable the
11526     // implicit-return-zero rule.
11527 
11528     // GCC in C mode accepts qualified 'int'.
11529     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11530       FD->setHasImplicitReturnZero(true);
11531     else {
11532       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11533       SourceRange RTRange = FD->getReturnTypeSourceRange();
11534       if (RTRange.isValid())
11535         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11536             << FixItHint::CreateReplacement(RTRange, "int");
11537     }
11538   } else {
11539     // In C and C++, main magically returns 0 if you fall off the end;
11540     // set the flag which tells us that.
11541     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11542 
11543     // All the standards say that main() should return 'int'.
11544     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11545       FD->setHasImplicitReturnZero(true);
11546     else {
11547       // Otherwise, this is just a flat-out error.
11548       SourceRange RTRange = FD->getReturnTypeSourceRange();
11549       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11550           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11551                                 : FixItHint());
11552       FD->setInvalidDecl(true);
11553     }
11554   }
11555 
11556   // Treat protoless main() as nullary.
11557   if (isa<FunctionNoProtoType>(FT)) return;
11558 
11559   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11560   unsigned nparams = FTP->getNumParams();
11561   assert(FD->getNumParams() == nparams);
11562 
11563   bool HasExtraParameters = (nparams > 3);
11564 
11565   if (FTP->isVariadic()) {
11566     Diag(FD->getLocation(), diag::ext_variadic_main);
11567     // FIXME: if we had information about the location of the ellipsis, we
11568     // could add a FixIt hint to remove it as a parameter.
11569   }
11570 
11571   // Darwin passes an undocumented fourth argument of type char**.  If
11572   // other platforms start sprouting these, the logic below will start
11573   // getting shifty.
11574   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11575     HasExtraParameters = false;
11576 
11577   if (HasExtraParameters) {
11578     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11579     FD->setInvalidDecl(true);
11580     nparams = 3;
11581   }
11582 
11583   // FIXME: a lot of the following diagnostics would be improved
11584   // if we had some location information about types.
11585 
11586   QualType CharPP =
11587     Context.getPointerType(Context.getPointerType(Context.CharTy));
11588   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11589 
11590   for (unsigned i = 0; i < nparams; ++i) {
11591     QualType AT = FTP->getParamType(i);
11592 
11593     bool mismatch = true;
11594 
11595     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11596       mismatch = false;
11597     else if (Expected[i] == CharPP) {
11598       // As an extension, the following forms are okay:
11599       //   char const **
11600       //   char const * const *
11601       //   char * const *
11602 
11603       QualifierCollector qs;
11604       const PointerType* PT;
11605       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11606           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11607           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11608                               Context.CharTy)) {
11609         qs.removeConst();
11610         mismatch = !qs.empty();
11611       }
11612     }
11613 
11614     if (mismatch) {
11615       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11616       // TODO: suggest replacing given type with expected type
11617       FD->setInvalidDecl(true);
11618     }
11619   }
11620 
11621   if (nparams == 1 && !FD->isInvalidDecl()) {
11622     Diag(FD->getLocation(), diag::warn_main_one_arg);
11623   }
11624 
11625   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11626     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11627     FD->setInvalidDecl();
11628   }
11629 }
11630 
11631 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11632 
11633   // Default calling convention for main and wmain is __cdecl
11634   if (FD->getName() == "main" || FD->getName() == "wmain")
11635     return false;
11636 
11637   // Default calling convention for MinGW is __cdecl
11638   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11639   if (T.isWindowsGNUEnvironment())
11640     return false;
11641 
11642   // Default calling convention for WinMain, wWinMain and DllMain
11643   // is __stdcall on 32 bit Windows
11644   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11645     return true;
11646 
11647   return false;
11648 }
11649 
11650 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11651   QualType T = FD->getType();
11652   assert(T->isFunctionType() && "function decl is not of function type");
11653   const FunctionType *FT = T->castAs<FunctionType>();
11654 
11655   // Set an implicit return of 'zero' if the function can return some integral,
11656   // enumeration, pointer or nullptr type.
11657   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11658       FT->getReturnType()->isAnyPointerType() ||
11659       FT->getReturnType()->isNullPtrType())
11660     // DllMain is exempt because a return value of zero means it failed.
11661     if (FD->getName() != "DllMain")
11662       FD->setHasImplicitReturnZero(true);
11663 
11664   // Explicity specified calling conventions are applied to MSVC entry points
11665   if (!hasExplicitCallingConv(T)) {
11666     if (isDefaultStdCall(FD, *this)) {
11667       if (FT->getCallConv() != CC_X86StdCall) {
11668         FT = Context.adjustFunctionType(
11669             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11670         FD->setType(QualType(FT, 0));
11671       }
11672     } else if (FT->getCallConv() != CC_C) {
11673       FT = Context.adjustFunctionType(FT,
11674                                       FT->getExtInfo().withCallingConv(CC_C));
11675       FD->setType(QualType(FT, 0));
11676     }
11677   }
11678 
11679   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11680     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11681     FD->setInvalidDecl();
11682   }
11683 }
11684 
11685 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11686   // FIXME: Need strict checking.  In C89, we need to check for
11687   // any assignment, increment, decrement, function-calls, or
11688   // commas outside of a sizeof.  In C99, it's the same list,
11689   // except that the aforementioned are allowed in unevaluated
11690   // expressions.  Everything else falls under the
11691   // "may accept other forms of constant expressions" exception.
11692   //
11693   // Regular C++ code will not end up here (exceptions: language extensions,
11694   // OpenCL C++ etc), so the constant expression rules there don't matter.
11695   if (Init->isValueDependent()) {
11696     assert(Init->containsErrors() &&
11697            "Dependent code should only occur in error-recovery path.");
11698     return true;
11699   }
11700   const Expr *Culprit;
11701   if (Init->isConstantInitializer(Context, false, &Culprit))
11702     return false;
11703   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11704     << Culprit->getSourceRange();
11705   return true;
11706 }
11707 
11708 namespace {
11709   // Visits an initialization expression to see if OrigDecl is evaluated in
11710   // its own initialization and throws a warning if it does.
11711   class SelfReferenceChecker
11712       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11713     Sema &S;
11714     Decl *OrigDecl;
11715     bool isRecordType;
11716     bool isPODType;
11717     bool isReferenceType;
11718 
11719     bool isInitList;
11720     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11721 
11722   public:
11723     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11724 
11725     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11726                                                     S(S), OrigDecl(OrigDecl) {
11727       isPODType = false;
11728       isRecordType = false;
11729       isReferenceType = false;
11730       isInitList = false;
11731       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11732         isPODType = VD->getType().isPODType(S.Context);
11733         isRecordType = VD->getType()->isRecordType();
11734         isReferenceType = VD->getType()->isReferenceType();
11735       }
11736     }
11737 
11738     // For most expressions, just call the visitor.  For initializer lists,
11739     // track the index of the field being initialized since fields are
11740     // initialized in order allowing use of previously initialized fields.
11741     void CheckExpr(Expr *E) {
11742       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11743       if (!InitList) {
11744         Visit(E);
11745         return;
11746       }
11747 
11748       // Track and increment the index here.
11749       isInitList = true;
11750       InitFieldIndex.push_back(0);
11751       for (auto Child : InitList->children()) {
11752         CheckExpr(cast<Expr>(Child));
11753         ++InitFieldIndex.back();
11754       }
11755       InitFieldIndex.pop_back();
11756     }
11757 
11758     // Returns true if MemberExpr is checked and no further checking is needed.
11759     // Returns false if additional checking is required.
11760     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11761       llvm::SmallVector<FieldDecl*, 4> Fields;
11762       Expr *Base = E;
11763       bool ReferenceField = false;
11764 
11765       // Get the field members used.
11766       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11767         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11768         if (!FD)
11769           return false;
11770         Fields.push_back(FD);
11771         if (FD->getType()->isReferenceType())
11772           ReferenceField = true;
11773         Base = ME->getBase()->IgnoreParenImpCasts();
11774       }
11775 
11776       // Keep checking only if the base Decl is the same.
11777       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11778       if (!DRE || DRE->getDecl() != OrigDecl)
11779         return false;
11780 
11781       // A reference field can be bound to an unininitialized field.
11782       if (CheckReference && !ReferenceField)
11783         return true;
11784 
11785       // Convert FieldDecls to their index number.
11786       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11787       for (const FieldDecl *I : llvm::reverse(Fields))
11788         UsedFieldIndex.push_back(I->getFieldIndex());
11789 
11790       // See if a warning is needed by checking the first difference in index
11791       // numbers.  If field being used has index less than the field being
11792       // initialized, then the use is safe.
11793       for (auto UsedIter = UsedFieldIndex.begin(),
11794                 UsedEnd = UsedFieldIndex.end(),
11795                 OrigIter = InitFieldIndex.begin(),
11796                 OrigEnd = InitFieldIndex.end();
11797            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11798         if (*UsedIter < *OrigIter)
11799           return true;
11800         if (*UsedIter > *OrigIter)
11801           break;
11802       }
11803 
11804       // TODO: Add a different warning which will print the field names.
11805       HandleDeclRefExpr(DRE);
11806       return true;
11807     }
11808 
11809     // For most expressions, the cast is directly above the DeclRefExpr.
11810     // For conditional operators, the cast can be outside the conditional
11811     // operator if both expressions are DeclRefExpr's.
11812     void HandleValue(Expr *E) {
11813       E = E->IgnoreParens();
11814       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11815         HandleDeclRefExpr(DRE);
11816         return;
11817       }
11818 
11819       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11820         Visit(CO->getCond());
11821         HandleValue(CO->getTrueExpr());
11822         HandleValue(CO->getFalseExpr());
11823         return;
11824       }
11825 
11826       if (BinaryConditionalOperator *BCO =
11827               dyn_cast<BinaryConditionalOperator>(E)) {
11828         Visit(BCO->getCond());
11829         HandleValue(BCO->getFalseExpr());
11830         return;
11831       }
11832 
11833       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11834         HandleValue(OVE->getSourceExpr());
11835         return;
11836       }
11837 
11838       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11839         if (BO->getOpcode() == BO_Comma) {
11840           Visit(BO->getLHS());
11841           HandleValue(BO->getRHS());
11842           return;
11843         }
11844       }
11845 
11846       if (isa<MemberExpr>(E)) {
11847         if (isInitList) {
11848           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11849                                       false /*CheckReference*/))
11850             return;
11851         }
11852 
11853         Expr *Base = E->IgnoreParenImpCasts();
11854         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11855           // Check for static member variables and don't warn on them.
11856           if (!isa<FieldDecl>(ME->getMemberDecl()))
11857             return;
11858           Base = ME->getBase()->IgnoreParenImpCasts();
11859         }
11860         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11861           HandleDeclRefExpr(DRE);
11862         return;
11863       }
11864 
11865       Visit(E);
11866     }
11867 
11868     // Reference types not handled in HandleValue are handled here since all
11869     // uses of references are bad, not just r-value uses.
11870     void VisitDeclRefExpr(DeclRefExpr *E) {
11871       if (isReferenceType)
11872         HandleDeclRefExpr(E);
11873     }
11874 
11875     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11876       if (E->getCastKind() == CK_LValueToRValue) {
11877         HandleValue(E->getSubExpr());
11878         return;
11879       }
11880 
11881       Inherited::VisitImplicitCastExpr(E);
11882     }
11883 
11884     void VisitMemberExpr(MemberExpr *E) {
11885       if (isInitList) {
11886         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11887           return;
11888       }
11889 
11890       // Don't warn on arrays since they can be treated as pointers.
11891       if (E->getType()->canDecayToPointerType()) return;
11892 
11893       // Warn when a non-static method call is followed by non-static member
11894       // field accesses, which is followed by a DeclRefExpr.
11895       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11896       bool Warn = (MD && !MD->isStatic());
11897       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11898       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11899         if (!isa<FieldDecl>(ME->getMemberDecl()))
11900           Warn = false;
11901         Base = ME->getBase()->IgnoreParenImpCasts();
11902       }
11903 
11904       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11905         if (Warn)
11906           HandleDeclRefExpr(DRE);
11907         return;
11908       }
11909 
11910       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11911       // Visit that expression.
11912       Visit(Base);
11913     }
11914 
11915     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11916       Expr *Callee = E->getCallee();
11917 
11918       if (isa<UnresolvedLookupExpr>(Callee))
11919         return Inherited::VisitCXXOperatorCallExpr(E);
11920 
11921       Visit(Callee);
11922       for (auto Arg: E->arguments())
11923         HandleValue(Arg->IgnoreParenImpCasts());
11924     }
11925 
11926     void VisitUnaryOperator(UnaryOperator *E) {
11927       // For POD record types, addresses of its own members are well-defined.
11928       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11929           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11930         if (!isPODType)
11931           HandleValue(E->getSubExpr());
11932         return;
11933       }
11934 
11935       if (E->isIncrementDecrementOp()) {
11936         HandleValue(E->getSubExpr());
11937         return;
11938       }
11939 
11940       Inherited::VisitUnaryOperator(E);
11941     }
11942 
11943     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11944 
11945     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11946       if (E->getConstructor()->isCopyConstructor()) {
11947         Expr *ArgExpr = E->getArg(0);
11948         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11949           if (ILE->getNumInits() == 1)
11950             ArgExpr = ILE->getInit(0);
11951         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11952           if (ICE->getCastKind() == CK_NoOp)
11953             ArgExpr = ICE->getSubExpr();
11954         HandleValue(ArgExpr);
11955         return;
11956       }
11957       Inherited::VisitCXXConstructExpr(E);
11958     }
11959 
11960     void VisitCallExpr(CallExpr *E) {
11961       // Treat std::move as a use.
11962       if (E->isCallToStdMove()) {
11963         HandleValue(E->getArg(0));
11964         return;
11965       }
11966 
11967       Inherited::VisitCallExpr(E);
11968     }
11969 
11970     void VisitBinaryOperator(BinaryOperator *E) {
11971       if (E->isCompoundAssignmentOp()) {
11972         HandleValue(E->getLHS());
11973         Visit(E->getRHS());
11974         return;
11975       }
11976 
11977       Inherited::VisitBinaryOperator(E);
11978     }
11979 
11980     // A custom visitor for BinaryConditionalOperator is needed because the
11981     // regular visitor would check the condition and true expression separately
11982     // but both point to the same place giving duplicate diagnostics.
11983     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11984       Visit(E->getCond());
11985       Visit(E->getFalseExpr());
11986     }
11987 
11988     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11989       Decl* ReferenceDecl = DRE->getDecl();
11990       if (OrigDecl != ReferenceDecl) return;
11991       unsigned diag;
11992       if (isReferenceType) {
11993         diag = diag::warn_uninit_self_reference_in_reference_init;
11994       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11995         diag = diag::warn_static_self_reference_in_init;
11996       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11997                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11998                  DRE->getDecl()->getType()->isRecordType()) {
11999         diag = diag::warn_uninit_self_reference_in_init;
12000       } else {
12001         // Local variables will be handled by the CFG analysis.
12002         return;
12003       }
12004 
12005       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12006                             S.PDiag(diag)
12007                                 << DRE->getDecl() << OrigDecl->getLocation()
12008                                 << DRE->getSourceRange());
12009     }
12010   };
12011 
12012   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12013   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12014                                  bool DirectInit) {
12015     // Parameters arguments are occassionially constructed with itself,
12016     // for instance, in recursive functions.  Skip them.
12017     if (isa<ParmVarDecl>(OrigDecl))
12018       return;
12019 
12020     E = E->IgnoreParens();
12021 
12022     // Skip checking T a = a where T is not a record or reference type.
12023     // Doing so is a way to silence uninitialized warnings.
12024     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12025       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12026         if (ICE->getCastKind() == CK_LValueToRValue)
12027           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12028             if (DRE->getDecl() == OrigDecl)
12029               return;
12030 
12031     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12032   }
12033 } // end anonymous namespace
12034 
12035 namespace {
12036   // Simple wrapper to add the name of a variable or (if no variable is
12037   // available) a DeclarationName into a diagnostic.
12038   struct VarDeclOrName {
12039     VarDecl *VDecl;
12040     DeclarationName Name;
12041 
12042     friend const Sema::SemaDiagnosticBuilder &
12043     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12044       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12045     }
12046   };
12047 } // end anonymous namespace
12048 
12049 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12050                                             DeclarationName Name, QualType Type,
12051                                             TypeSourceInfo *TSI,
12052                                             SourceRange Range, bool DirectInit,
12053                                             Expr *Init) {
12054   bool IsInitCapture = !VDecl;
12055   assert((!VDecl || !VDecl->isInitCapture()) &&
12056          "init captures are expected to be deduced prior to initialization");
12057 
12058   VarDeclOrName VN{VDecl, Name};
12059 
12060   DeducedType *Deduced = Type->getContainedDeducedType();
12061   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12062 
12063   // C++11 [dcl.spec.auto]p3
12064   if (!Init) {
12065     assert(VDecl && "no init for init capture deduction?");
12066 
12067     // Except for class argument deduction, and then for an initializing
12068     // declaration only, i.e. no static at class scope or extern.
12069     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12070         VDecl->hasExternalStorage() ||
12071         VDecl->isStaticDataMember()) {
12072       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12073         << VDecl->getDeclName() << Type;
12074       return QualType();
12075     }
12076   }
12077 
12078   ArrayRef<Expr*> DeduceInits;
12079   if (Init)
12080     DeduceInits = Init;
12081 
12082   if (DirectInit) {
12083     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12084       DeduceInits = PL->exprs();
12085   }
12086 
12087   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12088     assert(VDecl && "non-auto type for init capture deduction?");
12089     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12090     InitializationKind Kind = InitializationKind::CreateForInit(
12091         VDecl->getLocation(), DirectInit, Init);
12092     // FIXME: Initialization should not be taking a mutable list of inits.
12093     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12094     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12095                                                        InitsCopy);
12096   }
12097 
12098   if (DirectInit) {
12099     if (auto *IL = dyn_cast<InitListExpr>(Init))
12100       DeduceInits = IL->inits();
12101   }
12102 
12103   // Deduction only works if we have exactly one source expression.
12104   if (DeduceInits.empty()) {
12105     // It isn't possible to write this directly, but it is possible to
12106     // end up in this situation with "auto x(some_pack...);"
12107     Diag(Init->getBeginLoc(), IsInitCapture
12108                                   ? diag::err_init_capture_no_expression
12109                                   : diag::err_auto_var_init_no_expression)
12110         << VN << Type << Range;
12111     return QualType();
12112   }
12113 
12114   if (DeduceInits.size() > 1) {
12115     Diag(DeduceInits[1]->getBeginLoc(),
12116          IsInitCapture ? diag::err_init_capture_multiple_expressions
12117                        : diag::err_auto_var_init_multiple_expressions)
12118         << VN << Type << Range;
12119     return QualType();
12120   }
12121 
12122   Expr *DeduceInit = DeduceInits[0];
12123   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12124     Diag(Init->getBeginLoc(), IsInitCapture
12125                                   ? diag::err_init_capture_paren_braces
12126                                   : diag::err_auto_var_init_paren_braces)
12127         << isa<InitListExpr>(Init) << VN << Type << Range;
12128     return QualType();
12129   }
12130 
12131   // Expressions default to 'id' when we're in a debugger.
12132   bool DefaultedAnyToId = false;
12133   if (getLangOpts().DebuggerCastResultToId &&
12134       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12135     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12136     if (Result.isInvalid()) {
12137       return QualType();
12138     }
12139     Init = Result.get();
12140     DefaultedAnyToId = true;
12141   }
12142 
12143   // C++ [dcl.decomp]p1:
12144   //   If the assignment-expression [...] has array type A and no ref-qualifier
12145   //   is present, e has type cv A
12146   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12147       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12148       DeduceInit->getType()->isConstantArrayType())
12149     return Context.getQualifiedType(DeduceInit->getType(),
12150                                     Type.getQualifiers());
12151 
12152   QualType DeducedType;
12153   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12154     if (!IsInitCapture)
12155       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12156     else if (isa<InitListExpr>(Init))
12157       Diag(Range.getBegin(),
12158            diag::err_init_capture_deduction_failure_from_init_list)
12159           << VN
12160           << (DeduceInit->getType().isNull() ? TSI->getType()
12161                                              : DeduceInit->getType())
12162           << DeduceInit->getSourceRange();
12163     else
12164       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12165           << VN << TSI->getType()
12166           << (DeduceInit->getType().isNull() ? TSI->getType()
12167                                              : DeduceInit->getType())
12168           << DeduceInit->getSourceRange();
12169   }
12170 
12171   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12172   // 'id' instead of a specific object type prevents most of our usual
12173   // checks.
12174   // We only want to warn outside of template instantiations, though:
12175   // inside a template, the 'id' could have come from a parameter.
12176   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12177       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12178     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12179     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12180   }
12181 
12182   return DeducedType;
12183 }
12184 
12185 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12186                                          Expr *Init) {
12187   assert(!Init || !Init->containsErrors());
12188   QualType DeducedType = deduceVarTypeFromInitializer(
12189       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12190       VDecl->getSourceRange(), DirectInit, Init);
12191   if (DeducedType.isNull()) {
12192     VDecl->setInvalidDecl();
12193     return true;
12194   }
12195 
12196   VDecl->setType(DeducedType);
12197   assert(VDecl->isLinkageValid());
12198 
12199   // In ARC, infer lifetime.
12200   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12201     VDecl->setInvalidDecl();
12202 
12203   if (getLangOpts().OpenCL)
12204     deduceOpenCLAddressSpace(VDecl);
12205 
12206   // If this is a redeclaration, check that the type we just deduced matches
12207   // the previously declared type.
12208   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12209     // We never need to merge the type, because we cannot form an incomplete
12210     // array of auto, nor deduce such a type.
12211     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12212   }
12213 
12214   // Check the deduced type is valid for a variable declaration.
12215   CheckVariableDeclarationType(VDecl);
12216   return VDecl->isInvalidDecl();
12217 }
12218 
12219 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12220                                               SourceLocation Loc) {
12221   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12222     Init = EWC->getSubExpr();
12223 
12224   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12225     Init = CE->getSubExpr();
12226 
12227   QualType InitType = Init->getType();
12228   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12229           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12230          "shouldn't be called if type doesn't have a non-trivial C struct");
12231   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12232     for (auto I : ILE->inits()) {
12233       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12234           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12235         continue;
12236       SourceLocation SL = I->getExprLoc();
12237       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12238     }
12239     return;
12240   }
12241 
12242   if (isa<ImplicitValueInitExpr>(Init)) {
12243     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12244       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12245                             NTCUK_Init);
12246   } else {
12247     // Assume all other explicit initializers involving copying some existing
12248     // object.
12249     // TODO: ignore any explicit initializers where we can guarantee
12250     // copy-elision.
12251     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12252       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12253   }
12254 }
12255 
12256 namespace {
12257 
12258 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12259   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12260   // in the source code or implicitly by the compiler if it is in a union
12261   // defined in a system header and has non-trivial ObjC ownership
12262   // qualifications. We don't want those fields to participate in determining
12263   // whether the containing union is non-trivial.
12264   return FD->hasAttr<UnavailableAttr>();
12265 }
12266 
12267 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12268     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12269                                     void> {
12270   using Super =
12271       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12272                                     void>;
12273 
12274   DiagNonTrivalCUnionDefaultInitializeVisitor(
12275       QualType OrigTy, SourceLocation OrigLoc,
12276       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12277       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12278 
12279   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12280                      const FieldDecl *FD, bool InNonTrivialUnion) {
12281     if (const auto *AT = S.Context.getAsArrayType(QT))
12282       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12283                                      InNonTrivialUnion);
12284     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12285   }
12286 
12287   void visitARCStrong(QualType QT, const FieldDecl *FD,
12288                       bool InNonTrivialUnion) {
12289     if (InNonTrivialUnion)
12290       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12291           << 1 << 0 << QT << FD->getName();
12292   }
12293 
12294   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12295     if (InNonTrivialUnion)
12296       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12297           << 1 << 0 << QT << FD->getName();
12298   }
12299 
12300   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12301     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12302     if (RD->isUnion()) {
12303       if (OrigLoc.isValid()) {
12304         bool IsUnion = false;
12305         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12306           IsUnion = OrigRD->isUnion();
12307         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12308             << 0 << OrigTy << IsUnion << UseContext;
12309         // Reset OrigLoc so that this diagnostic is emitted only once.
12310         OrigLoc = SourceLocation();
12311       }
12312       InNonTrivialUnion = true;
12313     }
12314 
12315     if (InNonTrivialUnion)
12316       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12317           << 0 << 0 << QT.getUnqualifiedType() << "";
12318 
12319     for (const FieldDecl *FD : RD->fields())
12320       if (!shouldIgnoreForRecordTriviality(FD))
12321         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12322   }
12323 
12324   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12325 
12326   // The non-trivial C union type or the struct/union type that contains a
12327   // non-trivial C union.
12328   QualType OrigTy;
12329   SourceLocation OrigLoc;
12330   Sema::NonTrivialCUnionContext UseContext;
12331   Sema &S;
12332 };
12333 
12334 struct DiagNonTrivalCUnionDestructedTypeVisitor
12335     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12336   using Super =
12337       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12338 
12339   DiagNonTrivalCUnionDestructedTypeVisitor(
12340       QualType OrigTy, SourceLocation OrigLoc,
12341       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12342       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12343 
12344   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12345                      const FieldDecl *FD, bool InNonTrivialUnion) {
12346     if (const auto *AT = S.Context.getAsArrayType(QT))
12347       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12348                                      InNonTrivialUnion);
12349     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12350   }
12351 
12352   void visitARCStrong(QualType QT, const FieldDecl *FD,
12353                       bool InNonTrivialUnion) {
12354     if (InNonTrivialUnion)
12355       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12356           << 1 << 1 << QT << FD->getName();
12357   }
12358 
12359   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12360     if (InNonTrivialUnion)
12361       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12362           << 1 << 1 << QT << FD->getName();
12363   }
12364 
12365   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12366     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12367     if (RD->isUnion()) {
12368       if (OrigLoc.isValid()) {
12369         bool IsUnion = false;
12370         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12371           IsUnion = OrigRD->isUnion();
12372         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12373             << 1 << OrigTy << IsUnion << UseContext;
12374         // Reset OrigLoc so that this diagnostic is emitted only once.
12375         OrigLoc = SourceLocation();
12376       }
12377       InNonTrivialUnion = true;
12378     }
12379 
12380     if (InNonTrivialUnion)
12381       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12382           << 0 << 1 << QT.getUnqualifiedType() << "";
12383 
12384     for (const FieldDecl *FD : RD->fields())
12385       if (!shouldIgnoreForRecordTriviality(FD))
12386         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12387   }
12388 
12389   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12390   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12391                           bool InNonTrivialUnion) {}
12392 
12393   // The non-trivial C union type or the struct/union type that contains a
12394   // non-trivial C union.
12395   QualType OrigTy;
12396   SourceLocation OrigLoc;
12397   Sema::NonTrivialCUnionContext UseContext;
12398   Sema &S;
12399 };
12400 
12401 struct DiagNonTrivalCUnionCopyVisitor
12402     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12403   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12404 
12405   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12406                                  Sema::NonTrivialCUnionContext UseContext,
12407                                  Sema &S)
12408       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12409 
12410   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12411                      const FieldDecl *FD, bool InNonTrivialUnion) {
12412     if (const auto *AT = S.Context.getAsArrayType(QT))
12413       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12414                                      InNonTrivialUnion);
12415     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12416   }
12417 
12418   void visitARCStrong(QualType QT, const FieldDecl *FD,
12419                       bool InNonTrivialUnion) {
12420     if (InNonTrivialUnion)
12421       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12422           << 1 << 2 << QT << FD->getName();
12423   }
12424 
12425   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12426     if (InNonTrivialUnion)
12427       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12428           << 1 << 2 << QT << FD->getName();
12429   }
12430 
12431   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12432     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12433     if (RD->isUnion()) {
12434       if (OrigLoc.isValid()) {
12435         bool IsUnion = false;
12436         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12437           IsUnion = OrigRD->isUnion();
12438         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12439             << 2 << OrigTy << IsUnion << UseContext;
12440         // Reset OrigLoc so that this diagnostic is emitted only once.
12441         OrigLoc = SourceLocation();
12442       }
12443       InNonTrivialUnion = true;
12444     }
12445 
12446     if (InNonTrivialUnion)
12447       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12448           << 0 << 2 << QT.getUnqualifiedType() << "";
12449 
12450     for (const FieldDecl *FD : RD->fields())
12451       if (!shouldIgnoreForRecordTriviality(FD))
12452         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12453   }
12454 
12455   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12456                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12457   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12458   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12459                             bool InNonTrivialUnion) {}
12460 
12461   // The non-trivial C union type or the struct/union type that contains a
12462   // non-trivial C union.
12463   QualType OrigTy;
12464   SourceLocation OrigLoc;
12465   Sema::NonTrivialCUnionContext UseContext;
12466   Sema &S;
12467 };
12468 
12469 } // namespace
12470 
12471 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12472                                  NonTrivialCUnionContext UseContext,
12473                                  unsigned NonTrivialKind) {
12474   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12475           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12476           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12477          "shouldn't be called if type doesn't have a non-trivial C union");
12478 
12479   if ((NonTrivialKind & NTCUK_Init) &&
12480       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12481     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12482         .visit(QT, nullptr, false);
12483   if ((NonTrivialKind & NTCUK_Destruct) &&
12484       QT.hasNonTrivialToPrimitiveDestructCUnion())
12485     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12486         .visit(QT, nullptr, false);
12487   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12488     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12489         .visit(QT, nullptr, false);
12490 }
12491 
12492 /// AddInitializerToDecl - Adds the initializer Init to the
12493 /// declaration dcl. If DirectInit is true, this is C++ direct
12494 /// initialization rather than copy initialization.
12495 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12496   // If there is no declaration, there was an error parsing it.  Just ignore
12497   // the initializer.
12498   if (!RealDecl || RealDecl->isInvalidDecl()) {
12499     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12500     return;
12501   }
12502 
12503   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12504     // Pure-specifiers are handled in ActOnPureSpecifier.
12505     Diag(Method->getLocation(), diag::err_member_function_initialization)
12506       << Method->getDeclName() << Init->getSourceRange();
12507     Method->setInvalidDecl();
12508     return;
12509   }
12510 
12511   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12512   if (!VDecl) {
12513     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12514     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12515     RealDecl->setInvalidDecl();
12516     return;
12517   }
12518 
12519   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12520   if (VDecl->getType()->isUndeducedType()) {
12521     // Attempt typo correction early so that the type of the init expression can
12522     // be deduced based on the chosen correction if the original init contains a
12523     // TypoExpr.
12524     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12525     if (!Res.isUsable()) {
12526       // There are unresolved typos in Init, just drop them.
12527       // FIXME: improve the recovery strategy to preserve the Init.
12528       RealDecl->setInvalidDecl();
12529       return;
12530     }
12531     if (Res.get()->containsErrors()) {
12532       // Invalidate the decl as we don't know the type for recovery-expr yet.
12533       RealDecl->setInvalidDecl();
12534       VDecl->setInit(Res.get());
12535       return;
12536     }
12537     Init = Res.get();
12538 
12539     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12540       return;
12541   }
12542 
12543   // dllimport cannot be used on variable definitions.
12544   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12545     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12546     VDecl->setInvalidDecl();
12547     return;
12548   }
12549 
12550   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12551     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12552     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12553     VDecl->setInvalidDecl();
12554     return;
12555   }
12556 
12557   if (!VDecl->getType()->isDependentType()) {
12558     // A definition must end up with a complete type, which means it must be
12559     // complete with the restriction that an array type might be completed by
12560     // the initializer; note that later code assumes this restriction.
12561     QualType BaseDeclType = VDecl->getType();
12562     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12563       BaseDeclType = Array->getElementType();
12564     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12565                             diag::err_typecheck_decl_incomplete_type)) {
12566       RealDecl->setInvalidDecl();
12567       return;
12568     }
12569 
12570     // The variable can not have an abstract class type.
12571     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12572                                diag::err_abstract_type_in_decl,
12573                                AbstractVariableType))
12574       VDecl->setInvalidDecl();
12575   }
12576 
12577   // If adding the initializer will turn this declaration into a definition,
12578   // and we already have a definition for this variable, diagnose or otherwise
12579   // handle the situation.
12580   if (VarDecl *Def = VDecl->getDefinition())
12581     if (Def != VDecl &&
12582         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12583         !VDecl->isThisDeclarationADemotedDefinition() &&
12584         checkVarDeclRedefinition(Def, VDecl))
12585       return;
12586 
12587   if (getLangOpts().CPlusPlus) {
12588     // C++ [class.static.data]p4
12589     //   If a static data member is of const integral or const
12590     //   enumeration type, its declaration in the class definition can
12591     //   specify a constant-initializer which shall be an integral
12592     //   constant expression (5.19). In that case, the member can appear
12593     //   in integral constant expressions. The member shall still be
12594     //   defined in a namespace scope if it is used in the program and the
12595     //   namespace scope definition shall not contain an initializer.
12596     //
12597     // We already performed a redefinition check above, but for static
12598     // data members we also need to check whether there was an in-class
12599     // declaration with an initializer.
12600     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12601       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12602           << VDecl->getDeclName();
12603       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12604            diag::note_previous_initializer)
12605           << 0;
12606       return;
12607     }
12608 
12609     if (VDecl->hasLocalStorage())
12610       setFunctionHasBranchProtectedScope();
12611 
12612     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12613       VDecl->setInvalidDecl();
12614       return;
12615     }
12616   }
12617 
12618   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12619   // a kernel function cannot be initialized."
12620   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12621     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12622     VDecl->setInvalidDecl();
12623     return;
12624   }
12625 
12626   // The LoaderUninitialized attribute acts as a definition (of undef).
12627   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12628     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12629     VDecl->setInvalidDecl();
12630     return;
12631   }
12632 
12633   // Get the decls type and save a reference for later, since
12634   // CheckInitializerTypes may change it.
12635   QualType DclT = VDecl->getType(), SavT = DclT;
12636 
12637   // Expressions default to 'id' when we're in a debugger
12638   // and we are assigning it to a variable of Objective-C pointer type.
12639   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12640       Init->getType() == Context.UnknownAnyTy) {
12641     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12642     if (Result.isInvalid()) {
12643       VDecl->setInvalidDecl();
12644       return;
12645     }
12646     Init = Result.get();
12647   }
12648 
12649   // Perform the initialization.
12650   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12651   if (!VDecl->isInvalidDecl()) {
12652     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12653     InitializationKind Kind = InitializationKind::CreateForInit(
12654         VDecl->getLocation(), DirectInit, Init);
12655 
12656     MultiExprArg Args = Init;
12657     if (CXXDirectInit)
12658       Args = MultiExprArg(CXXDirectInit->getExprs(),
12659                           CXXDirectInit->getNumExprs());
12660 
12661     // Try to correct any TypoExprs in the initialization arguments.
12662     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12663       ExprResult Res = CorrectDelayedTyposInExpr(
12664           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12665           [this, Entity, Kind](Expr *E) {
12666             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12667             return Init.Failed() ? ExprError() : E;
12668           });
12669       if (Res.isInvalid()) {
12670         VDecl->setInvalidDecl();
12671       } else if (Res.get() != Args[Idx]) {
12672         Args[Idx] = Res.get();
12673       }
12674     }
12675     if (VDecl->isInvalidDecl())
12676       return;
12677 
12678     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12679                                    /*TopLevelOfInitList=*/false,
12680                                    /*TreatUnavailableAsInvalid=*/false);
12681     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12682     if (Result.isInvalid()) {
12683       // If the provided initializer fails to initialize the var decl,
12684       // we attach a recovery expr for better recovery.
12685       auto RecoveryExpr =
12686           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12687       if (RecoveryExpr.get())
12688         VDecl->setInit(RecoveryExpr.get());
12689       return;
12690     }
12691 
12692     Init = Result.getAs<Expr>();
12693   }
12694 
12695   // Check for self-references within variable initializers.
12696   // Variables declared within a function/method body (except for references)
12697   // are handled by a dataflow analysis.
12698   // This is undefined behavior in C++, but valid in C.
12699   if (getLangOpts().CPlusPlus)
12700     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12701         VDecl->getType()->isReferenceType())
12702       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12703 
12704   // If the type changed, it means we had an incomplete type that was
12705   // completed by the initializer. For example:
12706   //   int ary[] = { 1, 3, 5 };
12707   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12708   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12709     VDecl->setType(DclT);
12710 
12711   if (!VDecl->isInvalidDecl()) {
12712     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12713 
12714     if (VDecl->hasAttr<BlocksAttr>())
12715       checkRetainCycles(VDecl, Init);
12716 
12717     // It is safe to assign a weak reference into a strong variable.
12718     // Although this code can still have problems:
12719     //   id x = self.weakProp;
12720     //   id y = self.weakProp;
12721     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12722     // paths through the function. This should be revisited if
12723     // -Wrepeated-use-of-weak is made flow-sensitive.
12724     if (FunctionScopeInfo *FSI = getCurFunction())
12725       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12726            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12727           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12728                            Init->getBeginLoc()))
12729         FSI->markSafeWeakUse(Init);
12730   }
12731 
12732   // The initialization is usually a full-expression.
12733   //
12734   // FIXME: If this is a braced initialization of an aggregate, it is not
12735   // an expression, and each individual field initializer is a separate
12736   // full-expression. For instance, in:
12737   //
12738   //   struct Temp { ~Temp(); };
12739   //   struct S { S(Temp); };
12740   //   struct T { S a, b; } t = { Temp(), Temp() }
12741   //
12742   // we should destroy the first Temp before constructing the second.
12743   ExprResult Result =
12744       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12745                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12746   if (Result.isInvalid()) {
12747     VDecl->setInvalidDecl();
12748     return;
12749   }
12750   Init = Result.get();
12751 
12752   // Attach the initializer to the decl.
12753   VDecl->setInit(Init);
12754 
12755   if (VDecl->isLocalVarDecl()) {
12756     // Don't check the initializer if the declaration is malformed.
12757     if (VDecl->isInvalidDecl()) {
12758       // do nothing
12759 
12760     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12761     // This is true even in C++ for OpenCL.
12762     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12763       CheckForConstantInitializer(Init, DclT);
12764 
12765     // Otherwise, C++ does not restrict the initializer.
12766     } else if (getLangOpts().CPlusPlus) {
12767       // do nothing
12768 
12769     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12770     // static storage duration shall be constant expressions or string literals.
12771     } else if (VDecl->getStorageClass() == SC_Static) {
12772       CheckForConstantInitializer(Init, DclT);
12773 
12774     // C89 is stricter than C99 for aggregate initializers.
12775     // C89 6.5.7p3: All the expressions [...] in an initializer list
12776     // for an object that has aggregate or union type shall be
12777     // constant expressions.
12778     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12779                isa<InitListExpr>(Init)) {
12780       const Expr *Culprit;
12781       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12782         Diag(Culprit->getExprLoc(),
12783              diag::ext_aggregate_init_not_constant)
12784           << Culprit->getSourceRange();
12785       }
12786     }
12787 
12788     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12789       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12790         if (VDecl->hasLocalStorage())
12791           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12792   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12793              VDecl->getLexicalDeclContext()->isRecord()) {
12794     // This is an in-class initialization for a static data member, e.g.,
12795     //
12796     // struct S {
12797     //   static const int value = 17;
12798     // };
12799 
12800     // C++ [class.mem]p4:
12801     //   A member-declarator can contain a constant-initializer only
12802     //   if it declares a static member (9.4) of const integral or
12803     //   const enumeration type, see 9.4.2.
12804     //
12805     // C++11 [class.static.data]p3:
12806     //   If a non-volatile non-inline const static data member is of integral
12807     //   or enumeration type, its declaration in the class definition can
12808     //   specify a brace-or-equal-initializer in which every initializer-clause
12809     //   that is an assignment-expression is a constant expression. A static
12810     //   data member of literal type can be declared in the class definition
12811     //   with the constexpr specifier; if so, its declaration shall specify a
12812     //   brace-or-equal-initializer in which every initializer-clause that is
12813     //   an assignment-expression is a constant expression.
12814 
12815     // Do nothing on dependent types.
12816     if (DclT->isDependentType()) {
12817 
12818     // Allow any 'static constexpr' members, whether or not they are of literal
12819     // type. We separately check that every constexpr variable is of literal
12820     // type.
12821     } else if (VDecl->isConstexpr()) {
12822 
12823     // Require constness.
12824     } else if (!DclT.isConstQualified()) {
12825       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12826         << Init->getSourceRange();
12827       VDecl->setInvalidDecl();
12828 
12829     // We allow integer constant expressions in all cases.
12830     } else if (DclT->isIntegralOrEnumerationType()) {
12831       // Check whether the expression is a constant expression.
12832       SourceLocation Loc;
12833       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12834         // In C++11, a non-constexpr const static data member with an
12835         // in-class initializer cannot be volatile.
12836         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12837       else if (Init->isValueDependent())
12838         ; // Nothing to check.
12839       else if (Init->isIntegerConstantExpr(Context, &Loc))
12840         ; // Ok, it's an ICE!
12841       else if (Init->getType()->isScopedEnumeralType() &&
12842                Init->isCXX11ConstantExpr(Context))
12843         ; // Ok, it is a scoped-enum constant expression.
12844       else if (Init->isEvaluatable(Context)) {
12845         // If we can constant fold the initializer through heroics, accept it,
12846         // but report this as a use of an extension for -pedantic.
12847         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12848           << Init->getSourceRange();
12849       } else {
12850         // Otherwise, this is some crazy unknown case.  Report the issue at the
12851         // location provided by the isIntegerConstantExpr failed check.
12852         Diag(Loc, diag::err_in_class_initializer_non_constant)
12853           << Init->getSourceRange();
12854         VDecl->setInvalidDecl();
12855       }
12856 
12857     // We allow foldable floating-point constants as an extension.
12858     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12859       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12860       // it anyway and provide a fixit to add the 'constexpr'.
12861       if (getLangOpts().CPlusPlus11) {
12862         Diag(VDecl->getLocation(),
12863              diag::ext_in_class_initializer_float_type_cxx11)
12864             << DclT << Init->getSourceRange();
12865         Diag(VDecl->getBeginLoc(),
12866              diag::note_in_class_initializer_float_type_cxx11)
12867             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12868       } else {
12869         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12870           << DclT << Init->getSourceRange();
12871 
12872         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12873           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12874             << Init->getSourceRange();
12875           VDecl->setInvalidDecl();
12876         }
12877       }
12878 
12879     // Suggest adding 'constexpr' in C++11 for literal types.
12880     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12881       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12882           << DclT << Init->getSourceRange()
12883           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12884       VDecl->setConstexpr(true);
12885 
12886     } else {
12887       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12888         << DclT << Init->getSourceRange();
12889       VDecl->setInvalidDecl();
12890     }
12891   } else if (VDecl->isFileVarDecl()) {
12892     // In C, extern is typically used to avoid tentative definitions when
12893     // declaring variables in headers, but adding an intializer makes it a
12894     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12895     // In C++, extern is often used to give implictly static const variables
12896     // external linkage, so don't warn in that case. If selectany is present,
12897     // this might be header code intended for C and C++ inclusion, so apply the
12898     // C++ rules.
12899     if (VDecl->getStorageClass() == SC_Extern &&
12900         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12901          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12902         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12903         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12904       Diag(VDecl->getLocation(), diag::warn_extern_init);
12905 
12906     // In Microsoft C++ mode, a const variable defined in namespace scope has
12907     // external linkage by default if the variable is declared with
12908     // __declspec(dllexport).
12909     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12910         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12911         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12912       VDecl->setStorageClass(SC_Extern);
12913 
12914     // C99 6.7.8p4. All file scoped initializers need to be constant.
12915     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12916       CheckForConstantInitializer(Init, DclT);
12917   }
12918 
12919   QualType InitType = Init->getType();
12920   if (!InitType.isNull() &&
12921       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12922        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12923     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12924 
12925   // We will represent direct-initialization similarly to copy-initialization:
12926   //    int x(1);  -as-> int x = 1;
12927   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12928   //
12929   // Clients that want to distinguish between the two forms, can check for
12930   // direct initializer using VarDecl::getInitStyle().
12931   // A major benefit is that clients that don't particularly care about which
12932   // exactly form was it (like the CodeGen) can handle both cases without
12933   // special case code.
12934 
12935   // C++ 8.5p11:
12936   // The form of initialization (using parentheses or '=') is generally
12937   // insignificant, but does matter when the entity being initialized has a
12938   // class type.
12939   if (CXXDirectInit) {
12940     assert(DirectInit && "Call-style initializer must be direct init.");
12941     VDecl->setInitStyle(VarDecl::CallInit);
12942   } else if (DirectInit) {
12943     // This must be list-initialization. No other way is direct-initialization.
12944     VDecl->setInitStyle(VarDecl::ListInit);
12945   }
12946 
12947   if (LangOpts.OpenMP &&
12948       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12949       VDecl->isFileVarDecl())
12950     DeclsToCheckForDeferredDiags.insert(VDecl);
12951   CheckCompleteVariableDeclaration(VDecl);
12952 }
12953 
12954 /// ActOnInitializerError - Given that there was an error parsing an
12955 /// initializer for the given declaration, try to at least re-establish
12956 /// invariants such as whether a variable's type is either dependent or
12957 /// complete.
12958 void Sema::ActOnInitializerError(Decl *D) {
12959   // Our main concern here is re-establishing invariants like "a
12960   // variable's type is either dependent or complete".
12961   if (!D || D->isInvalidDecl()) return;
12962 
12963   VarDecl *VD = dyn_cast<VarDecl>(D);
12964   if (!VD) return;
12965 
12966   // Bindings are not usable if we can't make sense of the initializer.
12967   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12968     for (auto *BD : DD->bindings())
12969       BD->setInvalidDecl();
12970 
12971   // Auto types are meaningless if we can't make sense of the initializer.
12972   if (VD->getType()->isUndeducedType()) {
12973     D->setInvalidDecl();
12974     return;
12975   }
12976 
12977   QualType Ty = VD->getType();
12978   if (Ty->isDependentType()) return;
12979 
12980   // Require a complete type.
12981   if (RequireCompleteType(VD->getLocation(),
12982                           Context.getBaseElementType(Ty),
12983                           diag::err_typecheck_decl_incomplete_type)) {
12984     VD->setInvalidDecl();
12985     return;
12986   }
12987 
12988   // Require a non-abstract type.
12989   if (RequireNonAbstractType(VD->getLocation(), Ty,
12990                              diag::err_abstract_type_in_decl,
12991                              AbstractVariableType)) {
12992     VD->setInvalidDecl();
12993     return;
12994   }
12995 
12996   // Don't bother complaining about constructors or destructors,
12997   // though.
12998 }
12999 
13000 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13001   // If there is no declaration, there was an error parsing it. Just ignore it.
13002   if (!RealDecl)
13003     return;
13004 
13005   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13006     QualType Type = Var->getType();
13007 
13008     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13009     if (isa<DecompositionDecl>(RealDecl)) {
13010       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13011       Var->setInvalidDecl();
13012       return;
13013     }
13014 
13015     if (Type->isUndeducedType() &&
13016         DeduceVariableDeclarationType(Var, false, nullptr))
13017       return;
13018 
13019     // C++11 [class.static.data]p3: A static data member can be declared with
13020     // the constexpr specifier; if so, its declaration shall specify
13021     // a brace-or-equal-initializer.
13022     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13023     // the definition of a variable [...] or the declaration of a static data
13024     // member.
13025     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13026         !Var->isThisDeclarationADemotedDefinition()) {
13027       if (Var->isStaticDataMember()) {
13028         // C++1z removes the relevant rule; the in-class declaration is always
13029         // a definition there.
13030         if (!getLangOpts().CPlusPlus17 &&
13031             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13032           Diag(Var->getLocation(),
13033                diag::err_constexpr_static_mem_var_requires_init)
13034               << Var;
13035           Var->setInvalidDecl();
13036           return;
13037         }
13038       } else {
13039         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13040         Var->setInvalidDecl();
13041         return;
13042       }
13043     }
13044 
13045     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13046     // be initialized.
13047     if (!Var->isInvalidDecl() &&
13048         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13049         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13050       bool HasConstExprDefaultConstructor = false;
13051       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13052         for (auto *Ctor : RD->ctors()) {
13053           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13054               Ctor->getMethodQualifiers().getAddressSpace() ==
13055                   LangAS::opencl_constant) {
13056             HasConstExprDefaultConstructor = true;
13057           }
13058         }
13059       }
13060       if (!HasConstExprDefaultConstructor) {
13061         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13062         Var->setInvalidDecl();
13063         return;
13064       }
13065     }
13066 
13067     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13068       if (Var->getStorageClass() == SC_Extern) {
13069         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13070             << Var;
13071         Var->setInvalidDecl();
13072         return;
13073       }
13074       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13075                               diag::err_typecheck_decl_incomplete_type)) {
13076         Var->setInvalidDecl();
13077         return;
13078       }
13079       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13080         if (!RD->hasTrivialDefaultConstructor()) {
13081           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13082           Var->setInvalidDecl();
13083           return;
13084         }
13085       }
13086       // The declaration is unitialized, no need for further checks.
13087       return;
13088     }
13089 
13090     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13091     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13092         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13093       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13094                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13095 
13096 
13097     switch (DefKind) {
13098     case VarDecl::Definition:
13099       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13100         break;
13101 
13102       // We have an out-of-line definition of a static data member
13103       // that has an in-class initializer, so we type-check this like
13104       // a declaration.
13105       //
13106       LLVM_FALLTHROUGH;
13107 
13108     case VarDecl::DeclarationOnly:
13109       // It's only a declaration.
13110 
13111       // Block scope. C99 6.7p7: If an identifier for an object is
13112       // declared with no linkage (C99 6.2.2p6), the type for the
13113       // object shall be complete.
13114       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13115           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13116           RequireCompleteType(Var->getLocation(), Type,
13117                               diag::err_typecheck_decl_incomplete_type))
13118         Var->setInvalidDecl();
13119 
13120       // Make sure that the type is not abstract.
13121       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13122           RequireNonAbstractType(Var->getLocation(), Type,
13123                                  diag::err_abstract_type_in_decl,
13124                                  AbstractVariableType))
13125         Var->setInvalidDecl();
13126       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13127           Var->getStorageClass() == SC_PrivateExtern) {
13128         Diag(Var->getLocation(), diag::warn_private_extern);
13129         Diag(Var->getLocation(), diag::note_private_extern);
13130       }
13131 
13132       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13133           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13134         ExternalDeclarations.push_back(Var);
13135 
13136       return;
13137 
13138     case VarDecl::TentativeDefinition:
13139       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13140       // object that has file scope without an initializer, and without a
13141       // storage-class specifier or with the storage-class specifier "static",
13142       // constitutes a tentative definition. Note: A tentative definition with
13143       // external linkage is valid (C99 6.2.2p5).
13144       if (!Var->isInvalidDecl()) {
13145         if (const IncompleteArrayType *ArrayT
13146                                     = Context.getAsIncompleteArrayType(Type)) {
13147           if (RequireCompleteSizedType(
13148                   Var->getLocation(), ArrayT->getElementType(),
13149                   diag::err_array_incomplete_or_sizeless_type))
13150             Var->setInvalidDecl();
13151         } else if (Var->getStorageClass() == SC_Static) {
13152           // C99 6.9.2p3: If the declaration of an identifier for an object is
13153           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13154           // declared type shall not be an incomplete type.
13155           // NOTE: code such as the following
13156           //     static struct s;
13157           //     struct s { int a; };
13158           // is accepted by gcc. Hence here we issue a warning instead of
13159           // an error and we do not invalidate the static declaration.
13160           // NOTE: to avoid multiple warnings, only check the first declaration.
13161           if (Var->isFirstDecl())
13162             RequireCompleteType(Var->getLocation(), Type,
13163                                 diag::ext_typecheck_decl_incomplete_type);
13164         }
13165       }
13166 
13167       // Record the tentative definition; we're done.
13168       if (!Var->isInvalidDecl())
13169         TentativeDefinitions.push_back(Var);
13170       return;
13171     }
13172 
13173     // Provide a specific diagnostic for uninitialized variable
13174     // definitions with incomplete array type.
13175     if (Type->isIncompleteArrayType()) {
13176       Diag(Var->getLocation(),
13177            diag::err_typecheck_incomplete_array_needs_initializer);
13178       Var->setInvalidDecl();
13179       return;
13180     }
13181 
13182     // Provide a specific diagnostic for uninitialized variable
13183     // definitions with reference type.
13184     if (Type->isReferenceType()) {
13185       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13186           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13187       Var->setInvalidDecl();
13188       return;
13189     }
13190 
13191     // Do not attempt to type-check the default initializer for a
13192     // variable with dependent type.
13193     if (Type->isDependentType())
13194       return;
13195 
13196     if (Var->isInvalidDecl())
13197       return;
13198 
13199     if (!Var->hasAttr<AliasAttr>()) {
13200       if (RequireCompleteType(Var->getLocation(),
13201                               Context.getBaseElementType(Type),
13202                               diag::err_typecheck_decl_incomplete_type)) {
13203         Var->setInvalidDecl();
13204         return;
13205       }
13206     } else {
13207       return;
13208     }
13209 
13210     // The variable can not have an abstract class type.
13211     if (RequireNonAbstractType(Var->getLocation(), Type,
13212                                diag::err_abstract_type_in_decl,
13213                                AbstractVariableType)) {
13214       Var->setInvalidDecl();
13215       return;
13216     }
13217 
13218     // Check for jumps past the implicit initializer.  C++0x
13219     // clarifies that this applies to a "variable with automatic
13220     // storage duration", not a "local variable".
13221     // C++11 [stmt.dcl]p3
13222     //   A program that jumps from a point where a variable with automatic
13223     //   storage duration is not in scope to a point where it is in scope is
13224     //   ill-formed unless the variable has scalar type, class type with a
13225     //   trivial default constructor and a trivial destructor, a cv-qualified
13226     //   version of one of these types, or an array of one of the preceding
13227     //   types and is declared without an initializer.
13228     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13229       if (const RecordType *Record
13230             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13231         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13232         // Mark the function (if we're in one) for further checking even if the
13233         // looser rules of C++11 do not require such checks, so that we can
13234         // diagnose incompatibilities with C++98.
13235         if (!CXXRecord->isPOD())
13236           setFunctionHasBranchProtectedScope();
13237       }
13238     }
13239     // In OpenCL, we can't initialize objects in the __local address space,
13240     // even implicitly, so don't synthesize an implicit initializer.
13241     if (getLangOpts().OpenCL &&
13242         Var->getType().getAddressSpace() == LangAS::opencl_local)
13243       return;
13244     // C++03 [dcl.init]p9:
13245     //   If no initializer is specified for an object, and the
13246     //   object is of (possibly cv-qualified) non-POD class type (or
13247     //   array thereof), the object shall be default-initialized; if
13248     //   the object is of const-qualified type, the underlying class
13249     //   type shall have a user-declared default
13250     //   constructor. Otherwise, if no initializer is specified for
13251     //   a non- static object, the object and its subobjects, if
13252     //   any, have an indeterminate initial value); if the object
13253     //   or any of its subobjects are of const-qualified type, the
13254     //   program is ill-formed.
13255     // C++0x [dcl.init]p11:
13256     //   If no initializer is specified for an object, the object is
13257     //   default-initialized; [...].
13258     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13259     InitializationKind Kind
13260       = InitializationKind::CreateDefault(Var->getLocation());
13261 
13262     InitializationSequence InitSeq(*this, Entity, Kind, None);
13263     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13264 
13265     if (Init.get()) {
13266       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13267       // This is important for template substitution.
13268       Var->setInitStyle(VarDecl::CallInit);
13269     } else if (Init.isInvalid()) {
13270       // If default-init fails, attach a recovery-expr initializer to track
13271       // that initialization was attempted and failed.
13272       auto RecoveryExpr =
13273           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13274       if (RecoveryExpr.get())
13275         Var->setInit(RecoveryExpr.get());
13276     }
13277 
13278     CheckCompleteVariableDeclaration(Var);
13279   }
13280 }
13281 
13282 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13283   // If there is no declaration, there was an error parsing it. Ignore it.
13284   if (!D)
13285     return;
13286 
13287   VarDecl *VD = dyn_cast<VarDecl>(D);
13288   if (!VD) {
13289     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13290     D->setInvalidDecl();
13291     return;
13292   }
13293 
13294   VD->setCXXForRangeDecl(true);
13295 
13296   // for-range-declaration cannot be given a storage class specifier.
13297   int Error = -1;
13298   switch (VD->getStorageClass()) {
13299   case SC_None:
13300     break;
13301   case SC_Extern:
13302     Error = 0;
13303     break;
13304   case SC_Static:
13305     Error = 1;
13306     break;
13307   case SC_PrivateExtern:
13308     Error = 2;
13309     break;
13310   case SC_Auto:
13311     Error = 3;
13312     break;
13313   case SC_Register:
13314     Error = 4;
13315     break;
13316   }
13317 
13318   // for-range-declaration cannot be given a storage class specifier con't.
13319   switch (VD->getTSCSpec()) {
13320   case TSCS_thread_local:
13321     Error = 6;
13322     break;
13323   case TSCS___thread:
13324   case TSCS__Thread_local:
13325   case TSCS_unspecified:
13326     break;
13327   }
13328 
13329   if (Error != -1) {
13330     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13331         << VD << Error;
13332     D->setInvalidDecl();
13333   }
13334 }
13335 
13336 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13337                                             IdentifierInfo *Ident,
13338                                             ParsedAttributes &Attrs) {
13339   // C++1y [stmt.iter]p1:
13340   //   A range-based for statement of the form
13341   //      for ( for-range-identifier : for-range-initializer ) statement
13342   //   is equivalent to
13343   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13344   DeclSpec DS(Attrs.getPool().getFactory());
13345 
13346   const char *PrevSpec;
13347   unsigned DiagID;
13348   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13349                      getPrintingPolicy());
13350 
13351   Declarator D(DS, DeclaratorContext::ForInit);
13352   D.SetIdentifier(Ident, IdentLoc);
13353   D.takeAttributes(Attrs);
13354 
13355   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13356                 IdentLoc);
13357   Decl *Var = ActOnDeclarator(S, D);
13358   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13359   FinalizeDeclaration(Var);
13360   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13361                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13362                                                       : IdentLoc);
13363 }
13364 
13365 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13366   if (var->isInvalidDecl()) return;
13367 
13368   MaybeAddCUDAConstantAttr(var);
13369 
13370   if (getLangOpts().OpenCL) {
13371     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13372     // initialiser
13373     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13374         !var->hasInit()) {
13375       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13376           << 1 /*Init*/;
13377       var->setInvalidDecl();
13378       return;
13379     }
13380   }
13381 
13382   // In Objective-C, don't allow jumps past the implicit initialization of a
13383   // local retaining variable.
13384   if (getLangOpts().ObjC &&
13385       var->hasLocalStorage()) {
13386     switch (var->getType().getObjCLifetime()) {
13387     case Qualifiers::OCL_None:
13388     case Qualifiers::OCL_ExplicitNone:
13389     case Qualifiers::OCL_Autoreleasing:
13390       break;
13391 
13392     case Qualifiers::OCL_Weak:
13393     case Qualifiers::OCL_Strong:
13394       setFunctionHasBranchProtectedScope();
13395       break;
13396     }
13397   }
13398 
13399   if (var->hasLocalStorage() &&
13400       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13401     setFunctionHasBranchProtectedScope();
13402 
13403   // Warn about externally-visible variables being defined without a
13404   // prior declaration.  We only want to do this for global
13405   // declarations, but we also specifically need to avoid doing it for
13406   // class members because the linkage of an anonymous class can
13407   // change if it's later given a typedef name.
13408   if (var->isThisDeclarationADefinition() &&
13409       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13410       var->isExternallyVisible() && var->hasLinkage() &&
13411       !var->isInline() && !var->getDescribedVarTemplate() &&
13412       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13413       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13414       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13415                                   var->getLocation())) {
13416     // Find a previous declaration that's not a definition.
13417     VarDecl *prev = var->getPreviousDecl();
13418     while (prev && prev->isThisDeclarationADefinition())
13419       prev = prev->getPreviousDecl();
13420 
13421     if (!prev) {
13422       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13423       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13424           << /* variable */ 0;
13425     }
13426   }
13427 
13428   // Cache the result of checking for constant initialization.
13429   Optional<bool> CacheHasConstInit;
13430   const Expr *CacheCulprit = nullptr;
13431   auto checkConstInit = [&]() mutable {
13432     if (!CacheHasConstInit)
13433       CacheHasConstInit = var->getInit()->isConstantInitializer(
13434             Context, var->getType()->isReferenceType(), &CacheCulprit);
13435     return *CacheHasConstInit;
13436   };
13437 
13438   if (var->getTLSKind() == VarDecl::TLS_Static) {
13439     if (var->getType().isDestructedType()) {
13440       // GNU C++98 edits for __thread, [basic.start.term]p3:
13441       //   The type of an object with thread storage duration shall not
13442       //   have a non-trivial destructor.
13443       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13444       if (getLangOpts().CPlusPlus11)
13445         Diag(var->getLocation(), diag::note_use_thread_local);
13446     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13447       if (!checkConstInit()) {
13448         // GNU C++98 edits for __thread, [basic.start.init]p4:
13449         //   An object of thread storage duration shall not require dynamic
13450         //   initialization.
13451         // FIXME: Need strict checking here.
13452         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13453           << CacheCulprit->getSourceRange();
13454         if (getLangOpts().CPlusPlus11)
13455           Diag(var->getLocation(), diag::note_use_thread_local);
13456       }
13457     }
13458   }
13459 
13460 
13461   if (!var->getType()->isStructureType() && var->hasInit() &&
13462       isa<InitListExpr>(var->getInit())) {
13463     const auto *ILE = cast<InitListExpr>(var->getInit());
13464     unsigned NumInits = ILE->getNumInits();
13465     if (NumInits > 2)
13466       for (unsigned I = 0; I < NumInits; ++I) {
13467         const auto *Init = ILE->getInit(I);
13468         if (!Init)
13469           break;
13470         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13471         if (!SL)
13472           break;
13473 
13474         unsigned NumConcat = SL->getNumConcatenated();
13475         // Diagnose missing comma in string array initialization.
13476         // Do not warn when all the elements in the initializer are concatenated
13477         // together. Do not warn for macros too.
13478         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13479           bool OnlyOneMissingComma = true;
13480           for (unsigned J = I + 1; J < NumInits; ++J) {
13481             const auto *Init = ILE->getInit(J);
13482             if (!Init)
13483               break;
13484             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13485             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13486               OnlyOneMissingComma = false;
13487               break;
13488             }
13489           }
13490 
13491           if (OnlyOneMissingComma) {
13492             SmallVector<FixItHint, 1> Hints;
13493             for (unsigned i = 0; i < NumConcat - 1; ++i)
13494               Hints.push_back(FixItHint::CreateInsertion(
13495                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13496 
13497             Diag(SL->getStrTokenLoc(1),
13498                  diag::warn_concatenated_literal_array_init)
13499                 << Hints;
13500             Diag(SL->getBeginLoc(),
13501                  diag::note_concatenated_string_literal_silence);
13502           }
13503           // In any case, stop now.
13504           break;
13505         }
13506       }
13507   }
13508 
13509 
13510   QualType type = var->getType();
13511 
13512   if (var->hasAttr<BlocksAttr>())
13513     getCurFunction()->addByrefBlockVar(var);
13514 
13515   Expr *Init = var->getInit();
13516   bool GlobalStorage = var->hasGlobalStorage();
13517   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13518   QualType baseType = Context.getBaseElementType(type);
13519   bool HasConstInit = true;
13520 
13521   // Check whether the initializer is sufficiently constant.
13522   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13523       !Init->isValueDependent() &&
13524       (GlobalStorage || var->isConstexpr() ||
13525        var->mightBeUsableInConstantExpressions(Context))) {
13526     // If this variable might have a constant initializer or might be usable in
13527     // constant expressions, check whether or not it actually is now.  We can't
13528     // do this lazily, because the result might depend on things that change
13529     // later, such as which constexpr functions happen to be defined.
13530     SmallVector<PartialDiagnosticAt, 8> Notes;
13531     if (!getLangOpts().CPlusPlus11) {
13532       // Prior to C++11, in contexts where a constant initializer is required,
13533       // the set of valid constant initializers is described by syntactic rules
13534       // in [expr.const]p2-6.
13535       // FIXME: Stricter checking for these rules would be useful for constinit /
13536       // -Wglobal-constructors.
13537       HasConstInit = checkConstInit();
13538 
13539       // Compute and cache the constant value, and remember that we have a
13540       // constant initializer.
13541       if (HasConstInit) {
13542         (void)var->checkForConstantInitialization(Notes);
13543         Notes.clear();
13544       } else if (CacheCulprit) {
13545         Notes.emplace_back(CacheCulprit->getExprLoc(),
13546                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13547         Notes.back().second << CacheCulprit->getSourceRange();
13548       }
13549     } else {
13550       // Evaluate the initializer to see if it's a constant initializer.
13551       HasConstInit = var->checkForConstantInitialization(Notes);
13552     }
13553 
13554     if (HasConstInit) {
13555       // FIXME: Consider replacing the initializer with a ConstantExpr.
13556     } else if (var->isConstexpr()) {
13557       SourceLocation DiagLoc = var->getLocation();
13558       // If the note doesn't add any useful information other than a source
13559       // location, fold it into the primary diagnostic.
13560       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13561                                    diag::note_invalid_subexpr_in_const_expr) {
13562         DiagLoc = Notes[0].first;
13563         Notes.clear();
13564       }
13565       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13566           << var << Init->getSourceRange();
13567       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13568         Diag(Notes[I].first, Notes[I].second);
13569     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13570       auto *Attr = var->getAttr<ConstInitAttr>();
13571       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13572           << Init->getSourceRange();
13573       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13574           << Attr->getRange() << Attr->isConstinit();
13575       for (auto &it : Notes)
13576         Diag(it.first, it.second);
13577     } else if (IsGlobal &&
13578                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13579                                            var->getLocation())) {
13580       // Warn about globals which don't have a constant initializer.  Don't
13581       // warn about globals with a non-trivial destructor because we already
13582       // warned about them.
13583       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13584       if (!(RD && !RD->hasTrivialDestructor())) {
13585         // checkConstInit() here permits trivial default initialization even in
13586         // C++11 onwards, where such an initializer is not a constant initializer
13587         // but nonetheless doesn't require a global constructor.
13588         if (!checkConstInit())
13589           Diag(var->getLocation(), diag::warn_global_constructor)
13590               << Init->getSourceRange();
13591       }
13592     }
13593   }
13594 
13595   // Apply section attributes and pragmas to global variables.
13596   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13597       !inTemplateInstantiation()) {
13598     PragmaStack<StringLiteral *> *Stack = nullptr;
13599     int SectionFlags = ASTContext::PSF_Read;
13600     if (var->getType().isConstQualified()) {
13601       if (HasConstInit)
13602         Stack = &ConstSegStack;
13603       else {
13604         Stack = &BSSSegStack;
13605         SectionFlags |= ASTContext::PSF_Write;
13606       }
13607     } else if (var->hasInit() && HasConstInit) {
13608       Stack = &DataSegStack;
13609       SectionFlags |= ASTContext::PSF_Write;
13610     } else {
13611       Stack = &BSSSegStack;
13612       SectionFlags |= ASTContext::PSF_Write;
13613     }
13614     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13615       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13616         SectionFlags |= ASTContext::PSF_Implicit;
13617       UnifySection(SA->getName(), SectionFlags, var);
13618     } else if (Stack->CurrentValue) {
13619       SectionFlags |= ASTContext::PSF_Implicit;
13620       auto SectionName = Stack->CurrentValue->getString();
13621       var->addAttr(SectionAttr::CreateImplicit(
13622           Context, SectionName, Stack->CurrentPragmaLocation,
13623           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13624       if (UnifySection(SectionName, SectionFlags, var))
13625         var->dropAttr<SectionAttr>();
13626     }
13627 
13628     // Apply the init_seg attribute if this has an initializer.  If the
13629     // initializer turns out to not be dynamic, we'll end up ignoring this
13630     // attribute.
13631     if (CurInitSeg && var->getInit())
13632       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13633                                                CurInitSegLoc,
13634                                                AttributeCommonInfo::AS_Pragma));
13635   }
13636 
13637   // All the following checks are C++ only.
13638   if (!getLangOpts().CPlusPlus) {
13639     // If this variable must be emitted, add it as an initializer for the
13640     // current module.
13641     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13642       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13643     return;
13644   }
13645 
13646   // Require the destructor.
13647   if (!type->isDependentType())
13648     if (const RecordType *recordType = baseType->getAs<RecordType>())
13649       FinalizeVarWithDestructor(var, recordType);
13650 
13651   // If this variable must be emitted, add it as an initializer for the current
13652   // module.
13653   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13654     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13655 
13656   // Build the bindings if this is a structured binding declaration.
13657   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13658     CheckCompleteDecompositionDeclaration(DD);
13659 }
13660 
13661 /// Check if VD needs to be dllexport/dllimport due to being in a
13662 /// dllexport/import function.
13663 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13664   assert(VD->isStaticLocal());
13665 
13666   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13667 
13668   // Find outermost function when VD is in lambda function.
13669   while (FD && !getDLLAttr(FD) &&
13670          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13671          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13672     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13673   }
13674 
13675   if (!FD)
13676     return;
13677 
13678   // Static locals inherit dll attributes from their function.
13679   if (Attr *A = getDLLAttr(FD)) {
13680     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13681     NewAttr->setInherited(true);
13682     VD->addAttr(NewAttr);
13683   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13684     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13685     NewAttr->setInherited(true);
13686     VD->addAttr(NewAttr);
13687 
13688     // Export this function to enforce exporting this static variable even
13689     // if it is not used in this compilation unit.
13690     if (!FD->hasAttr<DLLExportAttr>())
13691       FD->addAttr(NewAttr);
13692 
13693   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13694     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13695     NewAttr->setInherited(true);
13696     VD->addAttr(NewAttr);
13697   }
13698 }
13699 
13700 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13701 /// any semantic actions necessary after any initializer has been attached.
13702 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13703   // Note that we are no longer parsing the initializer for this declaration.
13704   ParsingInitForAutoVars.erase(ThisDecl);
13705 
13706   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13707   if (!VD)
13708     return;
13709 
13710   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13711   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13712       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13713     if (PragmaClangBSSSection.Valid)
13714       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13715           Context, PragmaClangBSSSection.SectionName,
13716           PragmaClangBSSSection.PragmaLocation,
13717           AttributeCommonInfo::AS_Pragma));
13718     if (PragmaClangDataSection.Valid)
13719       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13720           Context, PragmaClangDataSection.SectionName,
13721           PragmaClangDataSection.PragmaLocation,
13722           AttributeCommonInfo::AS_Pragma));
13723     if (PragmaClangRodataSection.Valid)
13724       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13725           Context, PragmaClangRodataSection.SectionName,
13726           PragmaClangRodataSection.PragmaLocation,
13727           AttributeCommonInfo::AS_Pragma));
13728     if (PragmaClangRelroSection.Valid)
13729       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13730           Context, PragmaClangRelroSection.SectionName,
13731           PragmaClangRelroSection.PragmaLocation,
13732           AttributeCommonInfo::AS_Pragma));
13733   }
13734 
13735   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13736     for (auto *BD : DD->bindings()) {
13737       FinalizeDeclaration(BD);
13738     }
13739   }
13740 
13741   checkAttributesAfterMerging(*this, *VD);
13742 
13743   // Perform TLS alignment check here after attributes attached to the variable
13744   // which may affect the alignment have been processed. Only perform the check
13745   // if the target has a maximum TLS alignment (zero means no constraints).
13746   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13747     // Protect the check so that it's not performed on dependent types and
13748     // dependent alignments (we can't determine the alignment in that case).
13749     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13750       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13751       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13752         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13753           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13754           << (unsigned)MaxAlignChars.getQuantity();
13755       }
13756     }
13757   }
13758 
13759   if (VD->isStaticLocal())
13760     CheckStaticLocalForDllExport(VD);
13761 
13762   // Perform check for initializers of device-side global variables.
13763   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13764   // 7.5). We must also apply the same checks to all __shared__
13765   // variables whether they are local or not. CUDA also allows
13766   // constant initializers for __constant__ and __device__ variables.
13767   if (getLangOpts().CUDA)
13768     checkAllowedCUDAInitializer(VD);
13769 
13770   // Grab the dllimport or dllexport attribute off of the VarDecl.
13771   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13772 
13773   // Imported static data members cannot be defined out-of-line.
13774   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13775     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13776         VD->isThisDeclarationADefinition()) {
13777       // We allow definitions of dllimport class template static data members
13778       // with a warning.
13779       CXXRecordDecl *Context =
13780         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13781       bool IsClassTemplateMember =
13782           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13783           Context->getDescribedClassTemplate();
13784 
13785       Diag(VD->getLocation(),
13786            IsClassTemplateMember
13787                ? diag::warn_attribute_dllimport_static_field_definition
13788                : diag::err_attribute_dllimport_static_field_definition);
13789       Diag(IA->getLocation(), diag::note_attribute);
13790       if (!IsClassTemplateMember)
13791         VD->setInvalidDecl();
13792     }
13793   }
13794 
13795   // dllimport/dllexport variables cannot be thread local, their TLS index
13796   // isn't exported with the variable.
13797   if (DLLAttr && VD->getTLSKind()) {
13798     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13799     if (F && getDLLAttr(F)) {
13800       assert(VD->isStaticLocal());
13801       // But if this is a static local in a dlimport/dllexport function, the
13802       // function will never be inlined, which means the var would never be
13803       // imported, so having it marked import/export is safe.
13804     } else {
13805       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13806                                                                     << DLLAttr;
13807       VD->setInvalidDecl();
13808     }
13809   }
13810 
13811   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13812     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13813       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13814           << Attr;
13815       VD->dropAttr<UsedAttr>();
13816     }
13817   }
13818   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13819     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13820       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13821           << Attr;
13822       VD->dropAttr<RetainAttr>();
13823     }
13824   }
13825 
13826   const DeclContext *DC = VD->getDeclContext();
13827   // If there's a #pragma GCC visibility in scope, and this isn't a class
13828   // member, set the visibility of this variable.
13829   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13830     AddPushedVisibilityAttribute(VD);
13831 
13832   // FIXME: Warn on unused var template partial specializations.
13833   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13834     MarkUnusedFileScopedDecl(VD);
13835 
13836   // Now we have parsed the initializer and can update the table of magic
13837   // tag values.
13838   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13839       !VD->getType()->isIntegralOrEnumerationType())
13840     return;
13841 
13842   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13843     const Expr *MagicValueExpr = VD->getInit();
13844     if (!MagicValueExpr) {
13845       continue;
13846     }
13847     Optional<llvm::APSInt> MagicValueInt;
13848     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13849       Diag(I->getRange().getBegin(),
13850            diag::err_type_tag_for_datatype_not_ice)
13851         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13852       continue;
13853     }
13854     if (MagicValueInt->getActiveBits() > 64) {
13855       Diag(I->getRange().getBegin(),
13856            diag::err_type_tag_for_datatype_too_large)
13857         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13858       continue;
13859     }
13860     uint64_t MagicValue = MagicValueInt->getZExtValue();
13861     RegisterTypeTagForDatatype(I->getArgumentKind(),
13862                                MagicValue,
13863                                I->getMatchingCType(),
13864                                I->getLayoutCompatible(),
13865                                I->getMustBeNull());
13866   }
13867 }
13868 
13869 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13870   auto *VD = dyn_cast<VarDecl>(DD);
13871   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13872 }
13873 
13874 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13875                                                    ArrayRef<Decl *> Group) {
13876   SmallVector<Decl*, 8> Decls;
13877 
13878   if (DS.isTypeSpecOwned())
13879     Decls.push_back(DS.getRepAsDecl());
13880 
13881   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13882   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13883   bool DiagnosedMultipleDecomps = false;
13884   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13885   bool DiagnosedNonDeducedAuto = false;
13886 
13887   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13888     if (Decl *D = Group[i]) {
13889       // For declarators, there are some additional syntactic-ish checks we need
13890       // to perform.
13891       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13892         if (!FirstDeclaratorInGroup)
13893           FirstDeclaratorInGroup = DD;
13894         if (!FirstDecompDeclaratorInGroup)
13895           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13896         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13897             !hasDeducedAuto(DD))
13898           FirstNonDeducedAutoInGroup = DD;
13899 
13900         if (FirstDeclaratorInGroup != DD) {
13901           // A decomposition declaration cannot be combined with any other
13902           // declaration in the same group.
13903           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13904             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13905                  diag::err_decomp_decl_not_alone)
13906                 << FirstDeclaratorInGroup->getSourceRange()
13907                 << DD->getSourceRange();
13908             DiagnosedMultipleDecomps = true;
13909           }
13910 
13911           // A declarator that uses 'auto' in any way other than to declare a
13912           // variable with a deduced type cannot be combined with any other
13913           // declarator in the same group.
13914           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13915             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13916                  diag::err_auto_non_deduced_not_alone)
13917                 << FirstNonDeducedAutoInGroup->getType()
13918                        ->hasAutoForTrailingReturnType()
13919                 << FirstDeclaratorInGroup->getSourceRange()
13920                 << DD->getSourceRange();
13921             DiagnosedNonDeducedAuto = true;
13922           }
13923         }
13924       }
13925 
13926       Decls.push_back(D);
13927     }
13928   }
13929 
13930   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13931     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13932       handleTagNumbering(Tag, S);
13933       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13934           getLangOpts().CPlusPlus)
13935         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13936     }
13937   }
13938 
13939   return BuildDeclaratorGroup(Decls);
13940 }
13941 
13942 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13943 /// group, performing any necessary semantic checking.
13944 Sema::DeclGroupPtrTy
13945 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13946   // C++14 [dcl.spec.auto]p7: (DR1347)
13947   //   If the type that replaces the placeholder type is not the same in each
13948   //   deduction, the program is ill-formed.
13949   if (Group.size() > 1) {
13950     QualType Deduced;
13951     VarDecl *DeducedDecl = nullptr;
13952     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13953       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13954       if (!D || D->isInvalidDecl())
13955         break;
13956       DeducedType *DT = D->getType()->getContainedDeducedType();
13957       if (!DT || DT->getDeducedType().isNull())
13958         continue;
13959       if (Deduced.isNull()) {
13960         Deduced = DT->getDeducedType();
13961         DeducedDecl = D;
13962       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13963         auto *AT = dyn_cast<AutoType>(DT);
13964         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13965                         diag::err_auto_different_deductions)
13966                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13967                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13968                    << D->getDeclName();
13969         if (DeducedDecl->hasInit())
13970           Dia << DeducedDecl->getInit()->getSourceRange();
13971         if (D->getInit())
13972           Dia << D->getInit()->getSourceRange();
13973         D->setInvalidDecl();
13974         break;
13975       }
13976     }
13977   }
13978 
13979   ActOnDocumentableDecls(Group);
13980 
13981   return DeclGroupPtrTy::make(
13982       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13983 }
13984 
13985 void Sema::ActOnDocumentableDecl(Decl *D) {
13986   ActOnDocumentableDecls(D);
13987 }
13988 
13989 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13990   // Don't parse the comment if Doxygen diagnostics are ignored.
13991   if (Group.empty() || !Group[0])
13992     return;
13993 
13994   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13995                       Group[0]->getLocation()) &&
13996       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13997                       Group[0]->getLocation()))
13998     return;
13999 
14000   if (Group.size() >= 2) {
14001     // This is a decl group.  Normally it will contain only declarations
14002     // produced from declarator list.  But in case we have any definitions or
14003     // additional declaration references:
14004     //   'typedef struct S {} S;'
14005     //   'typedef struct S *S;'
14006     //   'struct S *pS;'
14007     // FinalizeDeclaratorGroup adds these as separate declarations.
14008     Decl *MaybeTagDecl = Group[0];
14009     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14010       Group = Group.slice(1);
14011     }
14012   }
14013 
14014   // FIMXE: We assume every Decl in the group is in the same file.
14015   // This is false when preprocessor constructs the group from decls in
14016   // different files (e. g. macros or #include).
14017   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14018 }
14019 
14020 /// Common checks for a parameter-declaration that should apply to both function
14021 /// parameters and non-type template parameters.
14022 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14023   // Check that there are no default arguments inside the type of this
14024   // parameter.
14025   if (getLangOpts().CPlusPlus)
14026     CheckExtraCXXDefaultArguments(D);
14027 
14028   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14029   if (D.getCXXScopeSpec().isSet()) {
14030     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14031       << D.getCXXScopeSpec().getRange();
14032   }
14033 
14034   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14035   // simple identifier except [...irrelevant cases...].
14036   switch (D.getName().getKind()) {
14037   case UnqualifiedIdKind::IK_Identifier:
14038     break;
14039 
14040   case UnqualifiedIdKind::IK_OperatorFunctionId:
14041   case UnqualifiedIdKind::IK_ConversionFunctionId:
14042   case UnqualifiedIdKind::IK_LiteralOperatorId:
14043   case UnqualifiedIdKind::IK_ConstructorName:
14044   case UnqualifiedIdKind::IK_DestructorName:
14045   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14046   case UnqualifiedIdKind::IK_DeductionGuideName:
14047     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14048       << GetNameForDeclarator(D).getName();
14049     break;
14050 
14051   case UnqualifiedIdKind::IK_TemplateId:
14052   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14053     // GetNameForDeclarator would not produce a useful name in this case.
14054     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14055     break;
14056   }
14057 }
14058 
14059 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14060 /// to introduce parameters into function prototype scope.
14061 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14062   const DeclSpec &DS = D.getDeclSpec();
14063 
14064   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14065 
14066   // C++03 [dcl.stc]p2 also permits 'auto'.
14067   StorageClass SC = SC_None;
14068   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14069     SC = SC_Register;
14070     // In C++11, the 'register' storage class specifier is deprecated.
14071     // In C++17, it is not allowed, but we tolerate it as an extension.
14072     if (getLangOpts().CPlusPlus11) {
14073       Diag(DS.getStorageClassSpecLoc(),
14074            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14075                                      : diag::warn_deprecated_register)
14076         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14077     }
14078   } else if (getLangOpts().CPlusPlus &&
14079              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14080     SC = SC_Auto;
14081   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14082     Diag(DS.getStorageClassSpecLoc(),
14083          diag::err_invalid_storage_class_in_func_decl);
14084     D.getMutableDeclSpec().ClearStorageClassSpecs();
14085   }
14086 
14087   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14088     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14089       << DeclSpec::getSpecifierName(TSCS);
14090   if (DS.isInlineSpecified())
14091     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14092         << getLangOpts().CPlusPlus17;
14093   if (DS.hasConstexprSpecifier())
14094     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14095         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14096 
14097   DiagnoseFunctionSpecifiers(DS);
14098 
14099   CheckFunctionOrTemplateParamDeclarator(S, D);
14100 
14101   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14102   QualType parmDeclType = TInfo->getType();
14103 
14104   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14105   IdentifierInfo *II = D.getIdentifier();
14106   if (II) {
14107     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14108                    ForVisibleRedeclaration);
14109     LookupName(R, S);
14110     if (R.isSingleResult()) {
14111       NamedDecl *PrevDecl = R.getFoundDecl();
14112       if (PrevDecl->isTemplateParameter()) {
14113         // Maybe we will complain about the shadowed template parameter.
14114         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14115         // Just pretend that we didn't see the previous declaration.
14116         PrevDecl = nullptr;
14117       } else if (S->isDeclScope(PrevDecl)) {
14118         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14119         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14120 
14121         // Recover by removing the name
14122         II = nullptr;
14123         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14124         D.setInvalidType(true);
14125       }
14126     }
14127   }
14128 
14129   // Temporarily put parameter variables in the translation unit, not
14130   // the enclosing context.  This prevents them from accidentally
14131   // looking like class members in C++.
14132   ParmVarDecl *New =
14133       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14134                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14135 
14136   if (D.isInvalidType())
14137     New->setInvalidDecl();
14138 
14139   assert(S->isFunctionPrototypeScope());
14140   assert(S->getFunctionPrototypeDepth() >= 1);
14141   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14142                     S->getNextFunctionPrototypeIndex());
14143 
14144   // Add the parameter declaration into this scope.
14145   S->AddDecl(New);
14146   if (II)
14147     IdResolver.AddDecl(New);
14148 
14149   ProcessDeclAttributes(S, New, D);
14150 
14151   if (D.getDeclSpec().isModulePrivateSpecified())
14152     Diag(New->getLocation(), diag::err_module_private_local)
14153         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14154         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14155 
14156   if (New->hasAttr<BlocksAttr>()) {
14157     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14158   }
14159 
14160   if (getLangOpts().OpenCL)
14161     deduceOpenCLAddressSpace(New);
14162 
14163   return New;
14164 }
14165 
14166 /// Synthesizes a variable for a parameter arising from a
14167 /// typedef.
14168 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14169                                               SourceLocation Loc,
14170                                               QualType T) {
14171   /* FIXME: setting StartLoc == Loc.
14172      Would it be worth to modify callers so as to provide proper source
14173      location for the unnamed parameters, embedding the parameter's type? */
14174   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14175                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14176                                            SC_None, nullptr);
14177   Param->setImplicit();
14178   return Param;
14179 }
14180 
14181 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14182   // Don't diagnose unused-parameter errors in template instantiations; we
14183   // will already have done so in the template itself.
14184   if (inTemplateInstantiation())
14185     return;
14186 
14187   for (const ParmVarDecl *Parameter : Parameters) {
14188     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14189         !Parameter->hasAttr<UnusedAttr>()) {
14190       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14191         << Parameter->getDeclName();
14192     }
14193   }
14194 }
14195 
14196 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14197     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14198   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14199     return;
14200 
14201   // Warn if the return value is pass-by-value and larger than the specified
14202   // threshold.
14203   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14204     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14205     if (Size > LangOpts.NumLargeByValueCopy)
14206       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14207   }
14208 
14209   // Warn if any parameter is pass-by-value and larger than the specified
14210   // threshold.
14211   for (const ParmVarDecl *Parameter : Parameters) {
14212     QualType T = Parameter->getType();
14213     if (T->isDependentType() || !T.isPODType(Context))
14214       continue;
14215     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14216     if (Size > LangOpts.NumLargeByValueCopy)
14217       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14218           << Parameter << Size;
14219   }
14220 }
14221 
14222 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14223                                   SourceLocation NameLoc, IdentifierInfo *Name,
14224                                   QualType T, TypeSourceInfo *TSInfo,
14225                                   StorageClass SC) {
14226   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14227   if (getLangOpts().ObjCAutoRefCount &&
14228       T.getObjCLifetime() == Qualifiers::OCL_None &&
14229       T->isObjCLifetimeType()) {
14230 
14231     Qualifiers::ObjCLifetime lifetime;
14232 
14233     // Special cases for arrays:
14234     //   - if it's const, use __unsafe_unretained
14235     //   - otherwise, it's an error
14236     if (T->isArrayType()) {
14237       if (!T.isConstQualified()) {
14238         if (DelayedDiagnostics.shouldDelayDiagnostics())
14239           DelayedDiagnostics.add(
14240               sema::DelayedDiagnostic::makeForbiddenType(
14241               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14242         else
14243           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14244               << TSInfo->getTypeLoc().getSourceRange();
14245       }
14246       lifetime = Qualifiers::OCL_ExplicitNone;
14247     } else {
14248       lifetime = T->getObjCARCImplicitLifetime();
14249     }
14250     T = Context.getLifetimeQualifiedType(T, lifetime);
14251   }
14252 
14253   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14254                                          Context.getAdjustedParameterType(T),
14255                                          TSInfo, SC, nullptr);
14256 
14257   // Make a note if we created a new pack in the scope of a lambda, so that
14258   // we know that references to that pack must also be expanded within the
14259   // lambda scope.
14260   if (New->isParameterPack())
14261     if (auto *LSI = getEnclosingLambda())
14262       LSI->LocalPacks.push_back(New);
14263 
14264   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14265       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14266     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14267                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14268 
14269   // Parameters can not be abstract class types.
14270   // For record types, this is done by the AbstractClassUsageDiagnoser once
14271   // the class has been completely parsed.
14272   if (!CurContext->isRecord() &&
14273       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14274                              AbstractParamType))
14275     New->setInvalidDecl();
14276 
14277   // Parameter declarators cannot be interface types. All ObjC objects are
14278   // passed by reference.
14279   if (T->isObjCObjectType()) {
14280     SourceLocation TypeEndLoc =
14281         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14282     Diag(NameLoc,
14283          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14284       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14285     T = Context.getObjCObjectPointerType(T);
14286     New->setType(T);
14287   }
14288 
14289   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14290   // duration shall not be qualified by an address-space qualifier."
14291   // Since all parameters have automatic store duration, they can not have
14292   // an address space.
14293   if (T.getAddressSpace() != LangAS::Default &&
14294       // OpenCL allows function arguments declared to be an array of a type
14295       // to be qualified with an address space.
14296       !(getLangOpts().OpenCL &&
14297         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14298     Diag(NameLoc, diag::err_arg_with_address_space);
14299     New->setInvalidDecl();
14300   }
14301 
14302   // PPC MMA non-pointer types are not allowed as function argument types.
14303   if (Context.getTargetInfo().getTriple().isPPC64() &&
14304       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14305     New->setInvalidDecl();
14306   }
14307 
14308   return New;
14309 }
14310 
14311 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14312                                            SourceLocation LocAfterDecls) {
14313   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14314 
14315   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14316   // for a K&R function.
14317   if (!FTI.hasPrototype) {
14318     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14319       --i;
14320       if (FTI.Params[i].Param == nullptr) {
14321         SmallString<256> Code;
14322         llvm::raw_svector_ostream(Code)
14323             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14324         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14325             << FTI.Params[i].Ident
14326             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14327 
14328         // Implicitly declare the argument as type 'int' for lack of a better
14329         // type.
14330         AttributeFactory attrs;
14331         DeclSpec DS(attrs);
14332         const char* PrevSpec; // unused
14333         unsigned DiagID; // unused
14334         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14335                            DiagID, Context.getPrintingPolicy());
14336         // Use the identifier location for the type source range.
14337         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14338         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14339         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14340         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14341         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14342       }
14343     }
14344   }
14345 }
14346 
14347 Decl *
14348 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14349                               MultiTemplateParamsArg TemplateParameterLists,
14350                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14351   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14352   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14353   Scope *ParentScope = FnBodyScope->getParent();
14354 
14355   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14356   // we define a non-templated function definition, we will create a declaration
14357   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14358   // The base function declaration will have the equivalent of an `omp declare
14359   // variant` annotation which specifies the mangled definition as a
14360   // specialization function under the OpenMP context defined as part of the
14361   // `omp begin declare variant`.
14362   SmallVector<FunctionDecl *, 4> Bases;
14363   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14364     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14365         ParentScope, D, TemplateParameterLists, Bases);
14366 
14367   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14368   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14369   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14370 
14371   if (!Bases.empty())
14372     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14373 
14374   return Dcl;
14375 }
14376 
14377 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14378   Consumer.HandleInlineFunctionDefinition(D);
14379 }
14380 
14381 static bool
14382 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14383                                 const FunctionDecl *&PossiblePrototype) {
14384   // Don't warn about invalid declarations.
14385   if (FD->isInvalidDecl())
14386     return false;
14387 
14388   // Or declarations that aren't global.
14389   if (!FD->isGlobal())
14390     return false;
14391 
14392   // Don't warn about C++ member functions.
14393   if (isa<CXXMethodDecl>(FD))
14394     return false;
14395 
14396   // Don't warn about 'main'.
14397   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14398     if (IdentifierInfo *II = FD->getIdentifier())
14399       if (II->isStr("main") || II->isStr("efi_main"))
14400         return false;
14401 
14402   // Don't warn about inline functions.
14403   if (FD->isInlined())
14404     return false;
14405 
14406   // Don't warn about function templates.
14407   if (FD->getDescribedFunctionTemplate())
14408     return false;
14409 
14410   // Don't warn about function template specializations.
14411   if (FD->isFunctionTemplateSpecialization())
14412     return false;
14413 
14414   // Don't warn for OpenCL kernels.
14415   if (FD->hasAttr<OpenCLKernelAttr>())
14416     return false;
14417 
14418   // Don't warn on explicitly deleted functions.
14419   if (FD->isDeleted())
14420     return false;
14421 
14422   // Don't warn on implicitly local functions (such as having local-typed
14423   // parameters).
14424   if (!FD->isExternallyVisible())
14425     return false;
14426 
14427   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14428        Prev; Prev = Prev->getPreviousDecl()) {
14429     // Ignore any declarations that occur in function or method
14430     // scope, because they aren't visible from the header.
14431     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14432       continue;
14433 
14434     PossiblePrototype = Prev;
14435     return Prev->getType()->isFunctionNoProtoType();
14436   }
14437 
14438   return true;
14439 }
14440 
14441 void
14442 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14443                                    const FunctionDecl *EffectiveDefinition,
14444                                    SkipBodyInfo *SkipBody) {
14445   const FunctionDecl *Definition = EffectiveDefinition;
14446   if (!Definition &&
14447       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14448     return;
14449 
14450   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14451     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14452       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14453         // A merged copy of the same function, instantiated as a member of
14454         // the same class, is OK.
14455         if (declaresSameEntity(OrigFD, OrigDef) &&
14456             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14457                                cast<Decl>(FD->getLexicalDeclContext())))
14458           return;
14459       }
14460     }
14461   }
14462 
14463   if (canRedefineFunction(Definition, getLangOpts()))
14464     return;
14465 
14466   // Don't emit an error when this is redefinition of a typo-corrected
14467   // definition.
14468   if (TypoCorrectedFunctionDefinitions.count(Definition))
14469     return;
14470 
14471   // If we don't have a visible definition of the function, and it's inline or
14472   // a template, skip the new definition.
14473   if (SkipBody && !hasVisibleDefinition(Definition) &&
14474       (Definition->getFormalLinkage() == InternalLinkage ||
14475        Definition->isInlined() ||
14476        Definition->getDescribedFunctionTemplate() ||
14477        Definition->getNumTemplateParameterLists())) {
14478     SkipBody->ShouldSkip = true;
14479     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14480     if (auto *TD = Definition->getDescribedFunctionTemplate())
14481       makeMergedDefinitionVisible(TD);
14482     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14483     return;
14484   }
14485 
14486   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14487       Definition->getStorageClass() == SC_Extern)
14488     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14489         << FD << getLangOpts().CPlusPlus;
14490   else
14491     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14492 
14493   Diag(Definition->getLocation(), diag::note_previous_definition);
14494   FD->setInvalidDecl();
14495 }
14496 
14497 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14498                                    Sema &S) {
14499   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14500 
14501   LambdaScopeInfo *LSI = S.PushLambdaScope();
14502   LSI->CallOperator = CallOperator;
14503   LSI->Lambda = LambdaClass;
14504   LSI->ReturnType = CallOperator->getReturnType();
14505   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14506 
14507   if (LCD == LCD_None)
14508     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14509   else if (LCD == LCD_ByCopy)
14510     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14511   else if (LCD == LCD_ByRef)
14512     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14513   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14514 
14515   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14516   LSI->Mutable = !CallOperator->isConst();
14517 
14518   // Add the captures to the LSI so they can be noted as already
14519   // captured within tryCaptureVar.
14520   auto I = LambdaClass->field_begin();
14521   for (const auto &C : LambdaClass->captures()) {
14522     if (C.capturesVariable()) {
14523       VarDecl *VD = C.getCapturedVar();
14524       if (VD->isInitCapture())
14525         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14526       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14527       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14528           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14529           /*EllipsisLoc*/C.isPackExpansion()
14530                          ? C.getEllipsisLoc() : SourceLocation(),
14531           I->getType(), /*Invalid*/false);
14532 
14533     } else if (C.capturesThis()) {
14534       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14535                           C.getCaptureKind() == LCK_StarThis);
14536     } else {
14537       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14538                              I->getType());
14539     }
14540     ++I;
14541   }
14542 }
14543 
14544 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14545                                     SkipBodyInfo *SkipBody,
14546                                     FnBodyKind BodyKind) {
14547   if (!D) {
14548     // Parsing the function declaration failed in some way. Push on a fake scope
14549     // anyway so we can try to parse the function body.
14550     PushFunctionScope();
14551     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14552     return D;
14553   }
14554 
14555   FunctionDecl *FD = nullptr;
14556 
14557   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14558     FD = FunTmpl->getTemplatedDecl();
14559   else
14560     FD = cast<FunctionDecl>(D);
14561 
14562   // Do not push if it is a lambda because one is already pushed when building
14563   // the lambda in ActOnStartOfLambdaDefinition().
14564   if (!isLambdaCallOperator(FD))
14565     PushExpressionEvaluationContext(
14566         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14567                           : ExprEvalContexts.back().Context);
14568 
14569   // Check for defining attributes before the check for redefinition.
14570   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14571     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14572     FD->dropAttr<AliasAttr>();
14573     FD->setInvalidDecl();
14574   }
14575   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14576     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14577     FD->dropAttr<IFuncAttr>();
14578     FD->setInvalidDecl();
14579   }
14580 
14581   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14582     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14583         Ctor->isDefaultConstructor() &&
14584         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14585       // If this is an MS ABI dllexport default constructor, instantiate any
14586       // default arguments.
14587       InstantiateDefaultCtorDefaultArgs(Ctor);
14588     }
14589   }
14590 
14591   // See if this is a redefinition. If 'will have body' (or similar) is already
14592   // set, then these checks were already performed when it was set.
14593   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14594       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14595     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14596 
14597     // If we're skipping the body, we're done. Don't enter the scope.
14598     if (SkipBody && SkipBody->ShouldSkip)
14599       return D;
14600   }
14601 
14602   // Mark this function as "will have a body eventually".  This lets users to
14603   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14604   // this function.
14605   FD->setWillHaveBody();
14606 
14607   // If we are instantiating a generic lambda call operator, push
14608   // a LambdaScopeInfo onto the function stack.  But use the information
14609   // that's already been calculated (ActOnLambdaExpr) to prime the current
14610   // LambdaScopeInfo.
14611   // When the template operator is being specialized, the LambdaScopeInfo,
14612   // has to be properly restored so that tryCaptureVariable doesn't try
14613   // and capture any new variables. In addition when calculating potential
14614   // captures during transformation of nested lambdas, it is necessary to
14615   // have the LSI properly restored.
14616   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14617     assert(inTemplateInstantiation() &&
14618            "There should be an active template instantiation on the stack "
14619            "when instantiating a generic lambda!");
14620     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14621   } else {
14622     // Enter a new function scope
14623     PushFunctionScope();
14624   }
14625 
14626   // Builtin functions cannot be defined.
14627   if (unsigned BuiltinID = FD->getBuiltinID()) {
14628     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14629         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14630       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14631       FD->setInvalidDecl();
14632     }
14633   }
14634 
14635   // The return type of a function definition must be complete (C99 6.9.1p3),
14636   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14637   QualType ResultType = FD->getReturnType();
14638   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14639       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14640       RequireCompleteType(FD->getLocation(), ResultType,
14641                           diag::err_func_def_incomplete_result))
14642     FD->setInvalidDecl();
14643 
14644   if (FnBodyScope)
14645     PushDeclContext(FnBodyScope, FD);
14646 
14647   // Check the validity of our function parameters
14648   if (BodyKind != FnBodyKind::Delete)
14649     CheckParmsForFunctionDef(FD->parameters(),
14650                              /*CheckParameterNames=*/true);
14651 
14652   // Add non-parameter declarations already in the function to the current
14653   // scope.
14654   if (FnBodyScope) {
14655     for (Decl *NPD : FD->decls()) {
14656       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14657       if (!NonParmDecl)
14658         continue;
14659       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14660              "parameters should not be in newly created FD yet");
14661 
14662       // If the decl has a name, make it accessible in the current scope.
14663       if (NonParmDecl->getDeclName())
14664         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14665 
14666       // Similarly, dive into enums and fish their constants out, making them
14667       // accessible in this scope.
14668       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14669         for (auto *EI : ED->enumerators())
14670           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14671       }
14672     }
14673   }
14674 
14675   // Introduce our parameters into the function scope
14676   for (auto Param : FD->parameters()) {
14677     Param->setOwningFunction(FD);
14678 
14679     // If this has an identifier, add it to the scope stack.
14680     if (Param->getIdentifier() && FnBodyScope) {
14681       CheckShadow(FnBodyScope, Param);
14682 
14683       PushOnScopeChains(Param, FnBodyScope);
14684     }
14685   }
14686 
14687   // Ensure that the function's exception specification is instantiated.
14688   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14689     ResolveExceptionSpec(D->getLocation(), FPT);
14690 
14691   // dllimport cannot be applied to non-inline function definitions.
14692   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14693       !FD->isTemplateInstantiation()) {
14694     assert(!FD->hasAttr<DLLExportAttr>());
14695     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14696     FD->setInvalidDecl();
14697     return D;
14698   }
14699   // We want to attach documentation to original Decl (which might be
14700   // a function template).
14701   ActOnDocumentableDecl(D);
14702   if (getCurLexicalContext()->isObjCContainer() &&
14703       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14704       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14705     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14706 
14707   return D;
14708 }
14709 
14710 /// Given the set of return statements within a function body,
14711 /// compute the variables that are subject to the named return value
14712 /// optimization.
14713 ///
14714 /// Each of the variables that is subject to the named return value
14715 /// optimization will be marked as NRVO variables in the AST, and any
14716 /// return statement that has a marked NRVO variable as its NRVO candidate can
14717 /// use the named return value optimization.
14718 ///
14719 /// This function applies a very simplistic algorithm for NRVO: if every return
14720 /// statement in the scope of a variable has the same NRVO candidate, that
14721 /// candidate is an NRVO variable.
14722 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14723   ReturnStmt **Returns = Scope->Returns.data();
14724 
14725   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14726     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14727       if (!NRVOCandidate->isNRVOVariable())
14728         Returns[I]->setNRVOCandidate(nullptr);
14729     }
14730   }
14731 }
14732 
14733 bool Sema::canDelayFunctionBody(const Declarator &D) {
14734   // We can't delay parsing the body of a constexpr function template (yet).
14735   if (D.getDeclSpec().hasConstexprSpecifier())
14736     return false;
14737 
14738   // We can't delay parsing the body of a function template with a deduced
14739   // return type (yet).
14740   if (D.getDeclSpec().hasAutoTypeSpec()) {
14741     // If the placeholder introduces a non-deduced trailing return type,
14742     // we can still delay parsing it.
14743     if (D.getNumTypeObjects()) {
14744       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14745       if (Outer.Kind == DeclaratorChunk::Function &&
14746           Outer.Fun.hasTrailingReturnType()) {
14747         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14748         return Ty.isNull() || !Ty->isUndeducedType();
14749       }
14750     }
14751     return false;
14752   }
14753 
14754   return true;
14755 }
14756 
14757 bool Sema::canSkipFunctionBody(Decl *D) {
14758   // We cannot skip the body of a function (or function template) which is
14759   // constexpr, since we may need to evaluate its body in order to parse the
14760   // rest of the file.
14761   // We cannot skip the body of a function with an undeduced return type,
14762   // because any callers of that function need to know the type.
14763   if (const FunctionDecl *FD = D->getAsFunction()) {
14764     if (FD->isConstexpr())
14765       return false;
14766     // We can't simply call Type::isUndeducedType here, because inside template
14767     // auto can be deduced to a dependent type, which is not considered
14768     // "undeduced".
14769     if (FD->getReturnType()->getContainedDeducedType())
14770       return false;
14771   }
14772   return Consumer.shouldSkipFunctionBody(D);
14773 }
14774 
14775 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14776   if (!Decl)
14777     return nullptr;
14778   if (FunctionDecl *FD = Decl->getAsFunction())
14779     FD->setHasSkippedBody();
14780   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14781     MD->setHasSkippedBody();
14782   return Decl;
14783 }
14784 
14785 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14786   return ActOnFinishFunctionBody(D, BodyArg, false);
14787 }
14788 
14789 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14790 /// body.
14791 class ExitFunctionBodyRAII {
14792 public:
14793   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14794   ~ExitFunctionBodyRAII() {
14795     if (!IsLambda)
14796       S.PopExpressionEvaluationContext();
14797   }
14798 
14799 private:
14800   Sema &S;
14801   bool IsLambda = false;
14802 };
14803 
14804 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14805   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14806 
14807   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14808     if (EscapeInfo.count(BD))
14809       return EscapeInfo[BD];
14810 
14811     bool R = false;
14812     const BlockDecl *CurBD = BD;
14813 
14814     do {
14815       R = !CurBD->doesNotEscape();
14816       if (R)
14817         break;
14818       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14819     } while (CurBD);
14820 
14821     return EscapeInfo[BD] = R;
14822   };
14823 
14824   // If the location where 'self' is implicitly retained is inside a escaping
14825   // block, emit a diagnostic.
14826   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14827        S.ImplicitlyRetainedSelfLocs)
14828     if (IsOrNestedInEscapingBlock(P.second))
14829       S.Diag(P.first, diag::warn_implicitly_retains_self)
14830           << FixItHint::CreateInsertion(P.first, "self->");
14831 }
14832 
14833 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14834                                     bool IsInstantiation) {
14835   FunctionScopeInfo *FSI = getCurFunction();
14836   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14837 
14838   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14839     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14840 
14841   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14842   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14843 
14844   if (getLangOpts().Coroutines && FSI->isCoroutine())
14845     CheckCompletedCoroutineBody(FD, Body);
14846 
14847   {
14848     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14849     // one is already popped when finishing the lambda in BuildLambdaExpr().
14850     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14851     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14852 
14853     if (FD) {
14854       FD->setBody(Body);
14855       FD->setWillHaveBody(false);
14856 
14857       if (getLangOpts().CPlusPlus14) {
14858         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14859             FD->getReturnType()->isUndeducedType()) {
14860           // For a function with a deduced result type to return void,
14861           // the result type as written must be 'auto' or 'decltype(auto)',
14862           // possibly cv-qualified or constrained, but not ref-qualified.
14863           if (!FD->getReturnType()->getAs<AutoType>()) {
14864             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14865                 << FD->getReturnType();
14866             FD->setInvalidDecl();
14867           } else {
14868             // Falling off the end of the function is the same as 'return;'.
14869             Expr *Dummy = nullptr;
14870             if (DeduceFunctionTypeFromReturnExpr(
14871                     FD, dcl->getLocation(), Dummy,
14872                     FD->getReturnType()->getAs<AutoType>()))
14873               FD->setInvalidDecl();
14874           }
14875         }
14876       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14877         // In C++11, we don't use 'auto' deduction rules for lambda call
14878         // operators because we don't support return type deduction.
14879         auto *LSI = getCurLambda();
14880         if (LSI->HasImplicitReturnType) {
14881           deduceClosureReturnType(*LSI);
14882 
14883           // C++11 [expr.prim.lambda]p4:
14884           //   [...] if there are no return statements in the compound-statement
14885           //   [the deduced type is] the type void
14886           QualType RetType =
14887               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14888 
14889           // Update the return type to the deduced type.
14890           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14891           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14892                                               Proto->getExtProtoInfo()));
14893         }
14894       }
14895 
14896       // If the function implicitly returns zero (like 'main') or is naked,
14897       // don't complain about missing return statements.
14898       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14899         WP.disableCheckFallThrough();
14900 
14901       // MSVC permits the use of pure specifier (=0) on function definition,
14902       // defined at class scope, warn about this non-standard construct.
14903       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14904         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14905 
14906       if (!FD->isInvalidDecl()) {
14907         // Don't diagnose unused parameters of defaulted, deleted or naked
14908         // functions.
14909         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14910             !FD->hasAttr<NakedAttr>())
14911           DiagnoseUnusedParameters(FD->parameters());
14912         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14913                                                FD->getReturnType(), FD);
14914 
14915         // If this is a structor, we need a vtable.
14916         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14917           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14918         else if (CXXDestructorDecl *Destructor =
14919                      dyn_cast<CXXDestructorDecl>(FD))
14920           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14921 
14922         // Try to apply the named return value optimization. We have to check
14923         // if we can do this here because lambdas keep return statements around
14924         // to deduce an implicit return type.
14925         if (FD->getReturnType()->isRecordType() &&
14926             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14927           computeNRVO(Body, FSI);
14928       }
14929 
14930       // GNU warning -Wmissing-prototypes:
14931       //   Warn if a global function is defined without a previous
14932       //   prototype declaration. This warning is issued even if the
14933       //   definition itself provides a prototype. The aim is to detect
14934       //   global functions that fail to be declared in header files.
14935       const FunctionDecl *PossiblePrototype = nullptr;
14936       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14937         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14938 
14939         if (PossiblePrototype) {
14940           // We found a declaration that is not a prototype,
14941           // but that could be a zero-parameter prototype
14942           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14943             TypeLoc TL = TI->getTypeLoc();
14944             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14945               Diag(PossiblePrototype->getLocation(),
14946                    diag::note_declaration_not_a_prototype)
14947                   << (FD->getNumParams() != 0)
14948                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14949                                                     FTL.getRParenLoc(), "void")
14950                                               : FixItHint{});
14951           }
14952         } else {
14953           // Returns true if the token beginning at this Loc is `const`.
14954           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14955                                   const LangOptions &LangOpts) {
14956             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14957             if (LocInfo.first.isInvalid())
14958               return false;
14959 
14960             bool Invalid = false;
14961             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14962             if (Invalid)
14963               return false;
14964 
14965             if (LocInfo.second > Buffer.size())
14966               return false;
14967 
14968             const char *LexStart = Buffer.data() + LocInfo.second;
14969             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14970 
14971             return StartTok.consume_front("const") &&
14972                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14973                     StartTok.startswith("/*") || StartTok.startswith("//"));
14974           };
14975 
14976           auto findBeginLoc = [&]() {
14977             // If the return type has `const` qualifier, we want to insert
14978             // `static` before `const` (and not before the typename).
14979             if ((FD->getReturnType()->isAnyPointerType() &&
14980                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14981                 FD->getReturnType().isConstQualified()) {
14982               // But only do this if we can determine where the `const` is.
14983 
14984               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14985                                getLangOpts()))
14986 
14987                 return FD->getBeginLoc();
14988             }
14989             return FD->getTypeSpecStartLoc();
14990           };
14991           Diag(FD->getTypeSpecStartLoc(),
14992                diag::note_static_for_internal_linkage)
14993               << /* function */ 1
14994               << (FD->getStorageClass() == SC_None
14995                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14996                       : FixItHint{});
14997         }
14998       }
14999 
15000       // If the function being defined does not have a prototype, then we may
15001       // need to diagnose it as changing behavior in C2x because we now know
15002       // whether the function accepts arguments or not. This only handles the
15003       // case where the definition has no prototype but does have parameters
15004       // and either there is no previous potential prototype, or the previous
15005       // potential prototype also has no actual prototype. This handles cases
15006       // like:
15007       //   void f(); void f(a) int a; {}
15008       //   void g(a) int a; {}
15009       // See MergeFunctionDecl() for other cases of the behavior change
15010       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15011       // type without a prototype.
15012       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15013           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15014                                   !PossiblePrototype->isImplicit()))) {
15015         // The function definition has parameters, so this will change behavior
15016         // in C2x. If there is a possible prototype, it comes before the
15017         // function definition.
15018         // FIXME: The declaration may have already been diagnosed as being
15019         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15020         // there's no way to test for the "changes behavior" condition in
15021         // SemaType.cpp when forming the declaration's function type. So, we do
15022         // this awkward dance instead.
15023         //
15024         // If we have a possible prototype and it declares a function with a
15025         // prototype, we don't want to diagnose it; if we have a possible
15026         // prototype and it has no prototype, it may have already been
15027         // diagnosed in SemaType.cpp as deprecated depending on whether
15028         // -Wstrict-prototypes is enabled. If we already warned about it being
15029         // deprecated, add a note that it also changes behavior. If we didn't
15030         // warn about it being deprecated (because the diagnostic is not
15031         // enabled), warn now that it is deprecated and changes behavior.
15032         bool AddNote = false;
15033         if (PossiblePrototype) {
15034           if (Diags.isIgnored(diag::warn_strict_prototypes,
15035                               PossiblePrototype->getLocation())) {
15036 
15037             PartialDiagnostic PD =
15038                 PDiag(diag::warn_non_prototype_changes_behavior);
15039             if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) {
15040               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
15041                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
15042             }
15043             Diag(PossiblePrototype->getLocation(), PD);
15044           } else {
15045             AddNote = true;
15046           }
15047         }
15048 
15049         // Because this function definition has no prototype and it has
15050         // parameters, it will definitely change behavior in C2x.
15051         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior);
15052         if (AddNote)
15053           Diag(PossiblePrototype->getLocation(),
15054                diag::note_func_decl_changes_behavior);
15055       }
15056 
15057       // Warn on CPUDispatch with an actual body.
15058       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15059         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15060           if (!CmpndBody->body_empty())
15061             Diag(CmpndBody->body_front()->getBeginLoc(),
15062                  diag::warn_dispatch_body_ignored);
15063 
15064       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15065         const CXXMethodDecl *KeyFunction;
15066         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15067             MD->isVirtual() &&
15068             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15069             MD == KeyFunction->getCanonicalDecl()) {
15070           // Update the key-function state if necessary for this ABI.
15071           if (FD->isInlined() &&
15072               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15073             Context.setNonKeyFunction(MD);
15074 
15075             // If the newly-chosen key function is already defined, then we
15076             // need to mark the vtable as used retroactively.
15077             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15078             const FunctionDecl *Definition;
15079             if (KeyFunction && KeyFunction->isDefined(Definition))
15080               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15081           } else {
15082             // We just defined they key function; mark the vtable as used.
15083             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15084           }
15085         }
15086       }
15087 
15088       assert(
15089           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15090           "Function parsing confused");
15091     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15092       assert(MD == getCurMethodDecl() && "Method parsing confused");
15093       MD->setBody(Body);
15094       if (!MD->isInvalidDecl()) {
15095         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15096                                                MD->getReturnType(), MD);
15097 
15098         if (Body)
15099           computeNRVO(Body, FSI);
15100       }
15101       if (FSI->ObjCShouldCallSuper) {
15102         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15103             << MD->getSelector().getAsString();
15104         FSI->ObjCShouldCallSuper = false;
15105       }
15106       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15107         const ObjCMethodDecl *InitMethod = nullptr;
15108         bool isDesignated =
15109             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15110         assert(isDesignated && InitMethod);
15111         (void)isDesignated;
15112 
15113         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15114           auto IFace = MD->getClassInterface();
15115           if (!IFace)
15116             return false;
15117           auto SuperD = IFace->getSuperClass();
15118           if (!SuperD)
15119             return false;
15120           return SuperD->getIdentifier() ==
15121                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15122         };
15123         // Don't issue this warning for unavailable inits or direct subclasses
15124         // of NSObject.
15125         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15126           Diag(MD->getLocation(),
15127                diag::warn_objc_designated_init_missing_super_call);
15128           Diag(InitMethod->getLocation(),
15129                diag::note_objc_designated_init_marked_here);
15130         }
15131         FSI->ObjCWarnForNoDesignatedInitChain = false;
15132       }
15133       if (FSI->ObjCWarnForNoInitDelegation) {
15134         // Don't issue this warning for unavaialable inits.
15135         if (!MD->isUnavailable())
15136           Diag(MD->getLocation(),
15137                diag::warn_objc_secondary_init_missing_init_call);
15138         FSI->ObjCWarnForNoInitDelegation = false;
15139       }
15140 
15141       diagnoseImplicitlyRetainedSelf(*this);
15142     } else {
15143       // Parsing the function declaration failed in some way. Pop the fake scope
15144       // we pushed on.
15145       PopFunctionScopeInfo(ActivePolicy, dcl);
15146       return nullptr;
15147     }
15148 
15149     if (Body && FSI->HasPotentialAvailabilityViolations)
15150       DiagnoseUnguardedAvailabilityViolations(dcl);
15151 
15152     assert(!FSI->ObjCShouldCallSuper &&
15153            "This should only be set for ObjC methods, which should have been "
15154            "handled in the block above.");
15155 
15156     // Verify and clean out per-function state.
15157     if (Body && (!FD || !FD->isDefaulted())) {
15158       // C++ constructors that have function-try-blocks can't have return
15159       // statements in the handlers of that block. (C++ [except.handle]p14)
15160       // Verify this.
15161       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15162         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15163 
15164       // Verify that gotos and switch cases don't jump into scopes illegally.
15165       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15166         DiagnoseInvalidJumps(Body);
15167 
15168       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15169         if (!Destructor->getParent()->isDependentType())
15170           CheckDestructor(Destructor);
15171 
15172         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15173                                                Destructor->getParent());
15174       }
15175 
15176       // If any errors have occurred, clear out any temporaries that may have
15177       // been leftover. This ensures that these temporaries won't be picked up
15178       // for deletion in some later function.
15179       if (hasUncompilableErrorOccurred() ||
15180           getDiagnostics().getSuppressAllDiagnostics()) {
15181         DiscardCleanupsInEvaluationContext();
15182       }
15183       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15184         // Since the body is valid, issue any analysis-based warnings that are
15185         // enabled.
15186         ActivePolicy = &WP;
15187       }
15188 
15189       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15190           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15191         FD->setInvalidDecl();
15192 
15193       if (FD && FD->hasAttr<NakedAttr>()) {
15194         for (const Stmt *S : Body->children()) {
15195           // Allow local register variables without initializer as they don't
15196           // require prologue.
15197           bool RegisterVariables = false;
15198           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15199             for (const auto *Decl : DS->decls()) {
15200               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15201                 RegisterVariables =
15202                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15203                 if (!RegisterVariables)
15204                   break;
15205               }
15206             }
15207           }
15208           if (RegisterVariables)
15209             continue;
15210           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15211             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15212             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15213             FD->setInvalidDecl();
15214             break;
15215           }
15216         }
15217       }
15218 
15219       assert(ExprCleanupObjects.size() ==
15220                  ExprEvalContexts.back().NumCleanupObjects &&
15221              "Leftover temporaries in function");
15222       assert(!Cleanup.exprNeedsCleanups() &&
15223              "Unaccounted cleanups in function");
15224       assert(MaybeODRUseExprs.empty() &&
15225              "Leftover expressions for odr-use checking");
15226     }
15227   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15228     // the declaration context below. Otherwise, we're unable to transform
15229     // 'this' expressions when transforming immediate context functions.
15230 
15231   if (!IsInstantiation)
15232     PopDeclContext();
15233 
15234   PopFunctionScopeInfo(ActivePolicy, dcl);
15235   // If any errors have occurred, clear out any temporaries that may have
15236   // been leftover. This ensures that these temporaries won't be picked up for
15237   // deletion in some later function.
15238   if (hasUncompilableErrorOccurred()) {
15239     DiscardCleanupsInEvaluationContext();
15240   }
15241 
15242   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15243                                   !LangOpts.OMPTargetTriples.empty())) ||
15244              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15245     auto ES = getEmissionStatus(FD);
15246     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15247         ES == Sema::FunctionEmissionStatus::Unknown)
15248       DeclsToCheckForDeferredDiags.insert(FD);
15249   }
15250 
15251   if (FD && !FD->isDeleted())
15252     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15253 
15254   return dcl;
15255 }
15256 
15257 /// When we finish delayed parsing of an attribute, we must attach it to the
15258 /// relevant Decl.
15259 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15260                                        ParsedAttributes &Attrs) {
15261   // Always attach attributes to the underlying decl.
15262   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15263     D = TD->getTemplatedDecl();
15264   ProcessDeclAttributeList(S, D, Attrs);
15265 
15266   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15267     if (Method->isStatic())
15268       checkThisInStaticMemberFunctionAttributes(Method);
15269 }
15270 
15271 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15272 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15273 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15274                                           IdentifierInfo &II, Scope *S) {
15275   // It is not valid to implicitly define a function in C2x.
15276   assert(!LangOpts.C2x && "Cannot implicitly define a function in C2x");
15277 
15278   // Find the scope in which the identifier is injected and the corresponding
15279   // DeclContext.
15280   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15281   // In that case, we inject the declaration into the translation unit scope
15282   // instead.
15283   Scope *BlockScope = S;
15284   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15285     BlockScope = BlockScope->getParent();
15286 
15287   Scope *ContextScope = BlockScope;
15288   while (!ContextScope->getEntity())
15289     ContextScope = ContextScope->getParent();
15290   ContextRAII SavedContext(*this, ContextScope->getEntity());
15291 
15292   // Before we produce a declaration for an implicitly defined
15293   // function, see whether there was a locally-scoped declaration of
15294   // this name as a function or variable. If so, use that
15295   // (non-visible) declaration, and complain about it.
15296   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15297   if (ExternCPrev) {
15298     // We still need to inject the function into the enclosing block scope so
15299     // that later (non-call) uses can see it.
15300     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15301 
15302     // C89 footnote 38:
15303     //   If in fact it is not defined as having type "function returning int",
15304     //   the behavior is undefined.
15305     if (!isa<FunctionDecl>(ExternCPrev) ||
15306         !Context.typesAreCompatible(
15307             cast<FunctionDecl>(ExternCPrev)->getType(),
15308             Context.getFunctionNoProtoType(Context.IntTy))) {
15309       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15310           << ExternCPrev << !getLangOpts().C99;
15311       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15312       return ExternCPrev;
15313     }
15314   }
15315 
15316   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15317   unsigned diag_id;
15318   if (II.getName().startswith("__builtin_"))
15319     diag_id = diag::warn_builtin_unknown;
15320   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15321   else if (getLangOpts().OpenCL)
15322     diag_id = diag::err_opencl_implicit_function_decl;
15323   else if (getLangOpts().C99)
15324     diag_id = diag::ext_implicit_function_decl_c99;
15325   else
15326     diag_id = diag::warn_implicit_function_decl;
15327 
15328   TypoCorrection Corrected;
15329   // Because typo correction is expensive, only do it if the implicit
15330   // function declaration is going to be treated as an error.
15331   //
15332   // Perform the corection before issuing the main diagnostic, as some consumers
15333   // use typo-correction callbacks to enhance the main diagnostic.
15334   if (S && !ExternCPrev &&
15335       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15336     DeclFilterCCC<FunctionDecl> CCC{};
15337     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15338                             S, nullptr, CCC, CTK_NonError);
15339   }
15340 
15341   Diag(Loc, diag_id) << &II;
15342   if (Corrected) {
15343     // If the correction is going to suggest an implicitly defined function,
15344     // skip the correction as not being a particularly good idea.
15345     bool Diagnose = true;
15346     if (const auto *D = Corrected.getCorrectionDecl())
15347       Diagnose = !D->isImplicit();
15348     if (Diagnose)
15349       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15350                    /*ErrorRecovery*/ false);
15351   }
15352 
15353   // If we found a prior declaration of this function, don't bother building
15354   // another one. We've already pushed that one into scope, so there's nothing
15355   // more to do.
15356   if (ExternCPrev)
15357     return ExternCPrev;
15358 
15359   // Set a Declarator for the implicit definition: int foo();
15360   const char *Dummy;
15361   AttributeFactory attrFactory;
15362   DeclSpec DS(attrFactory);
15363   unsigned DiagID;
15364   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15365                                   Context.getPrintingPolicy());
15366   (void)Error; // Silence warning.
15367   assert(!Error && "Error setting up implicit decl!");
15368   SourceLocation NoLoc;
15369   Declarator D(DS, DeclaratorContext::Block);
15370   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15371                                              /*IsAmbiguous=*/false,
15372                                              /*LParenLoc=*/NoLoc,
15373                                              /*Params=*/nullptr,
15374                                              /*NumParams=*/0,
15375                                              /*EllipsisLoc=*/NoLoc,
15376                                              /*RParenLoc=*/NoLoc,
15377                                              /*RefQualifierIsLvalueRef=*/true,
15378                                              /*RefQualifierLoc=*/NoLoc,
15379                                              /*MutableLoc=*/NoLoc, EST_None,
15380                                              /*ESpecRange=*/SourceRange(),
15381                                              /*Exceptions=*/nullptr,
15382                                              /*ExceptionRanges=*/nullptr,
15383                                              /*NumExceptions=*/0,
15384                                              /*NoexceptExpr=*/nullptr,
15385                                              /*ExceptionSpecTokens=*/nullptr,
15386                                              /*DeclsInPrototype=*/None, Loc,
15387                                              Loc, D),
15388                 std::move(DS.getAttributes()), SourceLocation());
15389   D.SetIdentifier(&II, Loc);
15390 
15391   // Insert this function into the enclosing block scope.
15392   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15393   FD->setImplicit();
15394 
15395   AddKnownFunctionAttributes(FD);
15396 
15397   return FD;
15398 }
15399 
15400 /// If this function is a C++ replaceable global allocation function
15401 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15402 /// adds any function attributes that we know a priori based on the standard.
15403 ///
15404 /// We need to check for duplicate attributes both here and where user-written
15405 /// attributes are applied to declarations.
15406 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15407     FunctionDecl *FD) {
15408   if (FD->isInvalidDecl())
15409     return;
15410 
15411   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15412       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15413     return;
15414 
15415   Optional<unsigned> AlignmentParam;
15416   bool IsNothrow = false;
15417   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15418     return;
15419 
15420   // C++2a [basic.stc.dynamic.allocation]p4:
15421   //   An allocation function that has a non-throwing exception specification
15422   //   indicates failure by returning a null pointer value. Any other allocation
15423   //   function never returns a null pointer value and indicates failure only by
15424   //   throwing an exception [...]
15425   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15426     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15427 
15428   // C++2a [basic.stc.dynamic.allocation]p2:
15429   //   An allocation function attempts to allocate the requested amount of
15430   //   storage. [...] If the request succeeds, the value returned by a
15431   //   replaceable allocation function is a [...] pointer value p0 different
15432   //   from any previously returned value p1 [...]
15433   //
15434   // However, this particular information is being added in codegen,
15435   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15436 
15437   // C++2a [basic.stc.dynamic.allocation]p2:
15438   //   An allocation function attempts to allocate the requested amount of
15439   //   storage. If it is successful, it returns the address of the start of a
15440   //   block of storage whose length in bytes is at least as large as the
15441   //   requested size.
15442   if (!FD->hasAttr<AllocSizeAttr>()) {
15443     FD->addAttr(AllocSizeAttr::CreateImplicit(
15444         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15445         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15446   }
15447 
15448   // C++2a [basic.stc.dynamic.allocation]p3:
15449   //   For an allocation function [...], the pointer returned on a successful
15450   //   call shall represent the address of storage that is aligned as follows:
15451   //   (3.1) If the allocation function takes an argument of type
15452   //         std​::​align_­val_­t, the storage will have the alignment
15453   //         specified by the value of this argument.
15454   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15455     FD->addAttr(AllocAlignAttr::CreateImplicit(
15456         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15457   }
15458 
15459   // FIXME:
15460   // C++2a [basic.stc.dynamic.allocation]p3:
15461   //   For an allocation function [...], the pointer returned on a successful
15462   //   call shall represent the address of storage that is aligned as follows:
15463   //   (3.2) Otherwise, if the allocation function is named operator new[],
15464   //         the storage is aligned for any object that does not have
15465   //         new-extended alignment ([basic.align]) and is no larger than the
15466   //         requested size.
15467   //   (3.3) Otherwise, the storage is aligned for any object that does not
15468   //         have new-extended alignment and is of the requested size.
15469 }
15470 
15471 /// Adds any function attributes that we know a priori based on
15472 /// the declaration of this function.
15473 ///
15474 /// These attributes can apply both to implicitly-declared builtins
15475 /// (like __builtin___printf_chk) or to library-declared functions
15476 /// like NSLog or printf.
15477 ///
15478 /// We need to check for duplicate attributes both here and where user-written
15479 /// attributes are applied to declarations.
15480 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15481   if (FD->isInvalidDecl())
15482     return;
15483 
15484   // If this is a built-in function, map its builtin attributes to
15485   // actual attributes.
15486   if (unsigned BuiltinID = FD->getBuiltinID()) {
15487     // Handle printf-formatting attributes.
15488     unsigned FormatIdx;
15489     bool HasVAListArg;
15490     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15491       if (!FD->hasAttr<FormatAttr>()) {
15492         const char *fmt = "printf";
15493         unsigned int NumParams = FD->getNumParams();
15494         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15495             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15496           fmt = "NSString";
15497         FD->addAttr(FormatAttr::CreateImplicit(Context,
15498                                                &Context.Idents.get(fmt),
15499                                                FormatIdx+1,
15500                                                HasVAListArg ? 0 : FormatIdx+2,
15501                                                FD->getLocation()));
15502       }
15503     }
15504     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15505                                              HasVAListArg)) {
15506      if (!FD->hasAttr<FormatAttr>())
15507        FD->addAttr(FormatAttr::CreateImplicit(Context,
15508                                               &Context.Idents.get("scanf"),
15509                                               FormatIdx+1,
15510                                               HasVAListArg ? 0 : FormatIdx+2,
15511                                               FD->getLocation()));
15512     }
15513 
15514     // Handle automatically recognized callbacks.
15515     SmallVector<int, 4> Encoding;
15516     if (!FD->hasAttr<CallbackAttr>() &&
15517         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15518       FD->addAttr(CallbackAttr::CreateImplicit(
15519           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15520 
15521     // Mark const if we don't care about errno and that is the only thing
15522     // preventing the function from being const. This allows IRgen to use LLVM
15523     // intrinsics for such functions.
15524     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15525         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15526       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15527 
15528     // We make "fma" on GNU or Windows const because we know it does not set
15529     // errno in those environments even though it could set errno based on the
15530     // C standard.
15531     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15532     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15533         !FD->hasAttr<ConstAttr>()) {
15534       switch (BuiltinID) {
15535       case Builtin::BI__builtin_fma:
15536       case Builtin::BI__builtin_fmaf:
15537       case Builtin::BI__builtin_fmal:
15538       case Builtin::BIfma:
15539       case Builtin::BIfmaf:
15540       case Builtin::BIfmal:
15541         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15542         break;
15543       default:
15544         break;
15545       }
15546     }
15547 
15548     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15549         !FD->hasAttr<ReturnsTwiceAttr>())
15550       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15551                                          FD->getLocation()));
15552     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15553       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15554     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15555       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15556     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15557       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15558     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15559         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15560       // Add the appropriate attribute, depending on the CUDA compilation mode
15561       // and which target the builtin belongs to. For example, during host
15562       // compilation, aux builtins are __device__, while the rest are __host__.
15563       if (getLangOpts().CUDAIsDevice !=
15564           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15565         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15566       else
15567         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15568     }
15569 
15570     // Add known guaranteed alignment for allocation functions.
15571     switch (BuiltinID) {
15572     case Builtin::BImemalign:
15573     case Builtin::BIaligned_alloc:
15574       if (!FD->hasAttr<AllocAlignAttr>())
15575         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15576                                                    FD->getLocation()));
15577       break;
15578     default:
15579       break;
15580     }
15581 
15582     // Add allocsize attribute for allocation functions.
15583     switch (BuiltinID) {
15584     case Builtin::BIcalloc:
15585       FD->addAttr(AllocSizeAttr::CreateImplicit(
15586           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15587       break;
15588     case Builtin::BImemalign:
15589     case Builtin::BIaligned_alloc:
15590     case Builtin::BIrealloc:
15591       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15592                                                 ParamIdx(), FD->getLocation()));
15593       break;
15594     case Builtin::BImalloc:
15595       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15596                                                 ParamIdx(), FD->getLocation()));
15597       break;
15598     default:
15599       break;
15600     }
15601   }
15602 
15603   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15604 
15605   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15606   // throw, add an implicit nothrow attribute to any extern "C" function we come
15607   // across.
15608   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15609       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15610     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15611     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15612       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15613   }
15614 
15615   IdentifierInfo *Name = FD->getIdentifier();
15616   if (!Name)
15617     return;
15618   if ((!getLangOpts().CPlusPlus &&
15619        FD->getDeclContext()->isTranslationUnit()) ||
15620       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15621        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15622        LinkageSpecDecl::lang_c)) {
15623     // Okay: this could be a libc/libm/Objective-C function we know
15624     // about.
15625   } else
15626     return;
15627 
15628   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15629     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15630     // target-specific builtins, perhaps?
15631     if (!FD->hasAttr<FormatAttr>())
15632       FD->addAttr(FormatAttr::CreateImplicit(Context,
15633                                              &Context.Idents.get("printf"), 2,
15634                                              Name->isStr("vasprintf") ? 0 : 3,
15635                                              FD->getLocation()));
15636   }
15637 
15638   if (Name->isStr("__CFStringMakeConstantString")) {
15639     // We already have a __builtin___CFStringMakeConstantString,
15640     // but builds that use -fno-constant-cfstrings don't go through that.
15641     if (!FD->hasAttr<FormatArgAttr>())
15642       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15643                                                 FD->getLocation()));
15644   }
15645 }
15646 
15647 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15648                                     TypeSourceInfo *TInfo) {
15649   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15650   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15651 
15652   if (!TInfo) {
15653     assert(D.isInvalidType() && "no declarator info for valid type");
15654     TInfo = Context.getTrivialTypeSourceInfo(T);
15655   }
15656 
15657   // Scope manipulation handled by caller.
15658   TypedefDecl *NewTD =
15659       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15660                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15661 
15662   // Bail out immediately if we have an invalid declaration.
15663   if (D.isInvalidType()) {
15664     NewTD->setInvalidDecl();
15665     return NewTD;
15666   }
15667 
15668   if (D.getDeclSpec().isModulePrivateSpecified()) {
15669     if (CurContext->isFunctionOrMethod())
15670       Diag(NewTD->getLocation(), diag::err_module_private_local)
15671           << 2 << NewTD
15672           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15673           << FixItHint::CreateRemoval(
15674                  D.getDeclSpec().getModulePrivateSpecLoc());
15675     else
15676       NewTD->setModulePrivate();
15677   }
15678 
15679   // C++ [dcl.typedef]p8:
15680   //   If the typedef declaration defines an unnamed class (or
15681   //   enum), the first typedef-name declared by the declaration
15682   //   to be that class type (or enum type) is used to denote the
15683   //   class type (or enum type) for linkage purposes only.
15684   // We need to check whether the type was declared in the declaration.
15685   switch (D.getDeclSpec().getTypeSpecType()) {
15686   case TST_enum:
15687   case TST_struct:
15688   case TST_interface:
15689   case TST_union:
15690   case TST_class: {
15691     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15692     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15693     break;
15694   }
15695 
15696   default:
15697     break;
15698   }
15699 
15700   return NewTD;
15701 }
15702 
15703 /// Check that this is a valid underlying type for an enum declaration.
15704 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15705   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15706   QualType T = TI->getType();
15707 
15708   if (T->isDependentType())
15709     return false;
15710 
15711   // This doesn't use 'isIntegralType' despite the error message mentioning
15712   // integral type because isIntegralType would also allow enum types in C.
15713   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15714     if (BT->isInteger())
15715       return false;
15716 
15717   if (T->isBitIntType())
15718     return false;
15719 
15720   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15721 }
15722 
15723 /// Check whether this is a valid redeclaration of a previous enumeration.
15724 /// \return true if the redeclaration was invalid.
15725 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15726                                   QualType EnumUnderlyingTy, bool IsFixed,
15727                                   const EnumDecl *Prev) {
15728   if (IsScoped != Prev->isScoped()) {
15729     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15730       << Prev->isScoped();
15731     Diag(Prev->getLocation(), diag::note_previous_declaration);
15732     return true;
15733   }
15734 
15735   if (IsFixed && Prev->isFixed()) {
15736     if (!EnumUnderlyingTy->isDependentType() &&
15737         !Prev->getIntegerType()->isDependentType() &&
15738         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15739                                         Prev->getIntegerType())) {
15740       // TODO: Highlight the underlying type of the redeclaration.
15741       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15742         << EnumUnderlyingTy << Prev->getIntegerType();
15743       Diag(Prev->getLocation(), diag::note_previous_declaration)
15744           << Prev->getIntegerTypeRange();
15745       return true;
15746     }
15747   } else if (IsFixed != Prev->isFixed()) {
15748     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15749       << Prev->isFixed();
15750     Diag(Prev->getLocation(), diag::note_previous_declaration);
15751     return true;
15752   }
15753 
15754   return false;
15755 }
15756 
15757 /// Get diagnostic %select index for tag kind for
15758 /// redeclaration diagnostic message.
15759 /// WARNING: Indexes apply to particular diagnostics only!
15760 ///
15761 /// \returns diagnostic %select index.
15762 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15763   switch (Tag) {
15764   case TTK_Struct: return 0;
15765   case TTK_Interface: return 1;
15766   case TTK_Class:  return 2;
15767   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15768   }
15769 }
15770 
15771 /// Determine if tag kind is a class-key compatible with
15772 /// class for redeclaration (class, struct, or __interface).
15773 ///
15774 /// \returns true iff the tag kind is compatible.
15775 static bool isClassCompatTagKind(TagTypeKind Tag)
15776 {
15777   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15778 }
15779 
15780 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15781                                              TagTypeKind TTK) {
15782   if (isa<TypedefDecl>(PrevDecl))
15783     return NTK_Typedef;
15784   else if (isa<TypeAliasDecl>(PrevDecl))
15785     return NTK_TypeAlias;
15786   else if (isa<ClassTemplateDecl>(PrevDecl))
15787     return NTK_Template;
15788   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15789     return NTK_TypeAliasTemplate;
15790   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15791     return NTK_TemplateTemplateArgument;
15792   switch (TTK) {
15793   case TTK_Struct:
15794   case TTK_Interface:
15795   case TTK_Class:
15796     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15797   case TTK_Union:
15798     return NTK_NonUnion;
15799   case TTK_Enum:
15800     return NTK_NonEnum;
15801   }
15802   llvm_unreachable("invalid TTK");
15803 }
15804 
15805 /// Determine whether a tag with a given kind is acceptable
15806 /// as a redeclaration of the given tag declaration.
15807 ///
15808 /// \returns true if the new tag kind is acceptable, false otherwise.
15809 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15810                                         TagTypeKind NewTag, bool isDefinition,
15811                                         SourceLocation NewTagLoc,
15812                                         const IdentifierInfo *Name) {
15813   // C++ [dcl.type.elab]p3:
15814   //   The class-key or enum keyword present in the
15815   //   elaborated-type-specifier shall agree in kind with the
15816   //   declaration to which the name in the elaborated-type-specifier
15817   //   refers. This rule also applies to the form of
15818   //   elaborated-type-specifier that declares a class-name or
15819   //   friend class since it can be construed as referring to the
15820   //   definition of the class. Thus, in any
15821   //   elaborated-type-specifier, the enum keyword shall be used to
15822   //   refer to an enumeration (7.2), the union class-key shall be
15823   //   used to refer to a union (clause 9), and either the class or
15824   //   struct class-key shall be used to refer to a class (clause 9)
15825   //   declared using the class or struct class-key.
15826   TagTypeKind OldTag = Previous->getTagKind();
15827   if (OldTag != NewTag &&
15828       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15829     return false;
15830 
15831   // Tags are compatible, but we might still want to warn on mismatched tags.
15832   // Non-class tags can't be mismatched at this point.
15833   if (!isClassCompatTagKind(NewTag))
15834     return true;
15835 
15836   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15837   // by our warning analysis. We don't want to warn about mismatches with (eg)
15838   // declarations in system headers that are designed to be specialized, but if
15839   // a user asks us to warn, we should warn if their code contains mismatched
15840   // declarations.
15841   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15842     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15843                                       Loc);
15844   };
15845   if (IsIgnoredLoc(NewTagLoc))
15846     return true;
15847 
15848   auto IsIgnored = [&](const TagDecl *Tag) {
15849     return IsIgnoredLoc(Tag->getLocation());
15850   };
15851   while (IsIgnored(Previous)) {
15852     Previous = Previous->getPreviousDecl();
15853     if (!Previous)
15854       return true;
15855     OldTag = Previous->getTagKind();
15856   }
15857 
15858   bool isTemplate = false;
15859   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15860     isTemplate = Record->getDescribedClassTemplate();
15861 
15862   if (inTemplateInstantiation()) {
15863     if (OldTag != NewTag) {
15864       // In a template instantiation, do not offer fix-its for tag mismatches
15865       // since they usually mess up the template instead of fixing the problem.
15866       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15867         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15868         << getRedeclDiagFromTagKind(OldTag);
15869       // FIXME: Note previous location?
15870     }
15871     return true;
15872   }
15873 
15874   if (isDefinition) {
15875     // On definitions, check all previous tags and issue a fix-it for each
15876     // one that doesn't match the current tag.
15877     if (Previous->getDefinition()) {
15878       // Don't suggest fix-its for redefinitions.
15879       return true;
15880     }
15881 
15882     bool previousMismatch = false;
15883     for (const TagDecl *I : Previous->redecls()) {
15884       if (I->getTagKind() != NewTag) {
15885         // Ignore previous declarations for which the warning was disabled.
15886         if (IsIgnored(I))
15887           continue;
15888 
15889         if (!previousMismatch) {
15890           previousMismatch = true;
15891           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15892             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15893             << getRedeclDiagFromTagKind(I->getTagKind());
15894         }
15895         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15896           << getRedeclDiagFromTagKind(NewTag)
15897           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15898                TypeWithKeyword::getTagTypeKindName(NewTag));
15899       }
15900     }
15901     return true;
15902   }
15903 
15904   // Identify the prevailing tag kind: this is the kind of the definition (if
15905   // there is a non-ignored definition), or otherwise the kind of the prior
15906   // (non-ignored) declaration.
15907   const TagDecl *PrevDef = Previous->getDefinition();
15908   if (PrevDef && IsIgnored(PrevDef))
15909     PrevDef = nullptr;
15910   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15911   if (Redecl->getTagKind() != NewTag) {
15912     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15913       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15914       << getRedeclDiagFromTagKind(OldTag);
15915     Diag(Redecl->getLocation(), diag::note_previous_use);
15916 
15917     // If there is a previous definition, suggest a fix-it.
15918     if (PrevDef) {
15919       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15920         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15921         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15922              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15923     }
15924   }
15925 
15926   return true;
15927 }
15928 
15929 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15930 /// from an outer enclosing namespace or file scope inside a friend declaration.
15931 /// This should provide the commented out code in the following snippet:
15932 ///   namespace N {
15933 ///     struct X;
15934 ///     namespace M {
15935 ///       struct Y { friend struct /*N::*/ X; };
15936 ///     }
15937 ///   }
15938 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15939                                          SourceLocation NameLoc) {
15940   // While the decl is in a namespace, do repeated lookup of that name and see
15941   // if we get the same namespace back.  If we do not, continue until
15942   // translation unit scope, at which point we have a fully qualified NNS.
15943   SmallVector<IdentifierInfo *, 4> Namespaces;
15944   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15945   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15946     // This tag should be declared in a namespace, which can only be enclosed by
15947     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15948     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15949     if (!Namespace || Namespace->isAnonymousNamespace())
15950       return FixItHint();
15951     IdentifierInfo *II = Namespace->getIdentifier();
15952     Namespaces.push_back(II);
15953     NamedDecl *Lookup = SemaRef.LookupSingleName(
15954         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15955     if (Lookup == Namespace)
15956       break;
15957   }
15958 
15959   // Once we have all the namespaces, reverse them to go outermost first, and
15960   // build an NNS.
15961   SmallString<64> Insertion;
15962   llvm::raw_svector_ostream OS(Insertion);
15963   if (DC->isTranslationUnit())
15964     OS << "::";
15965   std::reverse(Namespaces.begin(), Namespaces.end());
15966   for (auto *II : Namespaces)
15967     OS << II->getName() << "::";
15968   return FixItHint::CreateInsertion(NameLoc, Insertion);
15969 }
15970 
15971 /// Determine whether a tag originally declared in context \p OldDC can
15972 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15973 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15974 /// using-declaration).
15975 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15976                                          DeclContext *NewDC) {
15977   OldDC = OldDC->getRedeclContext();
15978   NewDC = NewDC->getRedeclContext();
15979 
15980   if (OldDC->Equals(NewDC))
15981     return true;
15982 
15983   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15984   // encloses the other).
15985   if (S.getLangOpts().MSVCCompat &&
15986       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15987     return true;
15988 
15989   return false;
15990 }
15991 
15992 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15993 /// former case, Name will be non-null.  In the later case, Name will be null.
15994 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15995 /// reference/declaration/definition of a tag.
15996 ///
15997 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15998 /// trailing-type-specifier) other than one in an alias-declaration.
15999 ///
16000 /// \param SkipBody If non-null, will be set to indicate if the caller should
16001 /// skip the definition of this tag and treat it as if it were a declaration.
16002 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16003                      SourceLocation KWLoc, CXXScopeSpec &SS,
16004                      IdentifierInfo *Name, SourceLocation NameLoc,
16005                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16006                      SourceLocation ModulePrivateLoc,
16007                      MultiTemplateParamsArg TemplateParameterLists,
16008                      bool &OwnedDecl, bool &IsDependent,
16009                      SourceLocation ScopedEnumKWLoc,
16010                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16011                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16012                      SkipBodyInfo *SkipBody) {
16013   // If this is not a definition, it must have a name.
16014   IdentifierInfo *OrigName = Name;
16015   assert((Name != nullptr || TUK == TUK_Definition) &&
16016          "Nameless record must be a definition!");
16017   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16018 
16019   OwnedDecl = false;
16020   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16021   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16022 
16023   // FIXME: Check member specializations more carefully.
16024   bool isMemberSpecialization = false;
16025   bool Invalid = false;
16026 
16027   // We only need to do this matching if we have template parameters
16028   // or a scope specifier, which also conveniently avoids this work
16029   // for non-C++ cases.
16030   if (TemplateParameterLists.size() > 0 ||
16031       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16032     if (TemplateParameterList *TemplateParams =
16033             MatchTemplateParametersToScopeSpecifier(
16034                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16035                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16036       if (Kind == TTK_Enum) {
16037         Diag(KWLoc, diag::err_enum_template);
16038         return nullptr;
16039       }
16040 
16041       if (TemplateParams->size() > 0) {
16042         // This is a declaration or definition of a class template (which may
16043         // be a member of another template).
16044 
16045         if (Invalid)
16046           return nullptr;
16047 
16048         OwnedDecl = false;
16049         DeclResult Result = CheckClassTemplate(
16050             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16051             AS, ModulePrivateLoc,
16052             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16053             TemplateParameterLists.data(), SkipBody);
16054         return Result.get();
16055       } else {
16056         // The "template<>" header is extraneous.
16057         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16058           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16059         isMemberSpecialization = true;
16060       }
16061     }
16062 
16063     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16064         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16065       return nullptr;
16066   }
16067 
16068   // Figure out the underlying type if this a enum declaration. We need to do
16069   // this early, because it's needed to detect if this is an incompatible
16070   // redeclaration.
16071   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16072   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16073 
16074   if (Kind == TTK_Enum) {
16075     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16076       // No underlying type explicitly specified, or we failed to parse the
16077       // type, default to int.
16078       EnumUnderlying = Context.IntTy.getTypePtr();
16079     } else if (UnderlyingType.get()) {
16080       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16081       // integral type; any cv-qualification is ignored.
16082       TypeSourceInfo *TI = nullptr;
16083       GetTypeFromParser(UnderlyingType.get(), &TI);
16084       EnumUnderlying = TI;
16085 
16086       if (CheckEnumUnderlyingType(TI))
16087         // Recover by falling back to int.
16088         EnumUnderlying = Context.IntTy.getTypePtr();
16089 
16090       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16091                                           UPPC_FixedUnderlyingType))
16092         EnumUnderlying = Context.IntTy.getTypePtr();
16093 
16094     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16095       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16096       // of 'int'. However, if this is an unfixed forward declaration, don't set
16097       // the underlying type unless the user enables -fms-compatibility. This
16098       // makes unfixed forward declared enums incomplete and is more conforming.
16099       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16100         EnumUnderlying = Context.IntTy.getTypePtr();
16101     }
16102   }
16103 
16104   DeclContext *SearchDC = CurContext;
16105   DeclContext *DC = CurContext;
16106   bool isStdBadAlloc = false;
16107   bool isStdAlignValT = false;
16108 
16109   RedeclarationKind Redecl = forRedeclarationInCurContext();
16110   if (TUK == TUK_Friend || TUK == TUK_Reference)
16111     Redecl = NotForRedeclaration;
16112 
16113   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16114   /// implemented asks for structural equivalence checking, the returned decl
16115   /// here is passed back to the parser, allowing the tag body to be parsed.
16116   auto createTagFromNewDecl = [&]() -> TagDecl * {
16117     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16118     // If there is an identifier, use the location of the identifier as the
16119     // location of the decl, otherwise use the location of the struct/union
16120     // keyword.
16121     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16122     TagDecl *New = nullptr;
16123 
16124     if (Kind == TTK_Enum) {
16125       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16126                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16127       // If this is an undefined enum, bail.
16128       if (TUK != TUK_Definition && !Invalid)
16129         return nullptr;
16130       if (EnumUnderlying) {
16131         EnumDecl *ED = cast<EnumDecl>(New);
16132         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16133           ED->setIntegerTypeSourceInfo(TI);
16134         else
16135           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16136         ED->setPromotionType(ED->getIntegerType());
16137       }
16138     } else { // struct/union
16139       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16140                                nullptr);
16141     }
16142 
16143     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16144       // Add alignment attributes if necessary; these attributes are checked
16145       // when the ASTContext lays out the structure.
16146       //
16147       // It is important for implementing the correct semantics that this
16148       // happen here (in ActOnTag). The #pragma pack stack is
16149       // maintained as a result of parser callbacks which can occur at
16150       // many points during the parsing of a struct declaration (because
16151       // the #pragma tokens are effectively skipped over during the
16152       // parsing of the struct).
16153       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16154         AddAlignmentAttributesForRecord(RD);
16155         AddMsStructLayoutForRecord(RD);
16156       }
16157     }
16158     New->setLexicalDeclContext(CurContext);
16159     return New;
16160   };
16161 
16162   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16163   if (Name && SS.isNotEmpty()) {
16164     // We have a nested-name tag ('struct foo::bar').
16165 
16166     // Check for invalid 'foo::'.
16167     if (SS.isInvalid()) {
16168       Name = nullptr;
16169       goto CreateNewDecl;
16170     }
16171 
16172     // If this is a friend or a reference to a class in a dependent
16173     // context, don't try to make a decl for it.
16174     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16175       DC = computeDeclContext(SS, false);
16176       if (!DC) {
16177         IsDependent = true;
16178         return nullptr;
16179       }
16180     } else {
16181       DC = computeDeclContext(SS, true);
16182       if (!DC) {
16183         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16184           << SS.getRange();
16185         return nullptr;
16186       }
16187     }
16188 
16189     if (RequireCompleteDeclContext(SS, DC))
16190       return nullptr;
16191 
16192     SearchDC = DC;
16193     // Look-up name inside 'foo::'.
16194     LookupQualifiedName(Previous, DC);
16195 
16196     if (Previous.isAmbiguous())
16197       return nullptr;
16198 
16199     if (Previous.empty()) {
16200       // Name lookup did not find anything. However, if the
16201       // nested-name-specifier refers to the current instantiation,
16202       // and that current instantiation has any dependent base
16203       // classes, we might find something at instantiation time: treat
16204       // this as a dependent elaborated-type-specifier.
16205       // But this only makes any sense for reference-like lookups.
16206       if (Previous.wasNotFoundInCurrentInstantiation() &&
16207           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16208         IsDependent = true;
16209         return nullptr;
16210       }
16211 
16212       // A tag 'foo::bar' must already exist.
16213       Diag(NameLoc, diag::err_not_tag_in_scope)
16214         << Kind << Name << DC << SS.getRange();
16215       Name = nullptr;
16216       Invalid = true;
16217       goto CreateNewDecl;
16218     }
16219   } else if (Name) {
16220     // C++14 [class.mem]p14:
16221     //   If T is the name of a class, then each of the following shall have a
16222     //   name different from T:
16223     //    -- every member of class T that is itself a type
16224     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16225         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16226       return nullptr;
16227 
16228     // If this is a named struct, check to see if there was a previous forward
16229     // declaration or definition.
16230     // FIXME: We're looking into outer scopes here, even when we
16231     // shouldn't be. Doing so can result in ambiguities that we
16232     // shouldn't be diagnosing.
16233     LookupName(Previous, S);
16234 
16235     // When declaring or defining a tag, ignore ambiguities introduced
16236     // by types using'ed into this scope.
16237     if (Previous.isAmbiguous() &&
16238         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16239       LookupResult::Filter F = Previous.makeFilter();
16240       while (F.hasNext()) {
16241         NamedDecl *ND = F.next();
16242         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16243                 SearchDC->getRedeclContext()))
16244           F.erase();
16245       }
16246       F.done();
16247     }
16248 
16249     // C++11 [namespace.memdef]p3:
16250     //   If the name in a friend declaration is neither qualified nor
16251     //   a template-id and the declaration is a function or an
16252     //   elaborated-type-specifier, the lookup to determine whether
16253     //   the entity has been previously declared shall not consider
16254     //   any scopes outside the innermost enclosing namespace.
16255     //
16256     // MSVC doesn't implement the above rule for types, so a friend tag
16257     // declaration may be a redeclaration of a type declared in an enclosing
16258     // scope.  They do implement this rule for friend functions.
16259     //
16260     // Does it matter that this should be by scope instead of by
16261     // semantic context?
16262     if (!Previous.empty() && TUK == TUK_Friend) {
16263       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16264       LookupResult::Filter F = Previous.makeFilter();
16265       bool FriendSawTagOutsideEnclosingNamespace = false;
16266       while (F.hasNext()) {
16267         NamedDecl *ND = F.next();
16268         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16269         if (DC->isFileContext() &&
16270             !EnclosingNS->Encloses(ND->getDeclContext())) {
16271           if (getLangOpts().MSVCCompat)
16272             FriendSawTagOutsideEnclosingNamespace = true;
16273           else
16274             F.erase();
16275         }
16276       }
16277       F.done();
16278 
16279       // Diagnose this MSVC extension in the easy case where lookup would have
16280       // unambiguously found something outside the enclosing namespace.
16281       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16282         NamedDecl *ND = Previous.getFoundDecl();
16283         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16284             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16285       }
16286     }
16287 
16288     // Note:  there used to be some attempt at recovery here.
16289     if (Previous.isAmbiguous())
16290       return nullptr;
16291 
16292     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16293       // FIXME: This makes sure that we ignore the contexts associated
16294       // with C structs, unions, and enums when looking for a matching
16295       // tag declaration or definition. See the similar lookup tweak
16296       // in Sema::LookupName; is there a better way to deal with this?
16297       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16298         SearchDC = SearchDC->getParent();
16299     } else if (getLangOpts().CPlusPlus) {
16300       // Inside ObjCContainer want to keep it as a lexical decl context but go
16301       // past it (most often to TranslationUnit) to find the semantic decl
16302       // context.
16303       while (isa<ObjCContainerDecl>(SearchDC))
16304         SearchDC = SearchDC->getParent();
16305     }
16306   } else if (getLangOpts().CPlusPlus) {
16307     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16308     // TagDecl the same way as we skip it for named TagDecl.
16309     while (isa<ObjCContainerDecl>(SearchDC))
16310       SearchDC = SearchDC->getParent();
16311   }
16312 
16313   if (Previous.isSingleResult() &&
16314       Previous.getFoundDecl()->isTemplateParameter()) {
16315     // Maybe we will complain about the shadowed template parameter.
16316     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16317     // Just pretend that we didn't see the previous declaration.
16318     Previous.clear();
16319   }
16320 
16321   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16322       DC->Equals(getStdNamespace())) {
16323     if (Name->isStr("bad_alloc")) {
16324       // This is a declaration of or a reference to "std::bad_alloc".
16325       isStdBadAlloc = true;
16326 
16327       // If std::bad_alloc has been implicitly declared (but made invisible to
16328       // name lookup), fill in this implicit declaration as the previous
16329       // declaration, so that the declarations get chained appropriately.
16330       if (Previous.empty() && StdBadAlloc)
16331         Previous.addDecl(getStdBadAlloc());
16332     } else if (Name->isStr("align_val_t")) {
16333       isStdAlignValT = true;
16334       if (Previous.empty() && StdAlignValT)
16335         Previous.addDecl(getStdAlignValT());
16336     }
16337   }
16338 
16339   // If we didn't find a previous declaration, and this is a reference
16340   // (or friend reference), move to the correct scope.  In C++, we
16341   // also need to do a redeclaration lookup there, just in case
16342   // there's a shadow friend decl.
16343   if (Name && Previous.empty() &&
16344       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16345     if (Invalid) goto CreateNewDecl;
16346     assert(SS.isEmpty());
16347 
16348     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16349       // C++ [basic.scope.pdecl]p5:
16350       //   -- for an elaborated-type-specifier of the form
16351       //
16352       //          class-key identifier
16353       //
16354       //      if the elaborated-type-specifier is used in the
16355       //      decl-specifier-seq or parameter-declaration-clause of a
16356       //      function defined in namespace scope, the identifier is
16357       //      declared as a class-name in the namespace that contains
16358       //      the declaration; otherwise, except as a friend
16359       //      declaration, the identifier is declared in the smallest
16360       //      non-class, non-function-prototype scope that contains the
16361       //      declaration.
16362       //
16363       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16364       // C structs and unions.
16365       //
16366       // It is an error in C++ to declare (rather than define) an enum
16367       // type, including via an elaborated type specifier.  We'll
16368       // diagnose that later; for now, declare the enum in the same
16369       // scope as we would have picked for any other tag type.
16370       //
16371       // GNU C also supports this behavior as part of its incomplete
16372       // enum types extension, while GNU C++ does not.
16373       //
16374       // Find the context where we'll be declaring the tag.
16375       // FIXME: We would like to maintain the current DeclContext as the
16376       // lexical context,
16377       SearchDC = getTagInjectionContext(SearchDC);
16378 
16379       // Find the scope where we'll be declaring the tag.
16380       S = getTagInjectionScope(S, getLangOpts());
16381     } else {
16382       assert(TUK == TUK_Friend);
16383       // C++ [namespace.memdef]p3:
16384       //   If a friend declaration in a non-local class first declares a
16385       //   class or function, the friend class or function is a member of
16386       //   the innermost enclosing namespace.
16387       SearchDC = SearchDC->getEnclosingNamespaceContext();
16388     }
16389 
16390     // In C++, we need to do a redeclaration lookup to properly
16391     // diagnose some problems.
16392     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16393     // hidden declaration so that we don't get ambiguity errors when using a
16394     // type declared by an elaborated-type-specifier.  In C that is not correct
16395     // and we should instead merge compatible types found by lookup.
16396     if (getLangOpts().CPlusPlus) {
16397       // FIXME: This can perform qualified lookups into function contexts,
16398       // which are meaningless.
16399       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16400       LookupQualifiedName(Previous, SearchDC);
16401     } else {
16402       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16403       LookupName(Previous, S);
16404     }
16405   }
16406 
16407   // If we have a known previous declaration to use, then use it.
16408   if (Previous.empty() && SkipBody && SkipBody->Previous)
16409     Previous.addDecl(SkipBody->Previous);
16410 
16411   if (!Previous.empty()) {
16412     NamedDecl *PrevDecl = Previous.getFoundDecl();
16413     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16414 
16415     // It's okay to have a tag decl in the same scope as a typedef
16416     // which hides a tag decl in the same scope.  Finding this
16417     // with a redeclaration lookup can only actually happen in C++.
16418     //
16419     // This is also okay for elaborated-type-specifiers, which is
16420     // technically forbidden by the current standard but which is
16421     // okay according to the likely resolution of an open issue;
16422     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16423     if (getLangOpts().CPlusPlus) {
16424       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16425         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16426           TagDecl *Tag = TT->getDecl();
16427           if (Tag->getDeclName() == Name &&
16428               Tag->getDeclContext()->getRedeclContext()
16429                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16430             PrevDecl = Tag;
16431             Previous.clear();
16432             Previous.addDecl(Tag);
16433             Previous.resolveKind();
16434           }
16435         }
16436       }
16437     }
16438 
16439     // If this is a redeclaration of a using shadow declaration, it must
16440     // declare a tag in the same context. In MSVC mode, we allow a
16441     // redefinition if either context is within the other.
16442     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16443       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16444       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16445           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16446           !(OldTag && isAcceptableTagRedeclContext(
16447                           *this, OldTag->getDeclContext(), SearchDC))) {
16448         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16449         Diag(Shadow->getTargetDecl()->getLocation(),
16450              diag::note_using_decl_target);
16451         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16452             << 0;
16453         // Recover by ignoring the old declaration.
16454         Previous.clear();
16455         goto CreateNewDecl;
16456       }
16457     }
16458 
16459     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16460       // If this is a use of a previous tag, or if the tag is already declared
16461       // in the same scope (so that the definition/declaration completes or
16462       // rementions the tag), reuse the decl.
16463       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16464           isDeclInScope(DirectPrevDecl, SearchDC, S,
16465                         SS.isNotEmpty() || isMemberSpecialization)) {
16466         // Make sure that this wasn't declared as an enum and now used as a
16467         // struct or something similar.
16468         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16469                                           TUK == TUK_Definition, KWLoc,
16470                                           Name)) {
16471           bool SafeToContinue
16472             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16473                Kind != TTK_Enum);
16474           if (SafeToContinue)
16475             Diag(KWLoc, diag::err_use_with_wrong_tag)
16476               << Name
16477               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16478                                               PrevTagDecl->getKindName());
16479           else
16480             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16481           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16482 
16483           if (SafeToContinue)
16484             Kind = PrevTagDecl->getTagKind();
16485           else {
16486             // Recover by making this an anonymous redefinition.
16487             Name = nullptr;
16488             Previous.clear();
16489             Invalid = true;
16490           }
16491         }
16492 
16493         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16494           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16495           if (TUK == TUK_Reference || TUK == TUK_Friend)
16496             return PrevTagDecl;
16497 
16498           QualType EnumUnderlyingTy;
16499           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16500             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16501           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16502             EnumUnderlyingTy = QualType(T, 0);
16503 
16504           // All conflicts with previous declarations are recovered by
16505           // returning the previous declaration, unless this is a definition,
16506           // in which case we want the caller to bail out.
16507           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16508                                      ScopedEnum, EnumUnderlyingTy,
16509                                      IsFixed, PrevEnum))
16510             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16511         }
16512 
16513         // C++11 [class.mem]p1:
16514         //   A member shall not be declared twice in the member-specification,
16515         //   except that a nested class or member class template can be declared
16516         //   and then later defined.
16517         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16518             S->isDeclScope(PrevDecl)) {
16519           Diag(NameLoc, diag::ext_member_redeclared);
16520           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16521         }
16522 
16523         if (!Invalid) {
16524           // If this is a use, just return the declaration we found, unless
16525           // we have attributes.
16526           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16527             if (!Attrs.empty()) {
16528               // FIXME: Diagnose these attributes. For now, we create a new
16529               // declaration to hold them.
16530             } else if (TUK == TUK_Reference &&
16531                        (PrevTagDecl->getFriendObjectKind() ==
16532                             Decl::FOK_Undeclared ||
16533                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16534                        SS.isEmpty()) {
16535               // This declaration is a reference to an existing entity, but
16536               // has different visibility from that entity: it either makes
16537               // a friend visible or it makes a type visible in a new module.
16538               // In either case, create a new declaration. We only do this if
16539               // the declaration would have meant the same thing if no prior
16540               // declaration were found, that is, if it was found in the same
16541               // scope where we would have injected a declaration.
16542               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16543                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16544                 return PrevTagDecl;
16545               // This is in the injected scope, create a new declaration in
16546               // that scope.
16547               S = getTagInjectionScope(S, getLangOpts());
16548             } else {
16549               return PrevTagDecl;
16550             }
16551           }
16552 
16553           // Diagnose attempts to redefine a tag.
16554           if (TUK == TUK_Definition) {
16555             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16556               // If we're defining a specialization and the previous definition
16557               // is from an implicit instantiation, don't emit an error
16558               // here; we'll catch this in the general case below.
16559               bool IsExplicitSpecializationAfterInstantiation = false;
16560               if (isMemberSpecialization) {
16561                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16562                   IsExplicitSpecializationAfterInstantiation =
16563                     RD->getTemplateSpecializationKind() !=
16564                     TSK_ExplicitSpecialization;
16565                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16566                   IsExplicitSpecializationAfterInstantiation =
16567                     ED->getTemplateSpecializationKind() !=
16568                     TSK_ExplicitSpecialization;
16569               }
16570 
16571               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16572               // not keep more that one definition around (merge them). However,
16573               // ensure the decl passes the structural compatibility check in
16574               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16575               NamedDecl *Hidden = nullptr;
16576               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16577                 // There is a definition of this tag, but it is not visible. We
16578                 // explicitly make use of C++'s one definition rule here, and
16579                 // assume that this definition is identical to the hidden one
16580                 // we already have. Make the existing definition visible and
16581                 // use it in place of this one.
16582                 if (!getLangOpts().CPlusPlus) {
16583                   // Postpone making the old definition visible until after we
16584                   // complete parsing the new one and do the structural
16585                   // comparison.
16586                   SkipBody->CheckSameAsPrevious = true;
16587                   SkipBody->New = createTagFromNewDecl();
16588                   SkipBody->Previous = Def;
16589                   return Def;
16590                 } else {
16591                   SkipBody->ShouldSkip = true;
16592                   SkipBody->Previous = Def;
16593                   makeMergedDefinitionVisible(Hidden);
16594                   // Carry on and handle it like a normal definition. We'll
16595                   // skip starting the definitiion later.
16596                 }
16597               } else if (!IsExplicitSpecializationAfterInstantiation) {
16598                 // A redeclaration in function prototype scope in C isn't
16599                 // visible elsewhere, so merely issue a warning.
16600                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16601                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16602                 else
16603                   Diag(NameLoc, diag::err_redefinition) << Name;
16604                 notePreviousDefinition(Def,
16605                                        NameLoc.isValid() ? NameLoc : KWLoc);
16606                 // If this is a redefinition, recover by making this
16607                 // struct be anonymous, which will make any later
16608                 // references get the previous definition.
16609                 Name = nullptr;
16610                 Previous.clear();
16611                 Invalid = true;
16612               }
16613             } else {
16614               // If the type is currently being defined, complain
16615               // about a nested redefinition.
16616               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16617               if (TD->isBeingDefined()) {
16618                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16619                 Diag(PrevTagDecl->getLocation(),
16620                      diag::note_previous_definition);
16621                 Name = nullptr;
16622                 Previous.clear();
16623                 Invalid = true;
16624               }
16625             }
16626 
16627             // Okay, this is definition of a previously declared or referenced
16628             // tag. We're going to create a new Decl for it.
16629           }
16630 
16631           // Okay, we're going to make a redeclaration.  If this is some kind
16632           // of reference, make sure we build the redeclaration in the same DC
16633           // as the original, and ignore the current access specifier.
16634           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16635             SearchDC = PrevTagDecl->getDeclContext();
16636             AS = AS_none;
16637           }
16638         }
16639         // If we get here we have (another) forward declaration or we
16640         // have a definition.  Just create a new decl.
16641 
16642       } else {
16643         // If we get here, this is a definition of a new tag type in a nested
16644         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16645         // new decl/type.  We set PrevDecl to NULL so that the entities
16646         // have distinct types.
16647         Previous.clear();
16648       }
16649       // If we get here, we're going to create a new Decl. If PrevDecl
16650       // is non-NULL, it's a definition of the tag declared by
16651       // PrevDecl. If it's NULL, we have a new definition.
16652 
16653     // Otherwise, PrevDecl is not a tag, but was found with tag
16654     // lookup.  This is only actually possible in C++, where a few
16655     // things like templates still live in the tag namespace.
16656     } else {
16657       // Use a better diagnostic if an elaborated-type-specifier
16658       // found the wrong kind of type on the first
16659       // (non-redeclaration) lookup.
16660       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16661           !Previous.isForRedeclaration()) {
16662         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16663         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16664                                                        << Kind;
16665         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16666         Invalid = true;
16667 
16668       // Otherwise, only diagnose if the declaration is in scope.
16669       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16670                                 SS.isNotEmpty() || isMemberSpecialization)) {
16671         // do nothing
16672 
16673       // Diagnose implicit declarations introduced by elaborated types.
16674       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16675         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16676         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16677         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16678         Invalid = true;
16679 
16680       // Otherwise it's a declaration.  Call out a particularly common
16681       // case here.
16682       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16683         unsigned Kind = 0;
16684         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16685         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16686           << Name << Kind << TND->getUnderlyingType();
16687         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16688         Invalid = true;
16689 
16690       // Otherwise, diagnose.
16691       } else {
16692         // The tag name clashes with something else in the target scope,
16693         // issue an error and recover by making this tag be anonymous.
16694         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16695         notePreviousDefinition(PrevDecl, NameLoc);
16696         Name = nullptr;
16697         Invalid = true;
16698       }
16699 
16700       // The existing declaration isn't relevant to us; we're in a
16701       // new scope, so clear out the previous declaration.
16702       Previous.clear();
16703     }
16704   }
16705 
16706 CreateNewDecl:
16707 
16708   TagDecl *PrevDecl = nullptr;
16709   if (Previous.isSingleResult())
16710     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16711 
16712   // If there is an identifier, use the location of the identifier as the
16713   // location of the decl, otherwise use the location of the struct/union
16714   // keyword.
16715   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16716 
16717   // Otherwise, create a new declaration. If there is a previous
16718   // declaration of the same entity, the two will be linked via
16719   // PrevDecl.
16720   TagDecl *New;
16721 
16722   if (Kind == TTK_Enum) {
16723     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16724     // enum X { A, B, C } D;    D should chain to X.
16725     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16726                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16727                            ScopedEnumUsesClassTag, IsFixed);
16728 
16729     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16730       StdAlignValT = cast<EnumDecl>(New);
16731 
16732     // If this is an undefined enum, warn.
16733     if (TUK != TUK_Definition && !Invalid) {
16734       TagDecl *Def;
16735       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16736         // C++0x: 7.2p2: opaque-enum-declaration.
16737         // Conflicts are diagnosed above. Do nothing.
16738       }
16739       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16740         Diag(Loc, diag::ext_forward_ref_enum_def)
16741           << New;
16742         Diag(Def->getLocation(), diag::note_previous_definition);
16743       } else {
16744         unsigned DiagID = diag::ext_forward_ref_enum;
16745         if (getLangOpts().MSVCCompat)
16746           DiagID = diag::ext_ms_forward_ref_enum;
16747         else if (getLangOpts().CPlusPlus)
16748           DiagID = diag::err_forward_ref_enum;
16749         Diag(Loc, DiagID);
16750       }
16751     }
16752 
16753     if (EnumUnderlying) {
16754       EnumDecl *ED = cast<EnumDecl>(New);
16755       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16756         ED->setIntegerTypeSourceInfo(TI);
16757       else
16758         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16759       ED->setPromotionType(ED->getIntegerType());
16760       assert(ED->isComplete() && "enum with type should be complete");
16761     }
16762   } else {
16763     // struct/union/class
16764 
16765     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16766     // struct X { int A; } D;    D should chain to X.
16767     if (getLangOpts().CPlusPlus) {
16768       // FIXME: Look for a way to use RecordDecl for simple structs.
16769       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16770                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16771 
16772       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16773         StdBadAlloc = cast<CXXRecordDecl>(New);
16774     } else
16775       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16776                                cast_or_null<RecordDecl>(PrevDecl));
16777   }
16778 
16779   // C++11 [dcl.type]p3:
16780   //   A type-specifier-seq shall not define a class or enumeration [...].
16781   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16782       TUK == TUK_Definition) {
16783     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16784       << Context.getTagDeclType(New);
16785     Invalid = true;
16786   }
16787 
16788   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16789       DC->getDeclKind() == Decl::Enum) {
16790     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16791       << Context.getTagDeclType(New);
16792     Invalid = true;
16793   }
16794 
16795   // Maybe add qualifier info.
16796   if (SS.isNotEmpty()) {
16797     if (SS.isSet()) {
16798       // If this is either a declaration or a definition, check the
16799       // nested-name-specifier against the current context.
16800       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16801           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16802                                        isMemberSpecialization))
16803         Invalid = true;
16804 
16805       New->setQualifierInfo(SS.getWithLocInContext(Context));
16806       if (TemplateParameterLists.size() > 0) {
16807         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16808       }
16809     }
16810     else
16811       Invalid = true;
16812   }
16813 
16814   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16815     // Add alignment attributes if necessary; these attributes are checked when
16816     // the ASTContext lays out the structure.
16817     //
16818     // It is important for implementing the correct semantics that this
16819     // happen here (in ActOnTag). The #pragma pack stack is
16820     // maintained as a result of parser callbacks which can occur at
16821     // many points during the parsing of a struct declaration (because
16822     // the #pragma tokens are effectively skipped over during the
16823     // parsing of the struct).
16824     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16825       AddAlignmentAttributesForRecord(RD);
16826       AddMsStructLayoutForRecord(RD);
16827     }
16828   }
16829 
16830   if (ModulePrivateLoc.isValid()) {
16831     if (isMemberSpecialization)
16832       Diag(New->getLocation(), diag::err_module_private_specialization)
16833         << 2
16834         << FixItHint::CreateRemoval(ModulePrivateLoc);
16835     // __module_private__ does not apply to local classes. However, we only
16836     // diagnose this as an error when the declaration specifiers are
16837     // freestanding. Here, we just ignore the __module_private__.
16838     else if (!SearchDC->isFunctionOrMethod())
16839       New->setModulePrivate();
16840   }
16841 
16842   // If this is a specialization of a member class (of a class template),
16843   // check the specialization.
16844   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16845     Invalid = true;
16846 
16847   // If we're declaring or defining a tag in function prototype scope in C,
16848   // note that this type can only be used within the function and add it to
16849   // the list of decls to inject into the function definition scope.
16850   if ((Name || Kind == TTK_Enum) &&
16851       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16852     if (getLangOpts().CPlusPlus) {
16853       // C++ [dcl.fct]p6:
16854       //   Types shall not be defined in return or parameter types.
16855       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16856         Diag(Loc, diag::err_type_defined_in_param_type)
16857             << Name;
16858         Invalid = true;
16859       }
16860     } else if (!PrevDecl) {
16861       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16862     }
16863   }
16864 
16865   if (Invalid)
16866     New->setInvalidDecl();
16867 
16868   // Set the lexical context. If the tag has a C++ scope specifier, the
16869   // lexical context will be different from the semantic context.
16870   New->setLexicalDeclContext(CurContext);
16871 
16872   // Mark this as a friend decl if applicable.
16873   // In Microsoft mode, a friend declaration also acts as a forward
16874   // declaration so we always pass true to setObjectOfFriendDecl to make
16875   // the tag name visible.
16876   if (TUK == TUK_Friend)
16877     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16878 
16879   // Set the access specifier.
16880   if (!Invalid && SearchDC->isRecord())
16881     SetMemberAccessSpecifier(New, PrevDecl, AS);
16882 
16883   if (PrevDecl)
16884     CheckRedeclarationInModule(New, PrevDecl);
16885 
16886   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16887     New->startDefinition();
16888 
16889   ProcessDeclAttributeList(S, New, Attrs);
16890   AddPragmaAttributes(S, New);
16891 
16892   // If this has an identifier, add it to the scope stack.
16893   if (TUK == TUK_Friend) {
16894     // We might be replacing an existing declaration in the lookup tables;
16895     // if so, borrow its access specifier.
16896     if (PrevDecl)
16897       New->setAccess(PrevDecl->getAccess());
16898 
16899     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16900     DC->makeDeclVisibleInContext(New);
16901     if (Name) // can be null along some error paths
16902       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16903         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16904   } else if (Name) {
16905     S = getNonFieldDeclScope(S);
16906     PushOnScopeChains(New, S, true);
16907   } else {
16908     CurContext->addDecl(New);
16909   }
16910 
16911   // If this is the C FILE type, notify the AST context.
16912   if (IdentifierInfo *II = New->getIdentifier())
16913     if (!New->isInvalidDecl() &&
16914         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16915         II->isStr("FILE"))
16916       Context.setFILEDecl(New);
16917 
16918   if (PrevDecl)
16919     mergeDeclAttributes(New, PrevDecl);
16920 
16921   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16922     inferGslOwnerPointerAttribute(CXXRD);
16923 
16924   // If there's a #pragma GCC visibility in scope, set the visibility of this
16925   // record.
16926   AddPushedVisibilityAttribute(New);
16927 
16928   if (isMemberSpecialization && !New->isInvalidDecl())
16929     CompleteMemberSpecialization(New, Previous);
16930 
16931   OwnedDecl = true;
16932   // In C++, don't return an invalid declaration. We can't recover well from
16933   // the cases where we make the type anonymous.
16934   if (Invalid && getLangOpts().CPlusPlus) {
16935     if (New->isBeingDefined())
16936       if (auto RD = dyn_cast<RecordDecl>(New))
16937         RD->completeDefinition();
16938     return nullptr;
16939   } else if (SkipBody && SkipBody->ShouldSkip) {
16940     return SkipBody->Previous;
16941   } else {
16942     return New;
16943   }
16944 }
16945 
16946 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16947   AdjustDeclIfTemplate(TagD);
16948   TagDecl *Tag = cast<TagDecl>(TagD);
16949 
16950   // Enter the tag context.
16951   PushDeclContext(S, Tag);
16952 
16953   ActOnDocumentableDecl(TagD);
16954 
16955   // If there's a #pragma GCC visibility in scope, set the visibility of this
16956   // record.
16957   AddPushedVisibilityAttribute(Tag);
16958 }
16959 
16960 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16961   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16962     return false;
16963 
16964   // Make the previous decl visible.
16965   makeMergedDefinitionVisible(SkipBody.Previous);
16966   return true;
16967 }
16968 
16969 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16970   assert(isa<ObjCContainerDecl>(IDecl) &&
16971          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16972   DeclContext *OCD = cast<DeclContext>(IDecl);
16973   assert(OCD->getLexicalParent() == CurContext &&
16974       "The next DeclContext should be lexically contained in the current one.");
16975   CurContext = OCD;
16976   return IDecl;
16977 }
16978 
16979 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16980                                            SourceLocation FinalLoc,
16981                                            bool IsFinalSpelledSealed,
16982                                            bool IsAbstract,
16983                                            SourceLocation LBraceLoc) {
16984   AdjustDeclIfTemplate(TagD);
16985   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16986 
16987   FieldCollector->StartClass();
16988 
16989   if (!Record->getIdentifier())
16990     return;
16991 
16992   if (IsAbstract)
16993     Record->markAbstract();
16994 
16995   if (FinalLoc.isValid()) {
16996     Record->addAttr(FinalAttr::Create(
16997         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16998         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16999   }
17000   // C++ [class]p2:
17001   //   [...] The class-name is also inserted into the scope of the
17002   //   class itself; this is known as the injected-class-name. For
17003   //   purposes of access checking, the injected-class-name is treated
17004   //   as if it were a public member name.
17005   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17006       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17007       Record->getLocation(), Record->getIdentifier(),
17008       /*PrevDecl=*/nullptr,
17009       /*DelayTypeCreation=*/true);
17010   Context.getTypeDeclType(InjectedClassName, Record);
17011   InjectedClassName->setImplicit();
17012   InjectedClassName->setAccess(AS_public);
17013   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17014       InjectedClassName->setDescribedClassTemplate(Template);
17015   PushOnScopeChains(InjectedClassName, S);
17016   assert(InjectedClassName->isInjectedClassName() &&
17017          "Broken injected-class-name");
17018 }
17019 
17020 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17021                                     SourceRange BraceRange) {
17022   AdjustDeclIfTemplate(TagD);
17023   TagDecl *Tag = cast<TagDecl>(TagD);
17024   Tag->setBraceRange(BraceRange);
17025 
17026   // Make sure we "complete" the definition even it is invalid.
17027   if (Tag->isBeingDefined()) {
17028     assert(Tag->isInvalidDecl() && "We should already have completed it");
17029     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17030       RD->completeDefinition();
17031   }
17032 
17033   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17034     FieldCollector->FinishClass();
17035     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17036       auto *Def = RD->getDefinition();
17037       assert(Def && "The record is expected to have a completed definition");
17038       unsigned NumInitMethods = 0;
17039       for (auto *Method : Def->methods()) {
17040         if (!Method->getIdentifier())
17041             continue;
17042         if (Method->getName() == "__init")
17043           NumInitMethods++;
17044       }
17045       if (NumInitMethods > 1 || !Def->hasInitMethod())
17046         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17047     }
17048   }
17049 
17050   // Exit this scope of this tag's definition.
17051   PopDeclContext();
17052 
17053   if (getCurLexicalContext()->isObjCContainer() &&
17054       Tag->getDeclContext()->isFileContext())
17055     Tag->setTopLevelDeclInObjCContainer();
17056 
17057   // Notify the consumer that we've defined a tag.
17058   if (!Tag->isInvalidDecl())
17059     Consumer.HandleTagDeclDefinition(Tag);
17060 
17061   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17062   // from XLs and instead matches the XL #pragma pack(1) behavior.
17063   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17064       AlignPackStack.hasValue()) {
17065     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17066     // Only diagnose #pragma align(packed).
17067     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17068       return;
17069     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17070     if (!RD)
17071       return;
17072     // Only warn if there is at least 1 bitfield member.
17073     if (llvm::any_of(RD->fields(),
17074                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17075       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17076   }
17077 }
17078 
17079 void Sema::ActOnObjCContainerFinishDefinition() {
17080   // Exit this scope of this interface definition.
17081   PopDeclContext();
17082 }
17083 
17084 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
17085   assert(DC == CurContext && "Mismatch of container contexts");
17086   OriginalLexicalContext = DC;
17087   ActOnObjCContainerFinishDefinition();
17088 }
17089 
17090 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
17091   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
17092   OriginalLexicalContext = nullptr;
17093 }
17094 
17095 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17096   AdjustDeclIfTemplate(TagD);
17097   TagDecl *Tag = cast<TagDecl>(TagD);
17098   Tag->setInvalidDecl();
17099 
17100   // Make sure we "complete" the definition even it is invalid.
17101   if (Tag->isBeingDefined()) {
17102     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17103       RD->completeDefinition();
17104   }
17105 
17106   // We're undoing ActOnTagStartDefinition here, not
17107   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17108   // the FieldCollector.
17109 
17110   PopDeclContext();
17111 }
17112 
17113 // Note that FieldName may be null for anonymous bitfields.
17114 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17115                                 IdentifierInfo *FieldName,
17116                                 QualType FieldTy, bool IsMsStruct,
17117                                 Expr *BitWidth, bool *ZeroWidth) {
17118   assert(BitWidth);
17119   if (BitWidth->containsErrors())
17120     return ExprError();
17121 
17122   // Default to true; that shouldn't confuse checks for emptiness
17123   if (ZeroWidth)
17124     *ZeroWidth = true;
17125 
17126   // C99 6.7.2.1p4 - verify the field type.
17127   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17128   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17129     // Handle incomplete and sizeless types with a specific error.
17130     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17131                                  diag::err_field_incomplete_or_sizeless))
17132       return ExprError();
17133     if (FieldName)
17134       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17135         << FieldName << FieldTy << BitWidth->getSourceRange();
17136     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17137       << FieldTy << BitWidth->getSourceRange();
17138   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17139                                              UPPC_BitFieldWidth))
17140     return ExprError();
17141 
17142   // If the bit-width is type- or value-dependent, don't try to check
17143   // it now.
17144   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17145     return BitWidth;
17146 
17147   llvm::APSInt Value;
17148   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17149   if (ICE.isInvalid())
17150     return ICE;
17151   BitWidth = ICE.get();
17152 
17153   if (Value != 0 && ZeroWidth)
17154     *ZeroWidth = false;
17155 
17156   // Zero-width bitfield is ok for anonymous field.
17157   if (Value == 0 && FieldName)
17158     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17159 
17160   if (Value.isSigned() && Value.isNegative()) {
17161     if (FieldName)
17162       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17163                << FieldName << toString(Value, 10);
17164     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17165       << toString(Value, 10);
17166   }
17167 
17168   // The size of the bit-field must not exceed our maximum permitted object
17169   // size.
17170   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17171     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17172            << !FieldName << FieldName << toString(Value, 10);
17173   }
17174 
17175   if (!FieldTy->isDependentType()) {
17176     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17177     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17178     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17179 
17180     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17181     // ABI.
17182     bool CStdConstraintViolation =
17183         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17184     bool MSBitfieldViolation =
17185         Value.ugt(TypeStorageSize) &&
17186         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17187     if (CStdConstraintViolation || MSBitfieldViolation) {
17188       unsigned DiagWidth =
17189           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17190       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17191              << (bool)FieldName << FieldName << toString(Value, 10)
17192              << !CStdConstraintViolation << DiagWidth;
17193     }
17194 
17195     // Warn on types where the user might conceivably expect to get all
17196     // specified bits as value bits: that's all integral types other than
17197     // 'bool'.
17198     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17199       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17200           << FieldName << toString(Value, 10)
17201           << (unsigned)TypeWidth;
17202     }
17203   }
17204 
17205   return BitWidth;
17206 }
17207 
17208 /// ActOnField - Each field of a C struct/union is passed into this in order
17209 /// to create a FieldDecl object for it.
17210 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17211                        Declarator &D, Expr *BitfieldWidth) {
17212   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17213                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17214                                /*InitStyle=*/ICIS_NoInit, AS_public);
17215   return Res;
17216 }
17217 
17218 /// HandleField - Analyze a field of a C struct or a C++ data member.
17219 ///
17220 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17221                              SourceLocation DeclStart,
17222                              Declarator &D, Expr *BitWidth,
17223                              InClassInitStyle InitStyle,
17224                              AccessSpecifier AS) {
17225   if (D.isDecompositionDeclarator()) {
17226     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17227     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17228       << Decomp.getSourceRange();
17229     return nullptr;
17230   }
17231 
17232   IdentifierInfo *II = D.getIdentifier();
17233   SourceLocation Loc = DeclStart;
17234   if (II) Loc = D.getIdentifierLoc();
17235 
17236   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17237   QualType T = TInfo->getType();
17238   if (getLangOpts().CPlusPlus) {
17239     CheckExtraCXXDefaultArguments(D);
17240 
17241     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17242                                         UPPC_DataMemberType)) {
17243       D.setInvalidType();
17244       T = Context.IntTy;
17245       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17246     }
17247   }
17248 
17249   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17250 
17251   if (D.getDeclSpec().isInlineSpecified())
17252     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17253         << getLangOpts().CPlusPlus17;
17254   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17255     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17256          diag::err_invalid_thread)
17257       << DeclSpec::getSpecifierName(TSCS);
17258 
17259   // Check to see if this name was declared as a member previously
17260   NamedDecl *PrevDecl = nullptr;
17261   LookupResult Previous(*this, II, Loc, LookupMemberName,
17262                         ForVisibleRedeclaration);
17263   LookupName(Previous, S);
17264   switch (Previous.getResultKind()) {
17265     case LookupResult::Found:
17266     case LookupResult::FoundUnresolvedValue:
17267       PrevDecl = Previous.getAsSingle<NamedDecl>();
17268       break;
17269 
17270     case LookupResult::FoundOverloaded:
17271       PrevDecl = Previous.getRepresentativeDecl();
17272       break;
17273 
17274     case LookupResult::NotFound:
17275     case LookupResult::NotFoundInCurrentInstantiation:
17276     case LookupResult::Ambiguous:
17277       break;
17278   }
17279   Previous.suppressDiagnostics();
17280 
17281   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17282     // Maybe we will complain about the shadowed template parameter.
17283     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17284     // Just pretend that we didn't see the previous declaration.
17285     PrevDecl = nullptr;
17286   }
17287 
17288   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17289     PrevDecl = nullptr;
17290 
17291   bool Mutable
17292     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17293   SourceLocation TSSL = D.getBeginLoc();
17294   FieldDecl *NewFD
17295     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17296                      TSSL, AS, PrevDecl, &D);
17297 
17298   if (NewFD->isInvalidDecl())
17299     Record->setInvalidDecl();
17300 
17301   if (D.getDeclSpec().isModulePrivateSpecified())
17302     NewFD->setModulePrivate();
17303 
17304   if (NewFD->isInvalidDecl() && PrevDecl) {
17305     // Don't introduce NewFD into scope; there's already something
17306     // with the same name in the same scope.
17307   } else if (II) {
17308     PushOnScopeChains(NewFD, S);
17309   } else
17310     Record->addDecl(NewFD);
17311 
17312   return NewFD;
17313 }
17314 
17315 /// Build a new FieldDecl and check its well-formedness.
17316 ///
17317 /// This routine builds a new FieldDecl given the fields name, type,
17318 /// record, etc. \p PrevDecl should refer to any previous declaration
17319 /// with the same name and in the same scope as the field to be
17320 /// created.
17321 ///
17322 /// \returns a new FieldDecl.
17323 ///
17324 /// \todo The Declarator argument is a hack. It will be removed once
17325 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17326                                 TypeSourceInfo *TInfo,
17327                                 RecordDecl *Record, SourceLocation Loc,
17328                                 bool Mutable, Expr *BitWidth,
17329                                 InClassInitStyle InitStyle,
17330                                 SourceLocation TSSL,
17331                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17332                                 Declarator *D) {
17333   IdentifierInfo *II = Name.getAsIdentifierInfo();
17334   bool InvalidDecl = false;
17335   if (D) InvalidDecl = D->isInvalidType();
17336 
17337   // If we receive a broken type, recover by assuming 'int' and
17338   // marking this declaration as invalid.
17339   if (T.isNull() || T->containsErrors()) {
17340     InvalidDecl = true;
17341     T = Context.IntTy;
17342   }
17343 
17344   QualType EltTy = Context.getBaseElementType(T);
17345   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17346     if (RequireCompleteSizedType(Loc, EltTy,
17347                                  diag::err_field_incomplete_or_sizeless)) {
17348       // Fields of incomplete type force their record to be invalid.
17349       Record->setInvalidDecl();
17350       InvalidDecl = true;
17351     } else {
17352       NamedDecl *Def;
17353       EltTy->isIncompleteType(&Def);
17354       if (Def && Def->isInvalidDecl()) {
17355         Record->setInvalidDecl();
17356         InvalidDecl = true;
17357       }
17358     }
17359   }
17360 
17361   // TR 18037 does not allow fields to be declared with address space
17362   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17363       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17364     Diag(Loc, diag::err_field_with_address_space);
17365     Record->setInvalidDecl();
17366     InvalidDecl = true;
17367   }
17368 
17369   if (LangOpts.OpenCL) {
17370     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17371     // used as structure or union field: image, sampler, event or block types.
17372     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17373         T->isBlockPointerType()) {
17374       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17375       Record->setInvalidDecl();
17376       InvalidDecl = true;
17377     }
17378     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17379     // is enabled.
17380     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17381                         "__cl_clang_bitfields", LangOpts)) {
17382       Diag(Loc, diag::err_opencl_bitfields);
17383       InvalidDecl = true;
17384     }
17385   }
17386 
17387   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17388   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17389       T.hasQualifiers()) {
17390     InvalidDecl = true;
17391     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17392   }
17393 
17394   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17395   // than a variably modified type.
17396   if (!InvalidDecl && T->isVariablyModifiedType()) {
17397     if (!tryToFixVariablyModifiedVarType(
17398             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17399       InvalidDecl = true;
17400   }
17401 
17402   // Fields can not have abstract class types
17403   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17404                                              diag::err_abstract_type_in_decl,
17405                                              AbstractFieldType))
17406     InvalidDecl = true;
17407 
17408   bool ZeroWidth = false;
17409   if (InvalidDecl)
17410     BitWidth = nullptr;
17411   // If this is declared as a bit-field, check the bit-field.
17412   if (BitWidth) {
17413     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17414                               &ZeroWidth).get();
17415     if (!BitWidth) {
17416       InvalidDecl = true;
17417       BitWidth = nullptr;
17418       ZeroWidth = false;
17419     }
17420   }
17421 
17422   // Check that 'mutable' is consistent with the type of the declaration.
17423   if (!InvalidDecl && Mutable) {
17424     unsigned DiagID = 0;
17425     if (T->isReferenceType())
17426       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17427                                         : diag::err_mutable_reference;
17428     else if (T.isConstQualified())
17429       DiagID = diag::err_mutable_const;
17430 
17431     if (DiagID) {
17432       SourceLocation ErrLoc = Loc;
17433       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17434         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17435       Diag(ErrLoc, DiagID);
17436       if (DiagID != diag::ext_mutable_reference) {
17437         Mutable = false;
17438         InvalidDecl = true;
17439       }
17440     }
17441   }
17442 
17443   // C++11 [class.union]p8 (DR1460):
17444   //   At most one variant member of a union may have a
17445   //   brace-or-equal-initializer.
17446   if (InitStyle != ICIS_NoInit)
17447     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17448 
17449   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17450                                        BitWidth, Mutable, InitStyle);
17451   if (InvalidDecl)
17452     NewFD->setInvalidDecl();
17453 
17454   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17455     Diag(Loc, diag::err_duplicate_member) << II;
17456     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17457     NewFD->setInvalidDecl();
17458   }
17459 
17460   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17461     if (Record->isUnion()) {
17462       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17463         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17464         if (RDecl->getDefinition()) {
17465           // C++ [class.union]p1: An object of a class with a non-trivial
17466           // constructor, a non-trivial copy constructor, a non-trivial
17467           // destructor, or a non-trivial copy assignment operator
17468           // cannot be a member of a union, nor can an array of such
17469           // objects.
17470           if (CheckNontrivialField(NewFD))
17471             NewFD->setInvalidDecl();
17472         }
17473       }
17474 
17475       // C++ [class.union]p1: If a union contains a member of reference type,
17476       // the program is ill-formed, except when compiling with MSVC extensions
17477       // enabled.
17478       if (EltTy->isReferenceType()) {
17479         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17480                                     diag::ext_union_member_of_reference_type :
17481                                     diag::err_union_member_of_reference_type)
17482           << NewFD->getDeclName() << EltTy;
17483         if (!getLangOpts().MicrosoftExt)
17484           NewFD->setInvalidDecl();
17485       }
17486     }
17487   }
17488 
17489   // FIXME: We need to pass in the attributes given an AST
17490   // representation, not a parser representation.
17491   if (D) {
17492     // FIXME: The current scope is almost... but not entirely... correct here.
17493     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17494 
17495     if (NewFD->hasAttrs())
17496       CheckAlignasUnderalignment(NewFD);
17497   }
17498 
17499   // In auto-retain/release, infer strong retension for fields of
17500   // retainable type.
17501   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17502     NewFD->setInvalidDecl();
17503 
17504   if (T.isObjCGCWeak())
17505     Diag(Loc, diag::warn_attribute_weak_on_field);
17506 
17507   // PPC MMA non-pointer types are not allowed as field types.
17508   if (Context.getTargetInfo().getTriple().isPPC64() &&
17509       CheckPPCMMAType(T, NewFD->getLocation()))
17510     NewFD->setInvalidDecl();
17511 
17512   NewFD->setAccess(AS);
17513   return NewFD;
17514 }
17515 
17516 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17517   assert(FD);
17518   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17519 
17520   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17521     return false;
17522 
17523   QualType EltTy = Context.getBaseElementType(FD->getType());
17524   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17525     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17526     if (RDecl->getDefinition()) {
17527       // We check for copy constructors before constructors
17528       // because otherwise we'll never get complaints about
17529       // copy constructors.
17530 
17531       CXXSpecialMember member = CXXInvalid;
17532       // We're required to check for any non-trivial constructors. Since the
17533       // implicit default constructor is suppressed if there are any
17534       // user-declared constructors, we just need to check that there is a
17535       // trivial default constructor and a trivial copy constructor. (We don't
17536       // worry about move constructors here, since this is a C++98 check.)
17537       if (RDecl->hasNonTrivialCopyConstructor())
17538         member = CXXCopyConstructor;
17539       else if (!RDecl->hasTrivialDefaultConstructor())
17540         member = CXXDefaultConstructor;
17541       else if (RDecl->hasNonTrivialCopyAssignment())
17542         member = CXXCopyAssignment;
17543       else if (RDecl->hasNonTrivialDestructor())
17544         member = CXXDestructor;
17545 
17546       if (member != CXXInvalid) {
17547         if (!getLangOpts().CPlusPlus11 &&
17548             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17549           // Objective-C++ ARC: it is an error to have a non-trivial field of
17550           // a union. However, system headers in Objective-C programs
17551           // occasionally have Objective-C lifetime objects within unions,
17552           // and rather than cause the program to fail, we make those
17553           // members unavailable.
17554           SourceLocation Loc = FD->getLocation();
17555           if (getSourceManager().isInSystemHeader(Loc)) {
17556             if (!FD->hasAttr<UnavailableAttr>())
17557               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17558                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17559             return false;
17560           }
17561         }
17562 
17563         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17564                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17565                diag::err_illegal_union_or_anon_struct_member)
17566           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17567         DiagnoseNontrivial(RDecl, member);
17568         return !getLangOpts().CPlusPlus11;
17569       }
17570     }
17571   }
17572 
17573   return false;
17574 }
17575 
17576 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17577 ///  AST enum value.
17578 static ObjCIvarDecl::AccessControl
17579 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17580   switch (ivarVisibility) {
17581   default: llvm_unreachable("Unknown visitibility kind");
17582   case tok::objc_private: return ObjCIvarDecl::Private;
17583   case tok::objc_public: return ObjCIvarDecl::Public;
17584   case tok::objc_protected: return ObjCIvarDecl::Protected;
17585   case tok::objc_package: return ObjCIvarDecl::Package;
17586   }
17587 }
17588 
17589 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17590 /// in order to create an IvarDecl object for it.
17591 Decl *Sema::ActOnIvar(Scope *S,
17592                                 SourceLocation DeclStart,
17593                                 Declarator &D, Expr *BitfieldWidth,
17594                                 tok::ObjCKeywordKind Visibility) {
17595 
17596   IdentifierInfo *II = D.getIdentifier();
17597   Expr *BitWidth = (Expr*)BitfieldWidth;
17598   SourceLocation Loc = DeclStart;
17599   if (II) Loc = D.getIdentifierLoc();
17600 
17601   // FIXME: Unnamed fields can be handled in various different ways, for
17602   // example, unnamed unions inject all members into the struct namespace!
17603 
17604   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17605   QualType T = TInfo->getType();
17606 
17607   if (BitWidth) {
17608     // 6.7.2.1p3, 6.7.2.1p4
17609     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17610     if (!BitWidth)
17611       D.setInvalidType();
17612   } else {
17613     // Not a bitfield.
17614 
17615     // validate II.
17616 
17617   }
17618   if (T->isReferenceType()) {
17619     Diag(Loc, diag::err_ivar_reference_type);
17620     D.setInvalidType();
17621   }
17622   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17623   // than a variably modified type.
17624   else if (T->isVariablyModifiedType()) {
17625     if (!tryToFixVariablyModifiedVarType(
17626             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17627       D.setInvalidType();
17628   }
17629 
17630   // Get the visibility (access control) for this ivar.
17631   ObjCIvarDecl::AccessControl ac =
17632     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17633                                         : ObjCIvarDecl::None;
17634   // Must set ivar's DeclContext to its enclosing interface.
17635   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17636   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17637     return nullptr;
17638   ObjCContainerDecl *EnclosingContext;
17639   if (ObjCImplementationDecl *IMPDecl =
17640       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17641     if (LangOpts.ObjCRuntime.isFragile()) {
17642     // Case of ivar declared in an implementation. Context is that of its class.
17643       EnclosingContext = IMPDecl->getClassInterface();
17644       assert(EnclosingContext && "Implementation has no class interface!");
17645     }
17646     else
17647       EnclosingContext = EnclosingDecl;
17648   } else {
17649     if (ObjCCategoryDecl *CDecl =
17650         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17651       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17652         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17653         return nullptr;
17654       }
17655     }
17656     EnclosingContext = EnclosingDecl;
17657   }
17658 
17659   // Construct the decl.
17660   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17661                                              DeclStart, Loc, II, T,
17662                                              TInfo, ac, (Expr *)BitfieldWidth);
17663 
17664   if (II) {
17665     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17666                                            ForVisibleRedeclaration);
17667     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17668         && !isa<TagDecl>(PrevDecl)) {
17669       Diag(Loc, diag::err_duplicate_member) << II;
17670       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17671       NewID->setInvalidDecl();
17672     }
17673   }
17674 
17675   // Process attributes attached to the ivar.
17676   ProcessDeclAttributes(S, NewID, D);
17677 
17678   if (D.isInvalidType())
17679     NewID->setInvalidDecl();
17680 
17681   // In ARC, infer 'retaining' for ivars of retainable type.
17682   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17683     NewID->setInvalidDecl();
17684 
17685   if (D.getDeclSpec().isModulePrivateSpecified())
17686     NewID->setModulePrivate();
17687 
17688   if (II) {
17689     // FIXME: When interfaces are DeclContexts, we'll need to add
17690     // these to the interface.
17691     S->AddDecl(NewID);
17692     IdResolver.AddDecl(NewID);
17693   }
17694 
17695   if (LangOpts.ObjCRuntime.isNonFragile() &&
17696       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17697     Diag(Loc, diag::warn_ivars_in_interface);
17698 
17699   return NewID;
17700 }
17701 
17702 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17703 /// class and class extensions. For every class \@interface and class
17704 /// extension \@interface, if the last ivar is a bitfield of any type,
17705 /// then add an implicit `char :0` ivar to the end of that interface.
17706 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17707                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17708   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17709     return;
17710 
17711   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17712   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17713 
17714   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17715     return;
17716   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17717   if (!ID) {
17718     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17719       if (!CD->IsClassExtension())
17720         return;
17721     }
17722     // No need to add this to end of @implementation.
17723     else
17724       return;
17725   }
17726   // All conditions are met. Add a new bitfield to the tail end of ivars.
17727   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17728   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17729 
17730   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17731                               DeclLoc, DeclLoc, nullptr,
17732                               Context.CharTy,
17733                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17734                                                                DeclLoc),
17735                               ObjCIvarDecl::Private, BW,
17736                               true);
17737   AllIvarDecls.push_back(Ivar);
17738 }
17739 
17740 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17741                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17742                        SourceLocation RBrac,
17743                        const ParsedAttributesView &Attrs) {
17744   assert(EnclosingDecl && "missing record or interface decl");
17745 
17746   // If this is an Objective-C @implementation or category and we have
17747   // new fields here we should reset the layout of the interface since
17748   // it will now change.
17749   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17750     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17751     switch (DC->getKind()) {
17752     default: break;
17753     case Decl::ObjCCategory:
17754       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17755       break;
17756     case Decl::ObjCImplementation:
17757       Context.
17758         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17759       break;
17760     }
17761   }
17762 
17763   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17764   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17765 
17766   // Start counting up the number of named members; make sure to include
17767   // members of anonymous structs and unions in the total.
17768   unsigned NumNamedMembers = 0;
17769   if (Record) {
17770     for (const auto *I : Record->decls()) {
17771       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17772         if (IFD->getDeclName())
17773           ++NumNamedMembers;
17774     }
17775   }
17776 
17777   // Verify that all the fields are okay.
17778   SmallVector<FieldDecl*, 32> RecFields;
17779 
17780   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17781        i != end; ++i) {
17782     FieldDecl *FD = cast<FieldDecl>(*i);
17783 
17784     // Get the type for the field.
17785     const Type *FDTy = FD->getType().getTypePtr();
17786 
17787     if (!FD->isAnonymousStructOrUnion()) {
17788       // Remember all fields written by the user.
17789       RecFields.push_back(FD);
17790     }
17791 
17792     // If the field is already invalid for some reason, don't emit more
17793     // diagnostics about it.
17794     if (FD->isInvalidDecl()) {
17795       EnclosingDecl->setInvalidDecl();
17796       continue;
17797     }
17798 
17799     // C99 6.7.2.1p2:
17800     //   A structure or union shall not contain a member with
17801     //   incomplete or function type (hence, a structure shall not
17802     //   contain an instance of itself, but may contain a pointer to
17803     //   an instance of itself), except that the last member of a
17804     //   structure with more than one named member may have incomplete
17805     //   array type; such a structure (and any union containing,
17806     //   possibly recursively, a member that is such a structure)
17807     //   shall not be a member of a structure or an element of an
17808     //   array.
17809     bool IsLastField = (i + 1 == Fields.end());
17810     if (FDTy->isFunctionType()) {
17811       // Field declared as a function.
17812       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17813         << FD->getDeclName();
17814       FD->setInvalidDecl();
17815       EnclosingDecl->setInvalidDecl();
17816       continue;
17817     } else if (FDTy->isIncompleteArrayType() &&
17818                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17819       if (Record) {
17820         // Flexible array member.
17821         // Microsoft and g++ is more permissive regarding flexible array.
17822         // It will accept flexible array in union and also
17823         // as the sole element of a struct/class.
17824         unsigned DiagID = 0;
17825         if (!Record->isUnion() && !IsLastField) {
17826           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17827             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17828           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17829           FD->setInvalidDecl();
17830           EnclosingDecl->setInvalidDecl();
17831           continue;
17832         } else if (Record->isUnion())
17833           DiagID = getLangOpts().MicrosoftExt
17834                        ? diag::ext_flexible_array_union_ms
17835                        : getLangOpts().CPlusPlus
17836                              ? diag::ext_flexible_array_union_gnu
17837                              : diag::err_flexible_array_union;
17838         else if (NumNamedMembers < 1)
17839           DiagID = getLangOpts().MicrosoftExt
17840                        ? diag::ext_flexible_array_empty_aggregate_ms
17841                        : getLangOpts().CPlusPlus
17842                              ? diag::ext_flexible_array_empty_aggregate_gnu
17843                              : diag::err_flexible_array_empty_aggregate;
17844 
17845         if (DiagID)
17846           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17847                                           << Record->getTagKind();
17848         // While the layout of types that contain virtual bases is not specified
17849         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17850         // virtual bases after the derived members.  This would make a flexible
17851         // array member declared at the end of an object not adjacent to the end
17852         // of the type.
17853         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17854           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17855               << FD->getDeclName() << Record->getTagKind();
17856         if (!getLangOpts().C99)
17857           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17858             << FD->getDeclName() << Record->getTagKind();
17859 
17860         // If the element type has a non-trivial destructor, we would not
17861         // implicitly destroy the elements, so disallow it for now.
17862         //
17863         // FIXME: GCC allows this. We should probably either implicitly delete
17864         // the destructor of the containing class, or just allow this.
17865         QualType BaseElem = Context.getBaseElementType(FD->getType());
17866         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17867           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17868             << FD->getDeclName() << FD->getType();
17869           FD->setInvalidDecl();
17870           EnclosingDecl->setInvalidDecl();
17871           continue;
17872         }
17873         // Okay, we have a legal flexible array member at the end of the struct.
17874         Record->setHasFlexibleArrayMember(true);
17875       } else {
17876         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17877         // unless they are followed by another ivar. That check is done
17878         // elsewhere, after synthesized ivars are known.
17879       }
17880     } else if (!FDTy->isDependentType() &&
17881                RequireCompleteSizedType(
17882                    FD->getLocation(), FD->getType(),
17883                    diag::err_field_incomplete_or_sizeless)) {
17884       // Incomplete type
17885       FD->setInvalidDecl();
17886       EnclosingDecl->setInvalidDecl();
17887       continue;
17888     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17889       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17890         // A type which contains a flexible array member is considered to be a
17891         // flexible array member.
17892         Record->setHasFlexibleArrayMember(true);
17893         if (!Record->isUnion()) {
17894           // If this is a struct/class and this is not the last element, reject
17895           // it.  Note that GCC supports variable sized arrays in the middle of
17896           // structures.
17897           if (!IsLastField)
17898             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17899               << FD->getDeclName() << FD->getType();
17900           else {
17901             // We support flexible arrays at the end of structs in
17902             // other structs as an extension.
17903             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17904               << FD->getDeclName();
17905           }
17906         }
17907       }
17908       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17909           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17910                                  diag::err_abstract_type_in_decl,
17911                                  AbstractIvarType)) {
17912         // Ivars can not have abstract class types
17913         FD->setInvalidDecl();
17914       }
17915       if (Record && FDTTy->getDecl()->hasObjectMember())
17916         Record->setHasObjectMember(true);
17917       if (Record && FDTTy->getDecl()->hasVolatileMember())
17918         Record->setHasVolatileMember(true);
17919     } else if (FDTy->isObjCObjectType()) {
17920       /// A field cannot be an Objective-c object
17921       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17922         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17923       QualType T = Context.getObjCObjectPointerType(FD->getType());
17924       FD->setType(T);
17925     } else if (Record && Record->isUnion() &&
17926                FD->getType().hasNonTrivialObjCLifetime() &&
17927                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17928                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17929                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17930                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17931       // For backward compatibility, fields of C unions declared in system
17932       // headers that have non-trivial ObjC ownership qualifications are marked
17933       // as unavailable unless the qualifier is explicit and __strong. This can
17934       // break ABI compatibility between programs compiled with ARC and MRR, but
17935       // is a better option than rejecting programs using those unions under
17936       // ARC.
17937       FD->addAttr(UnavailableAttr::CreateImplicit(
17938           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17939           FD->getLocation()));
17940     } else if (getLangOpts().ObjC &&
17941                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17942                !Record->hasObjectMember()) {
17943       if (FD->getType()->isObjCObjectPointerType() ||
17944           FD->getType().isObjCGCStrong())
17945         Record->setHasObjectMember(true);
17946       else if (Context.getAsArrayType(FD->getType())) {
17947         QualType BaseType = Context.getBaseElementType(FD->getType());
17948         if (BaseType->isRecordType() &&
17949             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17950           Record->setHasObjectMember(true);
17951         else if (BaseType->isObjCObjectPointerType() ||
17952                  BaseType.isObjCGCStrong())
17953                Record->setHasObjectMember(true);
17954       }
17955     }
17956 
17957     if (Record && !getLangOpts().CPlusPlus &&
17958         !shouldIgnoreForRecordTriviality(FD)) {
17959       QualType FT = FD->getType();
17960       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17961         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17962         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17963             Record->isUnion())
17964           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17965       }
17966       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17967       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17968         Record->setNonTrivialToPrimitiveCopy(true);
17969         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17970           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17971       }
17972       if (FT.isDestructedType()) {
17973         Record->setNonTrivialToPrimitiveDestroy(true);
17974         Record->setParamDestroyedInCallee(true);
17975         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17976           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17977       }
17978 
17979       if (const auto *RT = FT->getAs<RecordType>()) {
17980         if (RT->getDecl()->getArgPassingRestrictions() ==
17981             RecordDecl::APK_CanNeverPassInRegs)
17982           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17983       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17984         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17985     }
17986 
17987     if (Record && FD->getType().isVolatileQualified())
17988       Record->setHasVolatileMember(true);
17989     // Keep track of the number of named members.
17990     if (FD->getIdentifier())
17991       ++NumNamedMembers;
17992   }
17993 
17994   // Okay, we successfully defined 'Record'.
17995   if (Record) {
17996     bool Completed = false;
17997     if (CXXRecord) {
17998       if (!CXXRecord->isInvalidDecl()) {
17999         // Set access bits correctly on the directly-declared conversions.
18000         for (CXXRecordDecl::conversion_iterator
18001                I = CXXRecord->conversion_begin(),
18002                E = CXXRecord->conversion_end(); I != E; ++I)
18003           I.setAccess((*I)->getAccess());
18004       }
18005 
18006       // Add any implicitly-declared members to this class.
18007       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18008 
18009       if (!CXXRecord->isDependentType()) {
18010         if (!CXXRecord->isInvalidDecl()) {
18011           // If we have virtual base classes, we may end up finding multiple
18012           // final overriders for a given virtual function. Check for this
18013           // problem now.
18014           if (CXXRecord->getNumVBases()) {
18015             CXXFinalOverriderMap FinalOverriders;
18016             CXXRecord->getFinalOverriders(FinalOverriders);
18017 
18018             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18019                                              MEnd = FinalOverriders.end();
18020                  M != MEnd; ++M) {
18021               for (OverridingMethods::iterator SO = M->second.begin(),
18022                                             SOEnd = M->second.end();
18023                    SO != SOEnd; ++SO) {
18024                 assert(SO->second.size() > 0 &&
18025                        "Virtual function without overriding functions?");
18026                 if (SO->second.size() == 1)
18027                   continue;
18028 
18029                 // C++ [class.virtual]p2:
18030                 //   In a derived class, if a virtual member function of a base
18031                 //   class subobject has more than one final overrider the
18032                 //   program is ill-formed.
18033                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18034                   << (const NamedDecl *)M->first << Record;
18035                 Diag(M->first->getLocation(),
18036                      diag::note_overridden_virtual_function);
18037                 for (OverridingMethods::overriding_iterator
18038                           OM = SO->second.begin(),
18039                        OMEnd = SO->second.end();
18040                      OM != OMEnd; ++OM)
18041                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18042                     << (const NamedDecl *)M->first << OM->Method->getParent();
18043 
18044                 Record->setInvalidDecl();
18045               }
18046             }
18047             CXXRecord->completeDefinition(&FinalOverriders);
18048             Completed = true;
18049           }
18050         }
18051       }
18052     }
18053 
18054     if (!Completed)
18055       Record->completeDefinition();
18056 
18057     // Handle attributes before checking the layout.
18058     ProcessDeclAttributeList(S, Record, Attrs);
18059 
18060     // Maybe randomize the field order.
18061     if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() &&
18062         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18063         !Record->isRandomized()) {
18064       SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields());
18065       SmallVector<Decl *, 32> NewFieldOrdering;
18066       if (randstruct::randomizeStructureLayout(
18067               Context, Record->getNameAsString(), OrigFieldOrdering,
18068               NewFieldOrdering))
18069         Record->reorderFields(NewFieldOrdering);
18070     }
18071 
18072     // We may have deferred checking for a deleted destructor. Check now.
18073     if (CXXRecord) {
18074       auto *Dtor = CXXRecord->getDestructor();
18075       if (Dtor && Dtor->isImplicit() &&
18076           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18077         CXXRecord->setImplicitDestructorIsDeleted();
18078         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18079       }
18080     }
18081 
18082     if (Record->hasAttrs()) {
18083       CheckAlignasUnderalignment(Record);
18084 
18085       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18086         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18087                                            IA->getRange(), IA->getBestCase(),
18088                                            IA->getInheritanceModel());
18089     }
18090 
18091     // Check if the structure/union declaration is a type that can have zero
18092     // size in C. For C this is a language extension, for C++ it may cause
18093     // compatibility problems.
18094     bool CheckForZeroSize;
18095     if (!getLangOpts().CPlusPlus) {
18096       CheckForZeroSize = true;
18097     } else {
18098       // For C++ filter out types that cannot be referenced in C code.
18099       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18100       CheckForZeroSize =
18101           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18102           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18103           CXXRecord->isCLike();
18104     }
18105     if (CheckForZeroSize) {
18106       bool ZeroSize = true;
18107       bool IsEmpty = true;
18108       unsigned NonBitFields = 0;
18109       for (RecordDecl::field_iterator I = Record->field_begin(),
18110                                       E = Record->field_end();
18111            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18112         IsEmpty = false;
18113         if (I->isUnnamedBitfield()) {
18114           if (!I->isZeroLengthBitField(Context))
18115             ZeroSize = false;
18116         } else {
18117           ++NonBitFields;
18118           QualType FieldType = I->getType();
18119           if (FieldType->isIncompleteType() ||
18120               !Context.getTypeSizeInChars(FieldType).isZero())
18121             ZeroSize = false;
18122         }
18123       }
18124 
18125       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18126       // allowed in C++, but warn if its declaration is inside
18127       // extern "C" block.
18128       if (ZeroSize) {
18129         Diag(RecLoc, getLangOpts().CPlusPlus ?
18130                          diag::warn_zero_size_struct_union_in_extern_c :
18131                          diag::warn_zero_size_struct_union_compat)
18132           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18133       }
18134 
18135       // Structs without named members are extension in C (C99 6.7.2.1p7),
18136       // but are accepted by GCC.
18137       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18138         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18139                                diag::ext_no_named_members_in_struct_union)
18140           << Record->isUnion();
18141       }
18142     }
18143   } else {
18144     ObjCIvarDecl **ClsFields =
18145       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18146     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18147       ID->setEndOfDefinitionLoc(RBrac);
18148       // Add ivar's to class's DeclContext.
18149       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18150         ClsFields[i]->setLexicalDeclContext(ID);
18151         ID->addDecl(ClsFields[i]);
18152       }
18153       // Must enforce the rule that ivars in the base classes may not be
18154       // duplicates.
18155       if (ID->getSuperClass())
18156         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18157     } else if (ObjCImplementationDecl *IMPDecl =
18158                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18159       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18160       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18161         // Ivar declared in @implementation never belongs to the implementation.
18162         // Only it is in implementation's lexical context.
18163         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18164       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18165       IMPDecl->setIvarLBraceLoc(LBrac);
18166       IMPDecl->setIvarRBraceLoc(RBrac);
18167     } else if (ObjCCategoryDecl *CDecl =
18168                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18169       // case of ivars in class extension; all other cases have been
18170       // reported as errors elsewhere.
18171       // FIXME. Class extension does not have a LocEnd field.
18172       // CDecl->setLocEnd(RBrac);
18173       // Add ivar's to class extension's DeclContext.
18174       // Diagnose redeclaration of private ivars.
18175       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18176       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18177         if (IDecl) {
18178           if (const ObjCIvarDecl *ClsIvar =
18179               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18180             Diag(ClsFields[i]->getLocation(),
18181                  diag::err_duplicate_ivar_declaration);
18182             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18183             continue;
18184           }
18185           for (const auto *Ext : IDecl->known_extensions()) {
18186             if (const ObjCIvarDecl *ClsExtIvar
18187                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18188               Diag(ClsFields[i]->getLocation(),
18189                    diag::err_duplicate_ivar_declaration);
18190               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18191               continue;
18192             }
18193           }
18194         }
18195         ClsFields[i]->setLexicalDeclContext(CDecl);
18196         CDecl->addDecl(ClsFields[i]);
18197       }
18198       CDecl->setIvarLBraceLoc(LBrac);
18199       CDecl->setIvarRBraceLoc(RBrac);
18200     }
18201   }
18202 }
18203 
18204 /// Determine whether the given integral value is representable within
18205 /// the given type T.
18206 static bool isRepresentableIntegerValue(ASTContext &Context,
18207                                         llvm::APSInt &Value,
18208                                         QualType T) {
18209   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18210          "Integral type required!");
18211   unsigned BitWidth = Context.getIntWidth(T);
18212 
18213   if (Value.isUnsigned() || Value.isNonNegative()) {
18214     if (T->isSignedIntegerOrEnumerationType())
18215       --BitWidth;
18216     return Value.getActiveBits() <= BitWidth;
18217   }
18218   return Value.getMinSignedBits() <= BitWidth;
18219 }
18220 
18221 // Given an integral type, return the next larger integral type
18222 // (or a NULL type of no such type exists).
18223 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18224   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18225   // enum checking below.
18226   assert((T->isIntegralType(Context) ||
18227          T->isEnumeralType()) && "Integral type required!");
18228   const unsigned NumTypes = 4;
18229   QualType SignedIntegralTypes[NumTypes] = {
18230     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18231   };
18232   QualType UnsignedIntegralTypes[NumTypes] = {
18233     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18234     Context.UnsignedLongLongTy
18235   };
18236 
18237   unsigned BitWidth = Context.getTypeSize(T);
18238   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18239                                                         : UnsignedIntegralTypes;
18240   for (unsigned I = 0; I != NumTypes; ++I)
18241     if (Context.getTypeSize(Types[I]) > BitWidth)
18242       return Types[I];
18243 
18244   return QualType();
18245 }
18246 
18247 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18248                                           EnumConstantDecl *LastEnumConst,
18249                                           SourceLocation IdLoc,
18250                                           IdentifierInfo *Id,
18251                                           Expr *Val) {
18252   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18253   llvm::APSInt EnumVal(IntWidth);
18254   QualType EltTy;
18255 
18256   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18257     Val = nullptr;
18258 
18259   if (Val)
18260     Val = DefaultLvalueConversion(Val).get();
18261 
18262   if (Val) {
18263     if (Enum->isDependentType() || Val->isTypeDependent() ||
18264         Val->containsErrors())
18265       EltTy = Context.DependentTy;
18266     else {
18267       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18268       // underlying type, but do allow it in all other contexts.
18269       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18270         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18271         // constant-expression in the enumerator-definition shall be a converted
18272         // constant expression of the underlying type.
18273         EltTy = Enum->getIntegerType();
18274         ExprResult Converted =
18275           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18276                                            CCEK_Enumerator);
18277         if (Converted.isInvalid())
18278           Val = nullptr;
18279         else
18280           Val = Converted.get();
18281       } else if (!Val->isValueDependent() &&
18282                  !(Val =
18283                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18284                            .get())) {
18285         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18286       } else {
18287         if (Enum->isComplete()) {
18288           EltTy = Enum->getIntegerType();
18289 
18290           // In Obj-C and Microsoft mode, require the enumeration value to be
18291           // representable in the underlying type of the enumeration. In C++11,
18292           // we perform a non-narrowing conversion as part of converted constant
18293           // expression checking.
18294           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18295             if (Context.getTargetInfo()
18296                     .getTriple()
18297                     .isWindowsMSVCEnvironment()) {
18298               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18299             } else {
18300               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18301             }
18302           }
18303 
18304           // Cast to the underlying type.
18305           Val = ImpCastExprToType(Val, EltTy,
18306                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18307                                                          : CK_IntegralCast)
18308                     .get();
18309         } else if (getLangOpts().CPlusPlus) {
18310           // C++11 [dcl.enum]p5:
18311           //   If the underlying type is not fixed, the type of each enumerator
18312           //   is the type of its initializing value:
18313           //     - If an initializer is specified for an enumerator, the
18314           //       initializing value has the same type as the expression.
18315           EltTy = Val->getType();
18316         } else {
18317           // C99 6.7.2.2p2:
18318           //   The expression that defines the value of an enumeration constant
18319           //   shall be an integer constant expression that has a value
18320           //   representable as an int.
18321 
18322           // Complain if the value is not representable in an int.
18323           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18324             Diag(IdLoc, diag::ext_enum_value_not_int)
18325               << toString(EnumVal, 10) << Val->getSourceRange()
18326               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18327           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18328             // Force the type of the expression to 'int'.
18329             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18330           }
18331           EltTy = Val->getType();
18332         }
18333       }
18334     }
18335   }
18336 
18337   if (!Val) {
18338     if (Enum->isDependentType())
18339       EltTy = Context.DependentTy;
18340     else if (!LastEnumConst) {
18341       // C++0x [dcl.enum]p5:
18342       //   If the underlying type is not fixed, the type of each enumerator
18343       //   is the type of its initializing value:
18344       //     - If no initializer is specified for the first enumerator, the
18345       //       initializing value has an unspecified integral type.
18346       //
18347       // GCC uses 'int' for its unspecified integral type, as does
18348       // C99 6.7.2.2p3.
18349       if (Enum->isFixed()) {
18350         EltTy = Enum->getIntegerType();
18351       }
18352       else {
18353         EltTy = Context.IntTy;
18354       }
18355     } else {
18356       // Assign the last value + 1.
18357       EnumVal = LastEnumConst->getInitVal();
18358       ++EnumVal;
18359       EltTy = LastEnumConst->getType();
18360 
18361       // Check for overflow on increment.
18362       if (EnumVal < LastEnumConst->getInitVal()) {
18363         // C++0x [dcl.enum]p5:
18364         //   If the underlying type is not fixed, the type of each enumerator
18365         //   is the type of its initializing value:
18366         //
18367         //     - Otherwise the type of the initializing value is the same as
18368         //       the type of the initializing value of the preceding enumerator
18369         //       unless the incremented value is not representable in that type,
18370         //       in which case the type is an unspecified integral type
18371         //       sufficient to contain the incremented value. If no such type
18372         //       exists, the program is ill-formed.
18373         QualType T = getNextLargerIntegralType(Context, EltTy);
18374         if (T.isNull() || Enum->isFixed()) {
18375           // There is no integral type larger enough to represent this
18376           // value. Complain, then allow the value to wrap around.
18377           EnumVal = LastEnumConst->getInitVal();
18378           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18379           ++EnumVal;
18380           if (Enum->isFixed())
18381             // When the underlying type is fixed, this is ill-formed.
18382             Diag(IdLoc, diag::err_enumerator_wrapped)
18383               << toString(EnumVal, 10)
18384               << EltTy;
18385           else
18386             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18387               << toString(EnumVal, 10);
18388         } else {
18389           EltTy = T;
18390         }
18391 
18392         // Retrieve the last enumerator's value, extent that type to the
18393         // type that is supposed to be large enough to represent the incremented
18394         // value, then increment.
18395         EnumVal = LastEnumConst->getInitVal();
18396         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18397         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18398         ++EnumVal;
18399 
18400         // If we're not in C++, diagnose the overflow of enumerator values,
18401         // which in C99 means that the enumerator value is not representable in
18402         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18403         // permits enumerator values that are representable in some larger
18404         // integral type.
18405         if (!getLangOpts().CPlusPlus && !T.isNull())
18406           Diag(IdLoc, diag::warn_enum_value_overflow);
18407       } else if (!getLangOpts().CPlusPlus &&
18408                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18409         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18410         Diag(IdLoc, diag::ext_enum_value_not_int)
18411           << toString(EnumVal, 10) << 1;
18412       }
18413     }
18414   }
18415 
18416   if (!EltTy->isDependentType()) {
18417     // Make the enumerator value match the signedness and size of the
18418     // enumerator's type.
18419     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18420     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18421   }
18422 
18423   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18424                                   Val, EnumVal);
18425 }
18426 
18427 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18428                                                 SourceLocation IILoc) {
18429   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18430       !getLangOpts().CPlusPlus)
18431     return SkipBodyInfo();
18432 
18433   // We have an anonymous enum definition. Look up the first enumerator to
18434   // determine if we should merge the definition with an existing one and
18435   // skip the body.
18436   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18437                                          forRedeclarationInCurContext());
18438   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18439   if (!PrevECD)
18440     return SkipBodyInfo();
18441 
18442   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18443   NamedDecl *Hidden;
18444   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18445     SkipBodyInfo Skip;
18446     Skip.Previous = Hidden;
18447     return Skip;
18448   }
18449 
18450   return SkipBodyInfo();
18451 }
18452 
18453 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18454                               SourceLocation IdLoc, IdentifierInfo *Id,
18455                               const ParsedAttributesView &Attrs,
18456                               SourceLocation EqualLoc, Expr *Val) {
18457   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18458   EnumConstantDecl *LastEnumConst =
18459     cast_or_null<EnumConstantDecl>(lastEnumConst);
18460 
18461   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18462   // we find one that is.
18463   S = getNonFieldDeclScope(S);
18464 
18465   // Verify that there isn't already something declared with this name in this
18466   // scope.
18467   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18468   LookupName(R, S);
18469   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18470 
18471   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18472     // Maybe we will complain about the shadowed template parameter.
18473     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18474     // Just pretend that we didn't see the previous declaration.
18475     PrevDecl = nullptr;
18476   }
18477 
18478   // C++ [class.mem]p15:
18479   // If T is the name of a class, then each of the following shall have a name
18480   // different from T:
18481   // - every enumerator of every member of class T that is an unscoped
18482   // enumerated type
18483   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18484     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18485                             DeclarationNameInfo(Id, IdLoc));
18486 
18487   EnumConstantDecl *New =
18488     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18489   if (!New)
18490     return nullptr;
18491 
18492   if (PrevDecl) {
18493     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18494       // Check for other kinds of shadowing not already handled.
18495       CheckShadow(New, PrevDecl, R);
18496     }
18497 
18498     // When in C++, we may get a TagDecl with the same name; in this case the
18499     // enum constant will 'hide' the tag.
18500     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18501            "Received TagDecl when not in C++!");
18502     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18503       if (isa<EnumConstantDecl>(PrevDecl))
18504         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18505       else
18506         Diag(IdLoc, diag::err_redefinition) << Id;
18507       notePreviousDefinition(PrevDecl, IdLoc);
18508       return nullptr;
18509     }
18510   }
18511 
18512   // Process attributes.
18513   ProcessDeclAttributeList(S, New, Attrs);
18514   AddPragmaAttributes(S, New);
18515 
18516   // Register this decl in the current scope stack.
18517   New->setAccess(TheEnumDecl->getAccess());
18518   PushOnScopeChains(New, S);
18519 
18520   ActOnDocumentableDecl(New);
18521 
18522   return New;
18523 }
18524 
18525 // Returns true when the enum initial expression does not trigger the
18526 // duplicate enum warning.  A few common cases are exempted as follows:
18527 // Element2 = Element1
18528 // Element2 = Element1 + 1
18529 // Element2 = Element1 - 1
18530 // Where Element2 and Element1 are from the same enum.
18531 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18532   Expr *InitExpr = ECD->getInitExpr();
18533   if (!InitExpr)
18534     return true;
18535   InitExpr = InitExpr->IgnoreImpCasts();
18536 
18537   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18538     if (!BO->isAdditiveOp())
18539       return true;
18540     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18541     if (!IL)
18542       return true;
18543     if (IL->getValue() != 1)
18544       return true;
18545 
18546     InitExpr = BO->getLHS();
18547   }
18548 
18549   // This checks if the elements are from the same enum.
18550   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18551   if (!DRE)
18552     return true;
18553 
18554   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18555   if (!EnumConstant)
18556     return true;
18557 
18558   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18559       Enum)
18560     return true;
18561 
18562   return false;
18563 }
18564 
18565 // Emits a warning when an element is implicitly set a value that
18566 // a previous element has already been set to.
18567 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18568                                         EnumDecl *Enum, QualType EnumType) {
18569   // Avoid anonymous enums
18570   if (!Enum->getIdentifier())
18571     return;
18572 
18573   // Only check for small enums.
18574   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18575     return;
18576 
18577   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18578     return;
18579 
18580   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18581   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18582 
18583   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18584 
18585   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18586   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18587 
18588   // Use int64_t as a key to avoid needing special handling for map keys.
18589   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18590     llvm::APSInt Val = D->getInitVal();
18591     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18592   };
18593 
18594   DuplicatesVector DupVector;
18595   ValueToVectorMap EnumMap;
18596 
18597   // Populate the EnumMap with all values represented by enum constants without
18598   // an initializer.
18599   for (auto *Element : Elements) {
18600     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18601 
18602     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18603     // this constant.  Skip this enum since it may be ill-formed.
18604     if (!ECD) {
18605       return;
18606     }
18607 
18608     // Constants with initalizers are handled in the next loop.
18609     if (ECD->getInitExpr())
18610       continue;
18611 
18612     // Duplicate values are handled in the next loop.
18613     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18614   }
18615 
18616   if (EnumMap.size() == 0)
18617     return;
18618 
18619   // Create vectors for any values that has duplicates.
18620   for (auto *Element : Elements) {
18621     // The last loop returned if any constant was null.
18622     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18623     if (!ValidDuplicateEnum(ECD, Enum))
18624       continue;
18625 
18626     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18627     if (Iter == EnumMap.end())
18628       continue;
18629 
18630     DeclOrVector& Entry = Iter->second;
18631     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18632       // Ensure constants are different.
18633       if (D == ECD)
18634         continue;
18635 
18636       // Create new vector and push values onto it.
18637       auto Vec = std::make_unique<ECDVector>();
18638       Vec->push_back(D);
18639       Vec->push_back(ECD);
18640 
18641       // Update entry to point to the duplicates vector.
18642       Entry = Vec.get();
18643 
18644       // Store the vector somewhere we can consult later for quick emission of
18645       // diagnostics.
18646       DupVector.emplace_back(std::move(Vec));
18647       continue;
18648     }
18649 
18650     ECDVector *Vec = Entry.get<ECDVector*>();
18651     // Make sure constants are not added more than once.
18652     if (*Vec->begin() == ECD)
18653       continue;
18654 
18655     Vec->push_back(ECD);
18656   }
18657 
18658   // Emit diagnostics.
18659   for (const auto &Vec : DupVector) {
18660     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18661 
18662     // Emit warning for one enum constant.
18663     auto *FirstECD = Vec->front();
18664     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18665       << FirstECD << toString(FirstECD->getInitVal(), 10)
18666       << FirstECD->getSourceRange();
18667 
18668     // Emit one note for each of the remaining enum constants with
18669     // the same value.
18670     for (auto *ECD : llvm::drop_begin(*Vec))
18671       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18672         << ECD << toString(ECD->getInitVal(), 10)
18673         << ECD->getSourceRange();
18674   }
18675 }
18676 
18677 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18678                              bool AllowMask) const {
18679   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18680   assert(ED->isCompleteDefinition() && "expected enum definition");
18681 
18682   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18683   llvm::APInt &FlagBits = R.first->second;
18684 
18685   if (R.second) {
18686     for (auto *E : ED->enumerators()) {
18687       const auto &EVal = E->getInitVal();
18688       // Only single-bit enumerators introduce new flag values.
18689       if (EVal.isPowerOf2())
18690         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18691     }
18692   }
18693 
18694   // A value is in a flag enum if either its bits are a subset of the enum's
18695   // flag bits (the first condition) or we are allowing masks and the same is
18696   // true of its complement (the second condition). When masks are allowed, we
18697   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18698   //
18699   // While it's true that any value could be used as a mask, the assumption is
18700   // that a mask will have all of the insignificant bits set. Anything else is
18701   // likely a logic error.
18702   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18703   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18704 }
18705 
18706 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18707                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18708                          const ParsedAttributesView &Attrs) {
18709   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18710   QualType EnumType = Context.getTypeDeclType(Enum);
18711 
18712   ProcessDeclAttributeList(S, Enum, Attrs);
18713 
18714   if (Enum->isDependentType()) {
18715     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18716       EnumConstantDecl *ECD =
18717         cast_or_null<EnumConstantDecl>(Elements[i]);
18718       if (!ECD) continue;
18719 
18720       ECD->setType(EnumType);
18721     }
18722 
18723     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18724     return;
18725   }
18726 
18727   // TODO: If the result value doesn't fit in an int, it must be a long or long
18728   // long value.  ISO C does not support this, but GCC does as an extension,
18729   // emit a warning.
18730   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18731   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18732   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18733 
18734   // Verify that all the values are okay, compute the size of the values, and
18735   // reverse the list.
18736   unsigned NumNegativeBits = 0;
18737   unsigned NumPositiveBits = 0;
18738 
18739   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18740     EnumConstantDecl *ECD =
18741       cast_or_null<EnumConstantDecl>(Elements[i]);
18742     if (!ECD) continue;  // Already issued a diagnostic.
18743 
18744     const llvm::APSInt &InitVal = ECD->getInitVal();
18745 
18746     // Keep track of the size of positive and negative values.
18747     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18748       NumPositiveBits = std::max(NumPositiveBits,
18749                                  (unsigned)InitVal.getActiveBits());
18750     else
18751       NumNegativeBits = std::max(NumNegativeBits,
18752                                  (unsigned)InitVal.getMinSignedBits());
18753   }
18754 
18755   // Figure out the type that should be used for this enum.
18756   QualType BestType;
18757   unsigned BestWidth;
18758 
18759   // C++0x N3000 [conv.prom]p3:
18760   //   An rvalue of an unscoped enumeration type whose underlying
18761   //   type is not fixed can be converted to an rvalue of the first
18762   //   of the following types that can represent all the values of
18763   //   the enumeration: int, unsigned int, long int, unsigned long
18764   //   int, long long int, or unsigned long long int.
18765   // C99 6.4.4.3p2:
18766   //   An identifier declared as an enumeration constant has type int.
18767   // The C99 rule is modified by a gcc extension
18768   QualType BestPromotionType;
18769 
18770   bool Packed = Enum->hasAttr<PackedAttr>();
18771   // -fshort-enums is the equivalent to specifying the packed attribute on all
18772   // enum definitions.
18773   if (LangOpts.ShortEnums)
18774     Packed = true;
18775 
18776   // If the enum already has a type because it is fixed or dictated by the
18777   // target, promote that type instead of analyzing the enumerators.
18778   if (Enum->isComplete()) {
18779     BestType = Enum->getIntegerType();
18780     if (BestType->isPromotableIntegerType())
18781       BestPromotionType = Context.getPromotedIntegerType(BestType);
18782     else
18783       BestPromotionType = BestType;
18784 
18785     BestWidth = Context.getIntWidth(BestType);
18786   }
18787   else if (NumNegativeBits) {
18788     // If there is a negative value, figure out the smallest integer type (of
18789     // int/long/longlong) that fits.
18790     // If it's packed, check also if it fits a char or a short.
18791     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18792       BestType = Context.SignedCharTy;
18793       BestWidth = CharWidth;
18794     } else if (Packed && NumNegativeBits <= ShortWidth &&
18795                NumPositiveBits < ShortWidth) {
18796       BestType = Context.ShortTy;
18797       BestWidth = ShortWidth;
18798     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18799       BestType = Context.IntTy;
18800       BestWidth = IntWidth;
18801     } else {
18802       BestWidth = Context.getTargetInfo().getLongWidth();
18803 
18804       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18805         BestType = Context.LongTy;
18806       } else {
18807         BestWidth = Context.getTargetInfo().getLongLongWidth();
18808 
18809         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18810           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18811         BestType = Context.LongLongTy;
18812       }
18813     }
18814     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18815   } else {
18816     // If there is no negative value, figure out the smallest type that fits
18817     // all of the enumerator values.
18818     // If it's packed, check also if it fits a char or a short.
18819     if (Packed && NumPositiveBits <= CharWidth) {
18820       BestType = Context.UnsignedCharTy;
18821       BestPromotionType = Context.IntTy;
18822       BestWidth = CharWidth;
18823     } else if (Packed && NumPositiveBits <= ShortWidth) {
18824       BestType = Context.UnsignedShortTy;
18825       BestPromotionType = Context.IntTy;
18826       BestWidth = ShortWidth;
18827     } else if (NumPositiveBits <= IntWidth) {
18828       BestType = Context.UnsignedIntTy;
18829       BestWidth = IntWidth;
18830       BestPromotionType
18831         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18832                            ? Context.UnsignedIntTy : Context.IntTy;
18833     } else if (NumPositiveBits <=
18834                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18835       BestType = Context.UnsignedLongTy;
18836       BestPromotionType
18837         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18838                            ? Context.UnsignedLongTy : Context.LongTy;
18839     } else {
18840       BestWidth = Context.getTargetInfo().getLongLongWidth();
18841       assert(NumPositiveBits <= BestWidth &&
18842              "How could an initializer get larger than ULL?");
18843       BestType = Context.UnsignedLongLongTy;
18844       BestPromotionType
18845         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18846                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18847     }
18848   }
18849 
18850   // Loop over all of the enumerator constants, changing their types to match
18851   // the type of the enum if needed.
18852   for (auto *D : Elements) {
18853     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18854     if (!ECD) continue;  // Already issued a diagnostic.
18855 
18856     // Standard C says the enumerators have int type, but we allow, as an
18857     // extension, the enumerators to be larger than int size.  If each
18858     // enumerator value fits in an int, type it as an int, otherwise type it the
18859     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18860     // that X has type 'int', not 'unsigned'.
18861 
18862     // Determine whether the value fits into an int.
18863     llvm::APSInt InitVal = ECD->getInitVal();
18864 
18865     // If it fits into an integer type, force it.  Otherwise force it to match
18866     // the enum decl type.
18867     QualType NewTy;
18868     unsigned NewWidth;
18869     bool NewSign;
18870     if (!getLangOpts().CPlusPlus &&
18871         !Enum->isFixed() &&
18872         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18873       NewTy = Context.IntTy;
18874       NewWidth = IntWidth;
18875       NewSign = true;
18876     } else if (ECD->getType() == BestType) {
18877       // Already the right type!
18878       if (getLangOpts().CPlusPlus)
18879         // C++ [dcl.enum]p4: Following the closing brace of an
18880         // enum-specifier, each enumerator has the type of its
18881         // enumeration.
18882         ECD->setType(EnumType);
18883       continue;
18884     } else {
18885       NewTy = BestType;
18886       NewWidth = BestWidth;
18887       NewSign = BestType->isSignedIntegerOrEnumerationType();
18888     }
18889 
18890     // Adjust the APSInt value.
18891     InitVal = InitVal.extOrTrunc(NewWidth);
18892     InitVal.setIsSigned(NewSign);
18893     ECD->setInitVal(InitVal);
18894 
18895     // Adjust the Expr initializer and type.
18896     if (ECD->getInitExpr() &&
18897         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18898       ECD->setInitExpr(ImplicitCastExpr::Create(
18899           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18900           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18901     if (getLangOpts().CPlusPlus)
18902       // C++ [dcl.enum]p4: Following the closing brace of an
18903       // enum-specifier, each enumerator has the type of its
18904       // enumeration.
18905       ECD->setType(EnumType);
18906     else
18907       ECD->setType(NewTy);
18908   }
18909 
18910   Enum->completeDefinition(BestType, BestPromotionType,
18911                            NumPositiveBits, NumNegativeBits);
18912 
18913   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18914 
18915   if (Enum->isClosedFlag()) {
18916     for (Decl *D : Elements) {
18917       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18918       if (!ECD) continue;  // Already issued a diagnostic.
18919 
18920       llvm::APSInt InitVal = ECD->getInitVal();
18921       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18922           !IsValueInFlagEnum(Enum, InitVal, true))
18923         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18924           << ECD << Enum;
18925     }
18926   }
18927 
18928   // Now that the enum type is defined, ensure it's not been underaligned.
18929   if (Enum->hasAttrs())
18930     CheckAlignasUnderalignment(Enum);
18931 }
18932 
18933 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18934                                   SourceLocation StartLoc,
18935                                   SourceLocation EndLoc) {
18936   StringLiteral *AsmString = cast<StringLiteral>(expr);
18937 
18938   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18939                                                    AsmString, StartLoc,
18940                                                    EndLoc);
18941   CurContext->addDecl(New);
18942   return New;
18943 }
18944 
18945 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18946                                       IdentifierInfo* AliasName,
18947                                       SourceLocation PragmaLoc,
18948                                       SourceLocation NameLoc,
18949                                       SourceLocation AliasNameLoc) {
18950   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18951                                          LookupOrdinaryName);
18952   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18953                            AttributeCommonInfo::AS_Pragma);
18954   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18955       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18956 
18957   // If a declaration that:
18958   // 1) declares a function or a variable
18959   // 2) has external linkage
18960   // already exists, add a label attribute to it.
18961   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18962     if (isDeclExternC(PrevDecl))
18963       PrevDecl->addAttr(Attr);
18964     else
18965       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18966           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18967   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18968   } else
18969     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18970 }
18971 
18972 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18973                              SourceLocation PragmaLoc,
18974                              SourceLocation NameLoc) {
18975   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18976 
18977   if (PrevDecl) {
18978     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18979   } else {
18980     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18981   }
18982 }
18983 
18984 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18985                                 IdentifierInfo* AliasName,
18986                                 SourceLocation PragmaLoc,
18987                                 SourceLocation NameLoc,
18988                                 SourceLocation AliasNameLoc) {
18989   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18990                                     LookupOrdinaryName);
18991   WeakInfo W = WeakInfo(Name, NameLoc);
18992 
18993   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18994     if (!PrevDecl->hasAttr<AliasAttr>())
18995       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18996         DeclApplyPragmaWeak(TUScope, ND, W);
18997   } else {
18998     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18999   }
19000 }
19001 
19002 Decl *Sema::getObjCDeclContext() const {
19003   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19004 }
19005 
19006 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19007                                                      bool Final) {
19008   assert(FD && "Expected non-null FunctionDecl");
19009 
19010   // SYCL functions can be template, so we check if they have appropriate
19011   // attribute prior to checking if it is a template.
19012   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19013     return FunctionEmissionStatus::Emitted;
19014 
19015   // Templates are emitted when they're instantiated.
19016   if (FD->isDependentContext())
19017     return FunctionEmissionStatus::TemplateDiscarded;
19018 
19019   // Check whether this function is an externally visible definition.
19020   auto IsEmittedForExternalSymbol = [this, FD]() {
19021     // We have to check the GVA linkage of the function's *definition* -- if we
19022     // only have a declaration, we don't know whether or not the function will
19023     // be emitted, because (say) the definition could include "inline".
19024     FunctionDecl *Def = FD->getDefinition();
19025 
19026     return Def && !isDiscardableGVALinkage(
19027                       getASTContext().GetGVALinkageForFunction(Def));
19028   };
19029 
19030   if (LangOpts.OpenMPIsDevice) {
19031     // In OpenMP device mode we will not emit host only functions, or functions
19032     // we don't need due to their linkage.
19033     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19034         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19035     // DevTy may be changed later by
19036     //  #pragma omp declare target to(*) device_type(*).
19037     // Therefore DevTy having no value does not imply host. The emission status
19038     // will be checked again at the end of compilation unit with Final = true.
19039     if (DevTy.hasValue())
19040       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19041         return FunctionEmissionStatus::OMPDiscarded;
19042     // If we have an explicit value for the device type, or we are in a target
19043     // declare context, we need to emit all extern and used symbols.
19044     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
19045       if (IsEmittedForExternalSymbol())
19046         return FunctionEmissionStatus::Emitted;
19047     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19048     // we'll omit it.
19049     if (Final)
19050       return FunctionEmissionStatus::OMPDiscarded;
19051   } else if (LangOpts.OpenMP > 45) {
19052     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19053     // function. In 5.0, no_host was introduced which might cause a function to
19054     // be ommitted.
19055     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19056         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19057     if (DevTy.hasValue())
19058       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19059         return FunctionEmissionStatus::OMPDiscarded;
19060   }
19061 
19062   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19063     return FunctionEmissionStatus::Emitted;
19064 
19065   if (LangOpts.CUDA) {
19066     // When compiling for device, host functions are never emitted.  Similarly,
19067     // when compiling for host, device and global functions are never emitted.
19068     // (Technically, we do emit a host-side stub for global functions, but this
19069     // doesn't count for our purposes here.)
19070     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19071     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19072       return FunctionEmissionStatus::CUDADiscarded;
19073     if (!LangOpts.CUDAIsDevice &&
19074         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19075       return FunctionEmissionStatus::CUDADiscarded;
19076 
19077     if (IsEmittedForExternalSymbol())
19078       return FunctionEmissionStatus::Emitted;
19079   }
19080 
19081   // Otherwise, the function is known-emitted if it's in our set of
19082   // known-emitted functions.
19083   return FunctionEmissionStatus::Unknown;
19084 }
19085 
19086 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19087   // Host-side references to a __global__ function refer to the stub, so the
19088   // function itself is never emitted and therefore should not be marked.
19089   // If we have host fn calls kernel fn calls host+device, the HD function
19090   // does not get instantiated on the host. We model this by omitting at the
19091   // call to the kernel from the callgraph. This ensures that, when compiling
19092   // for host, only HD functions actually called from the host get marked as
19093   // known-emitted.
19094   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19095          IdentifyCUDATarget(Callee) == CFT_Global;
19096 }
19097