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 all language modes as functions without prototypes may not
938       // be supported.
939       if (getLangOpts().implicitFunctionsAllowed()) {
940         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
941           return NameClassification::NonType(D);
942       }
943     }
944 
945     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
946       // In C++20 onwards, this could be an ADL-only call to a function
947       // template, and we're required to assume that this is a template name.
948       //
949       // FIXME: Find a way to still do typo correction in this case.
950       TemplateName Template =
951           Context.getAssumedTemplateName(NameInfo.getName());
952       return NameClassification::UndeclaredTemplate(Template);
953     }
954 
955     // In C, we first see whether there is a tag type by the same name, in
956     // which case it's likely that the user just forgot to write "enum",
957     // "struct", or "union".
958     if (!getLangOpts().CPlusPlus && !SecondTry &&
959         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
960       break;
961     }
962 
963     // Perform typo correction to determine if there is another name that is
964     // close to this name.
965     if (!SecondTry && CCC) {
966       SecondTry = true;
967       if (TypoCorrection Corrected =
968               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
969                           &SS, *CCC, CTK_ErrorRecovery)) {
970         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
971         unsigned QualifiedDiag = diag::err_no_member_suggest;
972 
973         NamedDecl *FirstDecl = Corrected.getFoundDecl();
974         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
975         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
976             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
977           UnqualifiedDiag = diag::err_no_template_suggest;
978           QualifiedDiag = diag::err_no_member_template_suggest;
979         } else if (UnderlyingFirstDecl &&
980                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
981                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
982                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
983           UnqualifiedDiag = diag::err_unknown_typename_suggest;
984           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
985         }
986 
987         if (SS.isEmpty()) {
988           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
989         } else {// FIXME: is this even reachable? Test it.
990           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
991           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
992                                   Name->getName().equals(CorrectedStr);
993           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
994                                     << Name << computeDeclContext(SS, false)
995                                     << DroppedSpecifier << SS.getRange());
996         }
997 
998         // Update the name, so that the caller has the new name.
999         Name = Corrected.getCorrectionAsIdentifierInfo();
1000 
1001         // Typo correction corrected to a keyword.
1002         if (Corrected.isKeyword())
1003           return Name;
1004 
1005         // Also update the LookupResult...
1006         // FIXME: This should probably go away at some point
1007         Result.clear();
1008         Result.setLookupName(Corrected.getCorrection());
1009         if (FirstDecl)
1010           Result.addDecl(FirstDecl);
1011 
1012         // If we found an Objective-C instance variable, let
1013         // LookupInObjCMethod build the appropriate expression to
1014         // reference the ivar.
1015         // FIXME: This is a gross hack.
1016         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1017           DeclResult R =
1018               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1019           if (R.isInvalid())
1020             return NameClassification::Error();
1021           if (R.isUsable())
1022             return NameClassification::NonType(Ivar);
1023         }
1024 
1025         goto Corrected;
1026       }
1027     }
1028 
1029     // We failed to correct; just fall through and let the parser deal with it.
1030     Result.suppressDiagnostics();
1031     return NameClassification::Unknown();
1032 
1033   case LookupResult::NotFoundInCurrentInstantiation: {
1034     // We performed name lookup into the current instantiation, and there were
1035     // dependent bases, so we treat this result the same way as any other
1036     // dependent nested-name-specifier.
1037 
1038     // C++ [temp.res]p2:
1039     //   A name used in a template declaration or definition and that is
1040     //   dependent on a template-parameter is assumed not to name a type
1041     //   unless the applicable name lookup finds a type name or the name is
1042     //   qualified by the keyword typename.
1043     //
1044     // FIXME: If the next token is '<', we might want to ask the parser to
1045     // perform some heroics to see if we actually have a
1046     // template-argument-list, which would indicate a missing 'template'
1047     // keyword here.
1048     return NameClassification::DependentNonType();
1049   }
1050 
1051   case LookupResult::Found:
1052   case LookupResult::FoundOverloaded:
1053   case LookupResult::FoundUnresolvedValue:
1054     break;
1055 
1056   case LookupResult::Ambiguous:
1057     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1059                                       /*AllowDependent=*/false)) {
1060       // C++ [temp.local]p3:
1061       //   A lookup that finds an injected-class-name (10.2) can result in an
1062       //   ambiguity in certain cases (for example, if it is found in more than
1063       //   one base class). If all of the injected-class-names that are found
1064       //   refer to specializations of the same class template, and if the name
1065       //   is followed by a template-argument-list, the reference refers to the
1066       //   class template itself and not a specialization thereof, and is not
1067       //   ambiguous.
1068       //
1069       // This filtering can make an ambiguous result into an unambiguous one,
1070       // so try again after filtering out template names.
1071       FilterAcceptableTemplateNames(Result);
1072       if (!Result.isAmbiguous()) {
1073         IsFilteredTemplateName = true;
1074         break;
1075       }
1076     }
1077 
1078     // Diagnose the ambiguity and return an error.
1079     return NameClassification::Error();
1080   }
1081 
1082   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1083       (IsFilteredTemplateName ||
1084        hasAnyAcceptableTemplateNames(
1085            Result, /*AllowFunctionTemplates=*/true,
1086            /*AllowDependent=*/false,
1087            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1088                getLangOpts().CPlusPlus20))) {
1089     // C++ [temp.names]p3:
1090     //   After name lookup (3.4) finds that a name is a template-name or that
1091     //   an operator-function-id or a literal- operator-id refers to a set of
1092     //   overloaded functions any member of which is a function template if
1093     //   this is followed by a <, the < is always taken as the delimiter of a
1094     //   template-argument-list and never as the less-than operator.
1095     // C++2a [temp.names]p2:
1096     //   A name is also considered to refer to a template if it is an
1097     //   unqualified-id followed by a < and name lookup finds either one
1098     //   or more functions or finds nothing.
1099     if (!IsFilteredTemplateName)
1100       FilterAcceptableTemplateNames(Result);
1101 
1102     bool IsFunctionTemplate;
1103     bool IsVarTemplate;
1104     TemplateName Template;
1105     if (Result.end() - Result.begin() > 1) {
1106       IsFunctionTemplate = true;
1107       Template = Context.getOverloadedTemplateName(Result.begin(),
1108                                                    Result.end());
1109     } else if (!Result.empty()) {
1110       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1111           *Result.begin(), /*AllowFunctionTemplates=*/true,
1112           /*AllowDependent=*/false));
1113       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1114       IsVarTemplate = isa<VarTemplateDecl>(TD);
1115 
1116       UsingShadowDecl *FoundUsingShadow =
1117           dyn_cast<UsingShadowDecl>(*Result.begin());
1118       assert(!FoundUsingShadow ||
1119              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1120       Template =
1121           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1122       if (SS.isNotEmpty())
1123         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1124                                                     /*TemplateKeyword=*/false,
1125                                                     Template);
1126     } else {
1127       // All results were non-template functions. This is a function template
1128       // name.
1129       IsFunctionTemplate = true;
1130       Template = Context.getAssumedTemplateName(NameInfo.getName());
1131     }
1132 
1133     if (IsFunctionTemplate) {
1134       // Function templates always go through overload resolution, at which
1135       // point we'll perform the various checks (e.g., accessibility) we need
1136       // to based on which function we selected.
1137       Result.suppressDiagnostics();
1138 
1139       return NameClassification::FunctionTemplate(Template);
1140     }
1141 
1142     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1143                          : NameClassification::TypeTemplate(Template);
1144   }
1145 
1146   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1147     QualType T = Context.getTypeDeclType(Type);
1148     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1149       T = Context.getUsingType(USD, T);
1150 
1151     if (SS.isEmpty()) // No elaborated type, trivial location info
1152       return ParsedType::make(T);
1153 
1154     TypeLocBuilder Builder;
1155     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1156     T = getElaboratedType(ETK_None, SS, T);
1157     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1158     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1159     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1160     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1161   };
1162 
1163   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1164   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1165     DiagnoseUseOfDecl(Type, NameLoc);
1166     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1167     return BuildTypeFor(Type, *Result.begin());
1168   }
1169 
1170   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1171   if (!Class) {
1172     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1173     if (ObjCCompatibleAliasDecl *Alias =
1174             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1175       Class = Alias->getClassInterface();
1176   }
1177 
1178   if (Class) {
1179     DiagnoseUseOfDecl(Class, NameLoc);
1180 
1181     if (NextToken.is(tok::period)) {
1182       // Interface. <something> is parsed as a property reference expression.
1183       // Just return "unknown" as a fall-through for now.
1184       Result.suppressDiagnostics();
1185       return NameClassification::Unknown();
1186     }
1187 
1188     QualType T = Context.getObjCInterfaceType(Class);
1189     return ParsedType::make(T);
1190   }
1191 
1192   if (isa<ConceptDecl>(FirstDecl))
1193     return NameClassification::Concept(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1197     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1198     return NameClassification::Error();
1199   }
1200 
1201   // We can have a type template here if we're classifying a template argument.
1202   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1203       !isa<VarTemplateDecl>(FirstDecl))
1204     return NameClassification::TypeTemplate(
1205         TemplateName(cast<TemplateDecl>(FirstDecl)));
1206 
1207   // Check for a tag type hidden by a non-type decl in a few cases where it
1208   // seems likely a type is wanted instead of the non-type that was found.
1209   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1210   if ((NextToken.is(tok::identifier) ||
1211        (NextIsOp &&
1212         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1213       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1214     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1215     DiagnoseUseOfDecl(Type, NameLoc);
1216     return BuildTypeFor(Type, *Result.begin());
1217   }
1218 
1219   // If we already know which single declaration is referenced, just annotate
1220   // that declaration directly. Defer resolving even non-overloaded class
1221   // member accesses, as we need to defer certain access checks until we know
1222   // the context.
1223   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1224   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1225     return NameClassification::NonType(Result.getRepresentativeDecl());
1226 
1227   // Otherwise, this is an overload set that we will need to resolve later.
1228   Result.suppressDiagnostics();
1229   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1230       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1231       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1232       Result.begin(), Result.end()));
1233 }
1234 
1235 ExprResult
1236 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1237                                              SourceLocation NameLoc) {
1238   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1239   CXXScopeSpec SS;
1240   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1241   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1242 }
1243 
1244 ExprResult
1245 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1246                                             IdentifierInfo *Name,
1247                                             SourceLocation NameLoc,
1248                                             bool IsAddressOfOperand) {
1249   DeclarationNameInfo NameInfo(Name, NameLoc);
1250   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1251                                     NameInfo, IsAddressOfOperand,
1252                                     /*TemplateArgs=*/nullptr);
1253 }
1254 
1255 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1256                                               NamedDecl *Found,
1257                                               SourceLocation NameLoc,
1258                                               const Token &NextToken) {
1259   if (getCurMethodDecl() && SS.isEmpty())
1260     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1261       return BuildIvarRefExpr(S, NameLoc, Ivar);
1262 
1263   // Reconstruct the lookup result.
1264   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1265   Result.addDecl(Found);
1266   Result.resolveKind();
1267 
1268   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1269   return BuildDeclarationNameExpr(SS, Result, ADL);
1270 }
1271 
1272 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1273   // For an implicit class member access, transform the result into a member
1274   // access expression if necessary.
1275   auto *ULE = cast<UnresolvedLookupExpr>(E);
1276   if ((*ULE->decls_begin())->isCXXClassMember()) {
1277     CXXScopeSpec SS;
1278     SS.Adopt(ULE->getQualifierLoc());
1279 
1280     // Reconstruct the lookup result.
1281     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1282                         LookupOrdinaryName);
1283     Result.setNamingClass(ULE->getNamingClass());
1284     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1285       Result.addDecl(*I, I.getAccess());
1286     Result.resolveKind();
1287     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1288                                            nullptr, S);
1289   }
1290 
1291   // Otherwise, this is already in the form we needed, and no further checks
1292   // are necessary.
1293   return ULE;
1294 }
1295 
1296 Sema::TemplateNameKindForDiagnostics
1297 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1298   auto *TD = Name.getAsTemplateDecl();
1299   if (!TD)
1300     return TemplateNameKindForDiagnostics::DependentTemplate;
1301   if (isa<ClassTemplateDecl>(TD))
1302     return TemplateNameKindForDiagnostics::ClassTemplate;
1303   if (isa<FunctionTemplateDecl>(TD))
1304     return TemplateNameKindForDiagnostics::FunctionTemplate;
1305   if (isa<VarTemplateDecl>(TD))
1306     return TemplateNameKindForDiagnostics::VarTemplate;
1307   if (isa<TypeAliasTemplateDecl>(TD))
1308     return TemplateNameKindForDiagnostics::AliasTemplate;
1309   if (isa<TemplateTemplateParmDecl>(TD))
1310     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1311   if (isa<ConceptDecl>(TD))
1312     return TemplateNameKindForDiagnostics::Concept;
1313   return TemplateNameKindForDiagnostics::DependentTemplate;
1314 }
1315 
1316 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1317   assert(DC->getLexicalParent() == CurContext &&
1318       "The next DeclContext should be lexically contained in the current one.");
1319   CurContext = DC;
1320   S->setEntity(DC);
1321 }
1322 
1323 void Sema::PopDeclContext() {
1324   assert(CurContext && "DeclContext imbalance!");
1325 
1326   CurContext = CurContext->getLexicalParent();
1327   assert(CurContext && "Popped translation unit!");
1328 }
1329 
1330 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1331                                                                     Decl *D) {
1332   // Unlike PushDeclContext, the context to which we return is not necessarily
1333   // the containing DC of TD, because the new context will be some pre-existing
1334   // TagDecl definition instead of a fresh one.
1335   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1336   CurContext = cast<TagDecl>(D)->getDefinition();
1337   assert(CurContext && "skipping definition of undefined tag");
1338   // Start lookups from the parent of the current context; we don't want to look
1339   // into the pre-existing complete definition.
1340   S->setEntity(CurContext->getLookupParent());
1341   return Result;
1342 }
1343 
1344 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1345   CurContext = static_cast<decltype(CurContext)>(Context);
1346 }
1347 
1348 /// EnterDeclaratorContext - Used when we must lookup names in the context
1349 /// of a declarator's nested name specifier.
1350 ///
1351 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1352   // C++0x [basic.lookup.unqual]p13:
1353   //   A name used in the definition of a static data member of class
1354   //   X (after the qualified-id of the static member) is looked up as
1355   //   if the name was used in a member function of X.
1356   // C++0x [basic.lookup.unqual]p14:
1357   //   If a variable member of a namespace is defined outside of the
1358   //   scope of its namespace then any name used in the definition of
1359   //   the variable member (after the declarator-id) is looked up as
1360   //   if the definition of the variable member occurred in its
1361   //   namespace.
1362   // Both of these imply that we should push a scope whose context
1363   // is the semantic context of the declaration.  We can't use
1364   // PushDeclContext here because that context is not necessarily
1365   // lexically contained in the current context.  Fortunately,
1366   // the containing scope should have the appropriate information.
1367 
1368   assert(!S->getEntity() && "scope already has entity");
1369 
1370 #ifndef NDEBUG
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1374 #endif
1375 
1376   CurContext = DC;
1377   S->setEntity(DC);
1378 
1379   if (S->getParent()->isTemplateParamScope()) {
1380     // Also set the corresponding entities for all immediately-enclosing
1381     // template parameter scopes.
1382     EnterTemplatedContext(S->getParent(), DC);
1383   }
1384 }
1385 
1386 void Sema::ExitDeclaratorContext(Scope *S) {
1387   assert(S->getEntity() == CurContext && "Context imbalance!");
1388 
1389   // Switch back to the lexical context.  The safety of this is
1390   // enforced by an assert in EnterDeclaratorContext.
1391   Scope *Ancestor = S->getParent();
1392   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1393   CurContext = Ancestor->getEntity();
1394 
1395   // We don't need to do anything with the scope, which is going to
1396   // disappear.
1397 }
1398 
1399 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1400   assert(S->isTemplateParamScope() &&
1401          "expected to be initializing a template parameter scope");
1402 
1403   // C++20 [temp.local]p7:
1404   //   In the definition of a member of a class template that appears outside
1405   //   of the class template definition, the name of a member of the class
1406   //   template hides the name of a template-parameter of any enclosing class
1407   //   templates (but not a template-parameter of the member if the member is a
1408   //   class or function template).
1409   // C++20 [temp.local]p9:
1410   //   In the definition of a class template or in the definition of a member
1411   //   of such a template that appears outside of the template definition, for
1412   //   each non-dependent base class (13.8.2.1), if the name of the base class
1413   //   or the name of a member of the base class is the same as the name of a
1414   //   template-parameter, the base class name or member name hides the
1415   //   template-parameter name (6.4.10).
1416   //
1417   // This means that a template parameter scope should be searched immediately
1418   // after searching the DeclContext for which it is a template parameter
1419   // scope. For example, for
1420   //   template<typename T> template<typename U> template<typename V>
1421   //     void N::A<T>::B<U>::f(...)
1422   // we search V then B<U> (and base classes) then U then A<T> (and base
1423   // classes) then T then N then ::.
1424   unsigned ScopeDepth = getTemplateDepth(S);
1425   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1426     DeclContext *SearchDCAfterScope = DC;
1427     for (; DC; DC = DC->getLookupParent()) {
1428       if (const TemplateParameterList *TPL =
1429               cast<Decl>(DC)->getDescribedTemplateParams()) {
1430         unsigned DCDepth = TPL->getDepth() + 1;
1431         if (DCDepth > ScopeDepth)
1432           continue;
1433         if (ScopeDepth == DCDepth)
1434           SearchDCAfterScope = DC = DC->getLookupParent();
1435         break;
1436       }
1437     }
1438     S->setLookupEntity(SearchDCAfterScope);
1439   }
1440 }
1441 
1442 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1443   // We assume that the caller has already called
1444   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1445   FunctionDecl *FD = D->getAsFunction();
1446   if (!FD)
1447     return;
1448 
1449   // Same implementation as PushDeclContext, but enters the context
1450   // from the lexical parent, rather than the top-level class.
1451   assert(CurContext == FD->getLexicalParent() &&
1452     "The next DeclContext should be lexically contained in the current one.");
1453   CurContext = FD;
1454   S->setEntity(CurContext);
1455 
1456   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1457     ParmVarDecl *Param = FD->getParamDecl(P);
1458     // If the parameter has an identifier, then add it to the scope
1459     if (Param->getIdentifier()) {
1460       S->AddDecl(Param);
1461       IdResolver.AddDecl(Param);
1462     }
1463   }
1464 }
1465 
1466 void Sema::ActOnExitFunctionContext() {
1467   // Same implementation as PopDeclContext, but returns to the lexical parent,
1468   // rather than the top-level class.
1469   assert(CurContext && "DeclContext imbalance!");
1470   CurContext = CurContext->getLexicalParent();
1471   assert(CurContext && "Popped translation unit!");
1472 }
1473 
1474 /// Determine whether overloading is allowed for a new function
1475 /// declaration considering prior declarations of the same name.
1476 ///
1477 /// This routine determines whether overloading is possible, not
1478 /// whether a new declaration actually overloads a previous one.
1479 /// It will return true in C++ (where overloads are alway permitted)
1480 /// or, as a C extension, when either the new declaration or a
1481 /// previous one is declared with the 'overloadable' attribute.
1482 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1483                                        ASTContext &Context,
1484                                        const FunctionDecl *New) {
1485   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1486     return true;
1487 
1488   // Multiversion function declarations are not overloads in the
1489   // usual sense of that term, but lookup will report that an
1490   // overload set was found if more than one multiversion function
1491   // declaration is present for the same name. It is therefore
1492   // inadequate to assume that some prior declaration(s) had
1493   // the overloadable attribute; checking is required. Since one
1494   // declaration is permitted to omit the attribute, it is necessary
1495   // to check at least two; hence the 'any_of' check below. Note that
1496   // the overloadable attribute is implicitly added to declarations
1497   // that were required to have it but did not.
1498   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1499     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1500       return ND->hasAttr<OverloadableAttr>();
1501     });
1502   } else if (Previous.getResultKind() == LookupResult::Found)
1503     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1504 
1505   return false;
1506 }
1507 
1508 /// Add this decl to the scope shadowed decl chains.
1509 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1510   // Move up the scope chain until we find the nearest enclosing
1511   // non-transparent context. The declaration will be introduced into this
1512   // scope.
1513   while (S->getEntity() && S->getEntity()->isTransparentContext())
1514     S = S->getParent();
1515 
1516   // Add scoped declarations into their context, so that they can be
1517   // found later. Declarations without a context won't be inserted
1518   // into any context.
1519   if (AddToContext)
1520     CurContext->addDecl(D);
1521 
1522   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1523   // are function-local declarations.
1524   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1525     return;
1526 
1527   // Template instantiations should also not be pushed into scope.
1528   if (isa<FunctionDecl>(D) &&
1529       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1530     return;
1531 
1532   // If this replaces anything in the current scope,
1533   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1534                                IEnd = IdResolver.end();
1535   for (; I != IEnd; ++I) {
1536     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1537       S->RemoveDecl(*I);
1538       IdResolver.RemoveDecl(*I);
1539 
1540       // Should only need to replace one decl.
1541       break;
1542     }
1543   }
1544 
1545   S->AddDecl(D);
1546 
1547   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1548     // Implicitly-generated labels may end up getting generated in an order that
1549     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1550     // the label at the appropriate place in the identifier chain.
1551     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1552       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1553       if (IDC == CurContext) {
1554         if (!S->isDeclScope(*I))
1555           continue;
1556       } else if (IDC->Encloses(CurContext))
1557         break;
1558     }
1559 
1560     IdResolver.InsertDeclAfter(I, D);
1561   } else {
1562     IdResolver.AddDecl(D);
1563   }
1564   warnOnReservedIdentifier(D);
1565 }
1566 
1567 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1568                          bool AllowInlineNamespace) {
1569   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1570 }
1571 
1572 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1573   DeclContext *TargetDC = DC->getPrimaryContext();
1574   do {
1575     if (DeclContext *ScopeDC = S->getEntity())
1576       if (ScopeDC->getPrimaryContext() == TargetDC)
1577         return S;
1578   } while ((S = S->getParent()));
1579 
1580   return nullptr;
1581 }
1582 
1583 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1584                                             DeclContext*,
1585                                             ASTContext&);
1586 
1587 /// Filters out lookup results that don't fall within the given scope
1588 /// as determined by isDeclInScope.
1589 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1590                                 bool ConsiderLinkage,
1591                                 bool AllowInlineNamespace) {
1592   LookupResult::Filter F = R.makeFilter();
1593   while (F.hasNext()) {
1594     NamedDecl *D = F.next();
1595 
1596     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1597       continue;
1598 
1599     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1600       continue;
1601 
1602     F.erase();
1603   }
1604 
1605   F.done();
1606 }
1607 
1608 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1609 /// have compatible owning modules.
1610 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1611   // [module.interface]p7:
1612   // A declaration is attached to a module as follows:
1613   // - If the declaration is a non-dependent friend declaration that nominates a
1614   // function with a declarator-id that is a qualified-id or template-id or that
1615   // nominates a class other than with an elaborated-type-specifier with neither
1616   // a nested-name-specifier nor a simple-template-id, it is attached to the
1617   // module to which the friend is attached ([basic.link]).
1618   if (New->getFriendObjectKind() &&
1619       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1620     New->setLocalOwningModule(Old->getOwningModule());
1621     makeMergedDefinitionVisible(New);
1622     return false;
1623   }
1624 
1625   Module *NewM = New->getOwningModule();
1626   Module *OldM = Old->getOwningModule();
1627 
1628   if (NewM && NewM->isPrivateModule())
1629     NewM = NewM->Parent;
1630   if (OldM && OldM->isPrivateModule())
1631     OldM = OldM->Parent;
1632 
1633   if (NewM == OldM)
1634     return false;
1635 
1636   // Partitions are part of the module, but a partition could import another
1637   // module, so verify that the PMIs agree.
1638   if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition()))
1639     return NewM->getPrimaryModuleInterfaceName() ==
1640            OldM->getPrimaryModuleInterfaceName();
1641 
1642   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1643   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1644   if (NewIsModuleInterface || OldIsModuleInterface) {
1645     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1646     //   if a declaration of D [...] appears in the purview of a module, all
1647     //   other such declarations shall appear in the purview of the same module
1648     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1649       << New
1650       << NewIsModuleInterface
1651       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1652       << OldIsModuleInterface
1653       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1654     Diag(Old->getLocation(), diag::note_previous_declaration);
1655     New->setInvalidDecl();
1656     return true;
1657   }
1658 
1659   return false;
1660 }
1661 
1662 // [module.interface]p6:
1663 // A redeclaration of an entity X is implicitly exported if X was introduced by
1664 // an exported declaration; otherwise it shall not be exported.
1665 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1666   // [module.interface]p1:
1667   // An export-declaration shall inhabit a namespace scope.
1668   //
1669   // So it is meaningless to talk about redeclaration which is not at namespace
1670   // scope.
1671   if (!New->getLexicalDeclContext()
1672            ->getNonTransparentContext()
1673            ->isFileContext() ||
1674       !Old->getLexicalDeclContext()
1675            ->getNonTransparentContext()
1676            ->isFileContext())
1677     return false;
1678 
1679   bool IsNewExported = New->isInExportDeclContext();
1680   bool IsOldExported = Old->isInExportDeclContext();
1681 
1682   // It should be irrevelant if both of them are not exported.
1683   if (!IsNewExported && !IsOldExported)
1684     return false;
1685 
1686   if (IsOldExported)
1687     return false;
1688 
1689   assert(IsNewExported);
1690 
1691   auto Lk = Old->getFormalLinkage();
1692   int S = 0;
1693   if (Lk == Linkage::InternalLinkage)
1694     S = 1;
1695   else if (Lk == Linkage::ModuleLinkage)
1696     S = 2;
1697   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1698   Diag(Old->getLocation(), diag::note_previous_declaration);
1699   return true;
1700 }
1701 
1702 // A wrapper function for checking the semantic restrictions of
1703 // a redeclaration within a module.
1704 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1705   if (CheckRedeclarationModuleOwnership(New, Old))
1706     return true;
1707 
1708   if (CheckRedeclarationExported(New, Old))
1709     return true;
1710 
1711   return false;
1712 }
1713 
1714 static bool isUsingDecl(NamedDecl *D) {
1715   return isa<UsingShadowDecl>(D) ||
1716          isa<UnresolvedUsingTypenameDecl>(D) ||
1717          isa<UnresolvedUsingValueDecl>(D);
1718 }
1719 
1720 /// Removes using shadow declarations from the lookup results.
1721 static void RemoveUsingDecls(LookupResult &R) {
1722   LookupResult::Filter F = R.makeFilter();
1723   while (F.hasNext())
1724     if (isUsingDecl(F.next()))
1725       F.erase();
1726 
1727   F.done();
1728 }
1729 
1730 /// Check for this common pattern:
1731 /// @code
1732 /// class S {
1733 ///   S(const S&); // DO NOT IMPLEMENT
1734 ///   void operator=(const S&); // DO NOT IMPLEMENT
1735 /// };
1736 /// @endcode
1737 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1738   // FIXME: Should check for private access too but access is set after we get
1739   // the decl here.
1740   if (D->doesThisDeclarationHaveABody())
1741     return false;
1742 
1743   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1744     return CD->isCopyConstructor();
1745   return D->isCopyAssignmentOperator();
1746 }
1747 
1748 // We need this to handle
1749 //
1750 // typedef struct {
1751 //   void *foo() { return 0; }
1752 // } A;
1753 //
1754 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1755 // for example. If 'A', foo will have external linkage. If we have '*A',
1756 // foo will have no linkage. Since we can't know until we get to the end
1757 // of the typedef, this function finds out if D might have non-external linkage.
1758 // Callers should verify at the end of the TU if it D has external linkage or
1759 // not.
1760 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1761   const DeclContext *DC = D->getDeclContext();
1762   while (!DC->isTranslationUnit()) {
1763     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1764       if (!RD->hasNameForLinkage())
1765         return true;
1766     }
1767     DC = DC->getParent();
1768   }
1769 
1770   return !D->isExternallyVisible();
1771 }
1772 
1773 // FIXME: This needs to be refactored; some other isInMainFile users want
1774 // these semantics.
1775 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1776   if (S.TUKind != TU_Complete)
1777     return false;
1778   return S.SourceMgr.isInMainFile(Loc);
1779 }
1780 
1781 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1782   assert(D);
1783 
1784   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1785     return false;
1786 
1787   // Ignore all entities declared within templates, and out-of-line definitions
1788   // of members of class templates.
1789   if (D->getDeclContext()->isDependentContext() ||
1790       D->getLexicalDeclContext()->isDependentContext())
1791     return false;
1792 
1793   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1794     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1795       return false;
1796     // A non-out-of-line declaration of a member specialization was implicitly
1797     // instantiated; it's the out-of-line declaration that we're interested in.
1798     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1799         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1800       return false;
1801 
1802     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1803       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1804         return false;
1805     } else {
1806       // 'static inline' functions are defined in headers; don't warn.
1807       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1808         return false;
1809     }
1810 
1811     if (FD->doesThisDeclarationHaveABody() &&
1812         Context.DeclMustBeEmitted(FD))
1813       return false;
1814   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1815     // Constants and utility variables are defined in headers with internal
1816     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1817     // like "inline".)
1818     if (!isMainFileLoc(*this, VD->getLocation()))
1819       return false;
1820 
1821     if (Context.DeclMustBeEmitted(VD))
1822       return false;
1823 
1824     if (VD->isStaticDataMember() &&
1825         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1826       return false;
1827     if (VD->isStaticDataMember() &&
1828         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1829         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1830       return false;
1831 
1832     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1833       return false;
1834   } else {
1835     return false;
1836   }
1837 
1838   // Only warn for unused decls internal to the translation unit.
1839   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1840   // for inline functions defined in the main source file, for instance.
1841   return mightHaveNonExternalLinkage(D);
1842 }
1843 
1844 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1845   if (!D)
1846     return;
1847 
1848   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1849     const FunctionDecl *First = FD->getFirstDecl();
1850     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1851       return; // First should already be in the vector.
1852   }
1853 
1854   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1855     const VarDecl *First = VD->getFirstDecl();
1856     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1857       return; // First should already be in the vector.
1858   }
1859 
1860   if (ShouldWarnIfUnusedFileScopedDecl(D))
1861     UnusedFileScopedDecls.push_back(D);
1862 }
1863 
1864 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1865   if (D->isInvalidDecl())
1866     return false;
1867 
1868   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1869     // For a decomposition declaration, warn if none of the bindings are
1870     // referenced, instead of if the variable itself is referenced (which
1871     // it is, by the bindings' expressions).
1872     for (auto *BD : DD->bindings())
1873       if (BD->isReferenced())
1874         return false;
1875   } else if (!D->getDeclName()) {
1876     return false;
1877   } else if (D->isReferenced() || D->isUsed()) {
1878     return false;
1879   }
1880 
1881   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1882     return false;
1883 
1884   if (isa<LabelDecl>(D))
1885     return true;
1886 
1887   // Except for labels, we only care about unused decls that are local to
1888   // functions.
1889   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1890   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1891     // For dependent types, the diagnostic is deferred.
1892     WithinFunction =
1893         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1894   if (!WithinFunction)
1895     return false;
1896 
1897   if (isa<TypedefNameDecl>(D))
1898     return true;
1899 
1900   // White-list anything that isn't a local variable.
1901   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1902     return false;
1903 
1904   // Types of valid local variables should be complete, so this should succeed.
1905   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906 
1907     const Expr *Init = VD->getInit();
1908     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1909       Init = Cleanups->getSubExpr();
1910 
1911     const auto *Ty = VD->getType().getTypePtr();
1912 
1913     // Only look at the outermost level of typedef.
1914     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1915       // Allow anything marked with __attribute__((unused)).
1916       if (TT->getDecl()->hasAttr<UnusedAttr>())
1917         return false;
1918     }
1919 
1920     // Warn for reference variables whose initializtion performs lifetime
1921     // extension.
1922     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1923       if (MTE->getExtendingDecl()) {
1924         Ty = VD->getType().getNonReferenceType().getTypePtr();
1925         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1926       }
1927     }
1928 
1929     // If we failed to complete the type for some reason, or if the type is
1930     // dependent, don't diagnose the variable.
1931     if (Ty->isIncompleteType() || Ty->isDependentType())
1932       return false;
1933 
1934     // Look at the element type to ensure that the warning behaviour is
1935     // consistent for both scalars and arrays.
1936     Ty = Ty->getBaseElementTypeUnsafe();
1937 
1938     if (const TagType *TT = Ty->getAs<TagType>()) {
1939       const TagDecl *Tag = TT->getDecl();
1940       if (Tag->hasAttr<UnusedAttr>())
1941         return false;
1942 
1943       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1944         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1945           return false;
1946 
1947         if (Init) {
1948           const CXXConstructExpr *Construct =
1949             dyn_cast<CXXConstructExpr>(Init);
1950           if (Construct && !Construct->isElidable()) {
1951             CXXConstructorDecl *CD = Construct->getConstructor();
1952             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1953                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1954               return false;
1955           }
1956 
1957           // Suppress the warning if we don't know how this is constructed, and
1958           // it could possibly be non-trivial constructor.
1959           if (Init->isTypeDependent()) {
1960             for (const CXXConstructorDecl *Ctor : RD->ctors())
1961               if (!Ctor->isTrivial())
1962                 return false;
1963           }
1964 
1965           // Suppress the warning if the constructor is unresolved because
1966           // its arguments are dependent.
1967           if (isa<CXXUnresolvedConstructExpr>(Init))
1968             return false;
1969         }
1970       }
1971     }
1972 
1973     // TODO: __attribute__((unused)) templates?
1974   }
1975 
1976   return true;
1977 }
1978 
1979 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1980                                      FixItHint &Hint) {
1981   if (isa<LabelDecl>(D)) {
1982     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1983         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1984         true);
1985     if (AfterColon.isInvalid())
1986       return;
1987     Hint = FixItHint::CreateRemoval(
1988         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1989   }
1990 }
1991 
1992 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1993   if (D->getTypeForDecl()->isDependentType())
1994     return;
1995 
1996   for (auto *TmpD : D->decls()) {
1997     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1998       DiagnoseUnusedDecl(T);
1999     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2000       DiagnoseUnusedNestedTypedefs(R);
2001   }
2002 }
2003 
2004 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2005 /// unless they are marked attr(unused).
2006 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2007   if (!ShouldDiagnoseUnusedDecl(D))
2008     return;
2009 
2010   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2011     // typedefs can be referenced later on, so the diagnostics are emitted
2012     // at end-of-translation-unit.
2013     UnusedLocalTypedefNameCandidates.insert(TD);
2014     return;
2015   }
2016 
2017   FixItHint Hint;
2018   GenerateFixForUnusedDecl(D, Context, Hint);
2019 
2020   unsigned DiagID;
2021   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2022     DiagID = diag::warn_unused_exception_param;
2023   else if (isa<LabelDecl>(D))
2024     DiagID = diag::warn_unused_label;
2025   else
2026     DiagID = diag::warn_unused_variable;
2027 
2028   Diag(D->getLocation(), DiagID) << D << Hint;
2029 }
2030 
2031 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2032   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2033   // it's not really unused.
2034   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2035       VD->hasAttr<CleanupAttr>())
2036     return;
2037 
2038   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2039 
2040   if (Ty->isReferenceType() || Ty->isDependentType())
2041     return;
2042 
2043   if (const TagType *TT = Ty->getAs<TagType>()) {
2044     const TagDecl *Tag = TT->getDecl();
2045     if (Tag->hasAttr<UnusedAttr>())
2046       return;
2047     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2048     // mimic gcc's behavior.
2049     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2050       if (!RD->hasAttr<WarnUnusedAttr>())
2051         return;
2052     }
2053   }
2054 
2055   // Don't warn about __block Objective-C pointer variables, as they might
2056   // be assigned in the block but not used elsewhere for the purpose of lifetime
2057   // extension.
2058   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2059     return;
2060 
2061   // Don't warn about Objective-C pointer variables with precise lifetime
2062   // semantics; they can be used to ensure ARC releases the object at a known
2063   // time, which may mean assignment but no other references.
2064   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2065     return;
2066 
2067   auto iter = RefsMinusAssignments.find(VD);
2068   if (iter == RefsMinusAssignments.end())
2069     return;
2070 
2071   assert(iter->getSecond() >= 0 &&
2072          "Found a negative number of references to a VarDecl");
2073   if (iter->getSecond() != 0)
2074     return;
2075   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2076                                          : diag::warn_unused_but_set_variable;
2077   Diag(VD->getLocation(), DiagID) << VD;
2078 }
2079 
2080 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2081   // Verify that we have no forward references left.  If so, there was a goto
2082   // or address of a label taken, but no definition of it.  Label fwd
2083   // definitions are indicated with a null substmt which is also not a resolved
2084   // MS inline assembly label name.
2085   bool Diagnose = false;
2086   if (L->isMSAsmLabel())
2087     Diagnose = !L->isResolvedMSAsmLabel();
2088   else
2089     Diagnose = L->getStmt() == nullptr;
2090   if (Diagnose)
2091     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2092 }
2093 
2094 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2095   S->mergeNRVOIntoParent();
2096 
2097   if (S->decl_empty()) return;
2098   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2099          "Scope shouldn't contain decls!");
2100 
2101   for (auto *TmpD : S->decls()) {
2102     assert(TmpD && "This decl didn't get pushed??");
2103 
2104     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2105     NamedDecl *D = cast<NamedDecl>(TmpD);
2106 
2107     // Diagnose unused variables in this scope.
2108     if (!S->hasUnrecoverableErrorOccurred()) {
2109       DiagnoseUnusedDecl(D);
2110       if (const auto *RD = dyn_cast<RecordDecl>(D))
2111         DiagnoseUnusedNestedTypedefs(RD);
2112       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2113         DiagnoseUnusedButSetDecl(VD);
2114         RefsMinusAssignments.erase(VD);
2115       }
2116     }
2117 
2118     if (!D->getDeclName()) continue;
2119 
2120     // If this was a forward reference to a label, verify it was defined.
2121     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2122       CheckPoppedLabel(LD, *this);
2123 
2124     // Remove this name from our lexical scope, and warn on it if we haven't
2125     // already.
2126     IdResolver.RemoveDecl(D);
2127     auto ShadowI = ShadowingDecls.find(D);
2128     if (ShadowI != ShadowingDecls.end()) {
2129       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2130         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2131             << D << FD << FD->getParent();
2132         Diag(FD->getLocation(), diag::note_previous_declaration);
2133       }
2134       ShadowingDecls.erase(ShadowI);
2135     }
2136   }
2137 }
2138 
2139 /// Look for an Objective-C class in the translation unit.
2140 ///
2141 /// \param Id The name of the Objective-C class we're looking for. If
2142 /// typo-correction fixes this name, the Id will be updated
2143 /// to the fixed name.
2144 ///
2145 /// \param IdLoc The location of the name in the translation unit.
2146 ///
2147 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2148 /// if there is no class with the given name.
2149 ///
2150 /// \returns The declaration of the named Objective-C class, or NULL if the
2151 /// class could not be found.
2152 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2153                                               SourceLocation IdLoc,
2154                                               bool DoTypoCorrection) {
2155   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2156   // creation from this context.
2157   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2158 
2159   if (!IDecl && DoTypoCorrection) {
2160     // Perform typo correction at the given location, but only if we
2161     // find an Objective-C class name.
2162     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2163     if (TypoCorrection C =
2164             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2165                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2166       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2167       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2168       Id = IDecl->getIdentifier();
2169     }
2170   }
2171   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2172   // This routine must always return a class definition, if any.
2173   if (Def && Def->getDefinition())
2174       Def = Def->getDefinition();
2175   return Def;
2176 }
2177 
2178 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2179 /// from S, where a non-field would be declared. This routine copes
2180 /// with the difference between C and C++ scoping rules in structs and
2181 /// unions. For example, the following code is well-formed in C but
2182 /// ill-formed in C++:
2183 /// @code
2184 /// struct S6 {
2185 ///   enum { BAR } e;
2186 /// };
2187 ///
2188 /// void test_S6() {
2189 ///   struct S6 a;
2190 ///   a.e = BAR;
2191 /// }
2192 /// @endcode
2193 /// For the declaration of BAR, this routine will return a different
2194 /// scope. The scope S will be the scope of the unnamed enumeration
2195 /// within S6. In C++, this routine will return the scope associated
2196 /// with S6, because the enumeration's scope is a transparent
2197 /// context but structures can contain non-field names. In C, this
2198 /// routine will return the translation unit scope, since the
2199 /// enumeration's scope is a transparent context and structures cannot
2200 /// contain non-field names.
2201 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2202   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2203          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2204          (S->isClassScope() && !getLangOpts().CPlusPlus))
2205     S = S->getParent();
2206   return S;
2207 }
2208 
2209 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2210                                ASTContext::GetBuiltinTypeError Error) {
2211   switch (Error) {
2212   case ASTContext::GE_None:
2213     return "";
2214   case ASTContext::GE_Missing_type:
2215     return BuiltinInfo.getHeaderName(ID);
2216   case ASTContext::GE_Missing_stdio:
2217     return "stdio.h";
2218   case ASTContext::GE_Missing_setjmp:
2219     return "setjmp.h";
2220   case ASTContext::GE_Missing_ucontext:
2221     return "ucontext.h";
2222   }
2223   llvm_unreachable("unhandled error kind");
2224 }
2225 
2226 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2227                                   unsigned ID, SourceLocation Loc) {
2228   DeclContext *Parent = Context.getTranslationUnitDecl();
2229 
2230   if (getLangOpts().CPlusPlus) {
2231     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2232         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2233     CLinkageDecl->setImplicit();
2234     Parent->addDecl(CLinkageDecl);
2235     Parent = CLinkageDecl;
2236   }
2237 
2238   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2239                                            /*TInfo=*/nullptr, SC_Extern,
2240                                            getCurFPFeatures().isFPConstrained(),
2241                                            false, Type->isFunctionProtoType());
2242   New->setImplicit();
2243   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2244 
2245   // Create Decl objects for each parameter, adding them to the
2246   // FunctionDecl.
2247   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2248     SmallVector<ParmVarDecl *, 16> Params;
2249     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2250       ParmVarDecl *parm = ParmVarDecl::Create(
2251           Context, New, SourceLocation(), SourceLocation(), nullptr,
2252           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2253       parm->setScopeInfo(0, i);
2254       Params.push_back(parm);
2255     }
2256     New->setParams(Params);
2257   }
2258 
2259   AddKnownFunctionAttributes(New);
2260   return New;
2261 }
2262 
2263 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2264 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2265 /// if we're creating this built-in in anticipation of redeclaring the
2266 /// built-in.
2267 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2268                                      Scope *S, bool ForRedeclaration,
2269                                      SourceLocation Loc) {
2270   LookupNecessaryTypesForBuiltin(S, ID);
2271 
2272   ASTContext::GetBuiltinTypeError Error;
2273   QualType R = Context.GetBuiltinType(ID, Error);
2274   if (Error) {
2275     if (!ForRedeclaration)
2276       return nullptr;
2277 
2278     // If we have a builtin without an associated type we should not emit a
2279     // warning when we were not able to find a type for it.
2280     if (Error == ASTContext::GE_Missing_type ||
2281         Context.BuiltinInfo.allowTypeMismatch(ID))
2282       return nullptr;
2283 
2284     // If we could not find a type for setjmp it is because the jmp_buf type was
2285     // not defined prior to the setjmp declaration.
2286     if (Error == ASTContext::GE_Missing_setjmp) {
2287       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2288           << Context.BuiltinInfo.getName(ID);
2289       return nullptr;
2290     }
2291 
2292     // Generally, we emit a warning that the declaration requires the
2293     // appropriate header.
2294     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2295         << getHeaderName(Context.BuiltinInfo, ID, Error)
2296         << Context.BuiltinInfo.getName(ID);
2297     return nullptr;
2298   }
2299 
2300   if (!ForRedeclaration &&
2301       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2302        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2303     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2304                            : diag::ext_implicit_lib_function_decl)
2305         << Context.BuiltinInfo.getName(ID) << R;
2306     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2307       Diag(Loc, diag::note_include_header_or_declare)
2308           << Header << Context.BuiltinInfo.getName(ID);
2309   }
2310 
2311   if (R.isNull())
2312     return nullptr;
2313 
2314   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2315   RegisterLocallyScopedExternCDecl(New, S);
2316 
2317   // TUScope is the translation-unit scope to insert this function into.
2318   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2319   // relate Scopes to DeclContexts, and probably eliminate CurContext
2320   // entirely, but we're not there yet.
2321   DeclContext *SavedContext = CurContext;
2322   CurContext = New->getDeclContext();
2323   PushOnScopeChains(New, TUScope);
2324   CurContext = SavedContext;
2325   return New;
2326 }
2327 
2328 /// Typedef declarations don't have linkage, but they still denote the same
2329 /// entity if their types are the same.
2330 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2331 /// isSameEntity.
2332 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2333                                                      TypedefNameDecl *Decl,
2334                                                      LookupResult &Previous) {
2335   // This is only interesting when modules are enabled.
2336   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2337     return;
2338 
2339   // Empty sets are uninteresting.
2340   if (Previous.empty())
2341     return;
2342 
2343   LookupResult::Filter Filter = Previous.makeFilter();
2344   while (Filter.hasNext()) {
2345     NamedDecl *Old = Filter.next();
2346 
2347     // Non-hidden declarations are never ignored.
2348     if (S.isVisible(Old))
2349       continue;
2350 
2351     // Declarations of the same entity are not ignored, even if they have
2352     // different linkages.
2353     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2354       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2355                                 Decl->getUnderlyingType()))
2356         continue;
2357 
2358       // If both declarations give a tag declaration a typedef name for linkage
2359       // purposes, then they declare the same entity.
2360       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2361           Decl->getAnonDeclWithTypedefName())
2362         continue;
2363     }
2364 
2365     Filter.erase();
2366   }
2367 
2368   Filter.done();
2369 }
2370 
2371 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2372   QualType OldType;
2373   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2374     OldType = OldTypedef->getUnderlyingType();
2375   else
2376     OldType = Context.getTypeDeclType(Old);
2377   QualType NewType = New->getUnderlyingType();
2378 
2379   if (NewType->isVariablyModifiedType()) {
2380     // Must not redefine a typedef with a variably-modified type.
2381     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2382     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2383       << Kind << NewType;
2384     if (Old->getLocation().isValid())
2385       notePreviousDefinition(Old, New->getLocation());
2386     New->setInvalidDecl();
2387     return true;
2388   }
2389 
2390   if (OldType != NewType &&
2391       !OldType->isDependentType() &&
2392       !NewType->isDependentType() &&
2393       !Context.hasSameType(OldType, NewType)) {
2394     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2395     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2396       << Kind << NewType << OldType;
2397     if (Old->getLocation().isValid())
2398       notePreviousDefinition(Old, New->getLocation());
2399     New->setInvalidDecl();
2400     return true;
2401   }
2402   return false;
2403 }
2404 
2405 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2406 /// same name and scope as a previous declaration 'Old'.  Figure out
2407 /// how to resolve this situation, merging decls or emitting
2408 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2409 ///
2410 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2411                                 LookupResult &OldDecls) {
2412   // If the new decl is known invalid already, don't bother doing any
2413   // merging checks.
2414   if (New->isInvalidDecl()) return;
2415 
2416   // Allow multiple definitions for ObjC built-in typedefs.
2417   // FIXME: Verify the underlying types are equivalent!
2418   if (getLangOpts().ObjC) {
2419     const IdentifierInfo *TypeID = New->getIdentifier();
2420     switch (TypeID->getLength()) {
2421     default: break;
2422     case 2:
2423       {
2424         if (!TypeID->isStr("id"))
2425           break;
2426         QualType T = New->getUnderlyingType();
2427         if (!T->isPointerType())
2428           break;
2429         if (!T->isVoidPointerType()) {
2430           QualType PT = T->castAs<PointerType>()->getPointeeType();
2431           if (!PT->isStructureType())
2432             break;
2433         }
2434         Context.setObjCIdRedefinitionType(T);
2435         // Install the built-in type for 'id', ignoring the current definition.
2436         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2437         return;
2438       }
2439     case 5:
2440       if (!TypeID->isStr("Class"))
2441         break;
2442       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2443       // Install the built-in type for 'Class', ignoring the current definition.
2444       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2445       return;
2446     case 3:
2447       if (!TypeID->isStr("SEL"))
2448         break;
2449       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2450       // Install the built-in type for 'SEL', ignoring the current definition.
2451       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2452       return;
2453     }
2454     // Fall through - the typedef name was not a builtin type.
2455   }
2456 
2457   // Verify the old decl was also a type.
2458   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2459   if (!Old) {
2460     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2461       << New->getDeclName();
2462 
2463     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2464     if (OldD->getLocation().isValid())
2465       notePreviousDefinition(OldD, New->getLocation());
2466 
2467     return New->setInvalidDecl();
2468   }
2469 
2470   // If the old declaration is invalid, just give up here.
2471   if (Old->isInvalidDecl())
2472     return New->setInvalidDecl();
2473 
2474   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2475     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2476     auto *NewTag = New->getAnonDeclWithTypedefName();
2477     NamedDecl *Hidden = nullptr;
2478     if (OldTag && NewTag &&
2479         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2480         !hasVisibleDefinition(OldTag, &Hidden)) {
2481       // There is a definition of this tag, but it is not visible. Use it
2482       // instead of our tag.
2483       New->setTypeForDecl(OldTD->getTypeForDecl());
2484       if (OldTD->isModed())
2485         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2486                                     OldTD->getUnderlyingType());
2487       else
2488         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2489 
2490       // Make the old tag definition visible.
2491       makeMergedDefinitionVisible(Hidden);
2492 
2493       // If this was an unscoped enumeration, yank all of its enumerators
2494       // out of the scope.
2495       if (isa<EnumDecl>(NewTag)) {
2496         Scope *EnumScope = getNonFieldDeclScope(S);
2497         for (auto *D : NewTag->decls()) {
2498           auto *ED = cast<EnumConstantDecl>(D);
2499           assert(EnumScope->isDeclScope(ED));
2500           EnumScope->RemoveDecl(ED);
2501           IdResolver.RemoveDecl(ED);
2502           ED->getLexicalDeclContext()->removeDecl(ED);
2503         }
2504       }
2505     }
2506   }
2507 
2508   // If the typedef types are not identical, reject them in all languages and
2509   // with any extensions enabled.
2510   if (isIncompatibleTypedef(Old, New))
2511     return;
2512 
2513   // The types match.  Link up the redeclaration chain and merge attributes if
2514   // the old declaration was a typedef.
2515   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2516     New->setPreviousDecl(Typedef);
2517     mergeDeclAttributes(New, Old);
2518   }
2519 
2520   if (getLangOpts().MicrosoftExt)
2521     return;
2522 
2523   if (getLangOpts().CPlusPlus) {
2524     // C++ [dcl.typedef]p2:
2525     //   In a given non-class scope, a typedef specifier can be used to
2526     //   redefine the name of any type declared in that scope to refer
2527     //   to the type to which it already refers.
2528     if (!isa<CXXRecordDecl>(CurContext))
2529       return;
2530 
2531     // C++0x [dcl.typedef]p4:
2532     //   In a given class scope, a typedef specifier can be used to redefine
2533     //   any class-name declared in that scope that is not also a typedef-name
2534     //   to refer to the type to which it already refers.
2535     //
2536     // This wording came in via DR424, which was a correction to the
2537     // wording in DR56, which accidentally banned code like:
2538     //
2539     //   struct S {
2540     //     typedef struct A { } A;
2541     //   };
2542     //
2543     // in the C++03 standard. We implement the C++0x semantics, which
2544     // allow the above but disallow
2545     //
2546     //   struct S {
2547     //     typedef int I;
2548     //     typedef int I;
2549     //   };
2550     //
2551     // since that was the intent of DR56.
2552     if (!isa<TypedefNameDecl>(Old))
2553       return;
2554 
2555     Diag(New->getLocation(), diag::err_redefinition)
2556       << New->getDeclName();
2557     notePreviousDefinition(Old, New->getLocation());
2558     return New->setInvalidDecl();
2559   }
2560 
2561   // Modules always permit redefinition of typedefs, as does C11.
2562   if (getLangOpts().Modules || getLangOpts().C11)
2563     return;
2564 
2565   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2566   // is normally mapped to an error, but can be controlled with
2567   // -Wtypedef-redefinition.  If either the original or the redefinition is
2568   // in a system header, don't emit this for compatibility with GCC.
2569   if (getDiagnostics().getSuppressSystemWarnings() &&
2570       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2571       (Old->isImplicit() ||
2572        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2573        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2574     return;
2575 
2576   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2577     << New->getDeclName();
2578   notePreviousDefinition(Old, New->getLocation());
2579 }
2580 
2581 /// DeclhasAttr - returns true if decl Declaration already has the target
2582 /// attribute.
2583 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2584   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2585   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2586   for (const auto *i : D->attrs())
2587     if (i->getKind() == A->getKind()) {
2588       if (Ann) {
2589         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2590           return true;
2591         continue;
2592       }
2593       // FIXME: Don't hardcode this check
2594       if (OA && isa<OwnershipAttr>(i))
2595         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2596       return true;
2597     }
2598 
2599   return false;
2600 }
2601 
2602 static bool isAttributeTargetADefinition(Decl *D) {
2603   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2604     return VD->isThisDeclarationADefinition();
2605   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2606     return TD->isCompleteDefinition() || TD->isBeingDefined();
2607   return true;
2608 }
2609 
2610 /// Merge alignment attributes from \p Old to \p New, taking into account the
2611 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2612 ///
2613 /// \return \c true if any attributes were added to \p New.
2614 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2615   // Look for alignas attributes on Old, and pick out whichever attribute
2616   // specifies the strictest alignment requirement.
2617   AlignedAttr *OldAlignasAttr = nullptr;
2618   AlignedAttr *OldStrictestAlignAttr = nullptr;
2619   unsigned OldAlign = 0;
2620   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2621     // FIXME: We have no way of representing inherited dependent alignments
2622     // in a case like:
2623     //   template<int A, int B> struct alignas(A) X;
2624     //   template<int A, int B> struct alignas(B) X {};
2625     // For now, we just ignore any alignas attributes which are not on the
2626     // definition in such a case.
2627     if (I->isAlignmentDependent())
2628       return false;
2629 
2630     if (I->isAlignas())
2631       OldAlignasAttr = I;
2632 
2633     unsigned Align = I->getAlignment(S.Context);
2634     if (Align > OldAlign) {
2635       OldAlign = Align;
2636       OldStrictestAlignAttr = I;
2637     }
2638   }
2639 
2640   // Look for alignas attributes on New.
2641   AlignedAttr *NewAlignasAttr = nullptr;
2642   unsigned NewAlign = 0;
2643   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2644     if (I->isAlignmentDependent())
2645       return false;
2646 
2647     if (I->isAlignas())
2648       NewAlignasAttr = I;
2649 
2650     unsigned Align = I->getAlignment(S.Context);
2651     if (Align > NewAlign)
2652       NewAlign = Align;
2653   }
2654 
2655   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2656     // Both declarations have 'alignas' attributes. We require them to match.
2657     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2658     // fall short. (If two declarations both have alignas, they must both match
2659     // every definition, and so must match each other if there is a definition.)
2660 
2661     // If either declaration only contains 'alignas(0)' specifiers, then it
2662     // specifies the natural alignment for the type.
2663     if (OldAlign == 0 || NewAlign == 0) {
2664       QualType Ty;
2665       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2666         Ty = VD->getType();
2667       else
2668         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2669 
2670       if (OldAlign == 0)
2671         OldAlign = S.Context.getTypeAlign(Ty);
2672       if (NewAlign == 0)
2673         NewAlign = S.Context.getTypeAlign(Ty);
2674     }
2675 
2676     if (OldAlign != NewAlign) {
2677       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2678         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2679         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2680       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2681     }
2682   }
2683 
2684   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2685     // C++11 [dcl.align]p6:
2686     //   if any declaration of an entity has an alignment-specifier,
2687     //   every defining declaration of that entity shall specify an
2688     //   equivalent alignment.
2689     // C11 6.7.5/7:
2690     //   If the definition of an object does not have an alignment
2691     //   specifier, any other declaration of that object shall also
2692     //   have no alignment specifier.
2693     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2694       << OldAlignasAttr;
2695     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2696       << OldAlignasAttr;
2697   }
2698 
2699   bool AnyAdded = false;
2700 
2701   // Ensure we have an attribute representing the strictest alignment.
2702   if (OldAlign > NewAlign) {
2703     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2704     Clone->setInherited(true);
2705     New->addAttr(Clone);
2706     AnyAdded = true;
2707   }
2708 
2709   // Ensure we have an alignas attribute if the old declaration had one.
2710   if (OldAlignasAttr && !NewAlignasAttr &&
2711       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2712     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2713     Clone->setInherited(true);
2714     New->addAttr(Clone);
2715     AnyAdded = true;
2716   }
2717 
2718   return AnyAdded;
2719 }
2720 
2721 #define WANT_DECL_MERGE_LOGIC
2722 #include "clang/Sema/AttrParsedAttrImpl.inc"
2723 #undef WANT_DECL_MERGE_LOGIC
2724 
2725 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2726                                const InheritableAttr *Attr,
2727                                Sema::AvailabilityMergeKind AMK) {
2728   // Diagnose any mutual exclusions between the attribute that we want to add
2729   // and attributes that already exist on the declaration.
2730   if (!DiagnoseMutualExclusions(S, D, Attr))
2731     return false;
2732 
2733   // This function copies an attribute Attr from a previous declaration to the
2734   // new declaration D if the new declaration doesn't itself have that attribute
2735   // yet or if that attribute allows duplicates.
2736   // If you're adding a new attribute that requires logic different from
2737   // "use explicit attribute on decl if present, else use attribute from
2738   // previous decl", for example if the attribute needs to be consistent
2739   // between redeclarations, you need to call a custom merge function here.
2740   InheritableAttr *NewAttr = nullptr;
2741   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2742     NewAttr = S.mergeAvailabilityAttr(
2743         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2744         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2745         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2746         AA->getPriority());
2747   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2748     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2749   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2750     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2751   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2752     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2753   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2754     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2755   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2756     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2757   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2758     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2759                                 FA->getFirstArg());
2760   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2761     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2762   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2763     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2764   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2765     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2766                                        IA->getInheritanceModel());
2767   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2768     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2769                                       &S.Context.Idents.get(AA->getSpelling()));
2770   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2771            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2772             isa<CUDAGlobalAttr>(Attr))) {
2773     // CUDA target attributes are part of function signature for
2774     // overloading purposes and must not be merged.
2775     return false;
2776   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2777     NewAttr = S.mergeMinSizeAttr(D, *MA);
2778   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2779     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2780   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2781     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2782   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2783     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2784   else if (isa<AlignedAttr>(Attr))
2785     // AlignedAttrs are handled separately, because we need to handle all
2786     // such attributes on a declaration at the same time.
2787     NewAttr = nullptr;
2788   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2789            (AMK == Sema::AMK_Override ||
2790             AMK == Sema::AMK_ProtocolImplementation ||
2791             AMK == Sema::AMK_OptionalProtocolImplementation))
2792     NewAttr = nullptr;
2793   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2794     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2795   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2796     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2797   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2798     NewAttr = S.mergeImportNameAttr(D, *INA);
2799   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2800     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2801   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2802     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2803   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2804     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2805   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2806     NewAttr =
2807         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2808   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2809     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2810   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2811     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2812 
2813   if (NewAttr) {
2814     NewAttr->setInherited(true);
2815     D->addAttr(NewAttr);
2816     if (isa<MSInheritanceAttr>(NewAttr))
2817       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2818     return true;
2819   }
2820 
2821   return false;
2822 }
2823 
2824 static const NamedDecl *getDefinition(const Decl *D) {
2825   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2826     return TD->getDefinition();
2827   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2828     const VarDecl *Def = VD->getDefinition();
2829     if (Def)
2830       return Def;
2831     return VD->getActingDefinition();
2832   }
2833   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2834     const FunctionDecl *Def = nullptr;
2835     if (FD->isDefined(Def, true))
2836       return Def;
2837   }
2838   return nullptr;
2839 }
2840 
2841 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2842   for (const auto *Attribute : D->attrs())
2843     if (Attribute->getKind() == Kind)
2844       return true;
2845   return false;
2846 }
2847 
2848 /// checkNewAttributesAfterDef - If we already have a definition, check that
2849 /// there are no new attributes in this declaration.
2850 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2851   if (!New->hasAttrs())
2852     return;
2853 
2854   const NamedDecl *Def = getDefinition(Old);
2855   if (!Def || Def == New)
2856     return;
2857 
2858   AttrVec &NewAttributes = New->getAttrs();
2859   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2860     const Attr *NewAttribute = NewAttributes[I];
2861 
2862     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2863       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2864         Sema::SkipBodyInfo SkipBody;
2865         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2866 
2867         // If we're skipping this definition, drop the "alias" attribute.
2868         if (SkipBody.ShouldSkip) {
2869           NewAttributes.erase(NewAttributes.begin() + I);
2870           --E;
2871           continue;
2872         }
2873       } else {
2874         VarDecl *VD = cast<VarDecl>(New);
2875         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2876                                 VarDecl::TentativeDefinition
2877                             ? diag::err_alias_after_tentative
2878                             : diag::err_redefinition;
2879         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2880         if (Diag == diag::err_redefinition)
2881           S.notePreviousDefinition(Def, VD->getLocation());
2882         else
2883           S.Diag(Def->getLocation(), diag::note_previous_definition);
2884         VD->setInvalidDecl();
2885       }
2886       ++I;
2887       continue;
2888     }
2889 
2890     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2891       // Tentative definitions are only interesting for the alias check above.
2892       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2893         ++I;
2894         continue;
2895       }
2896     }
2897 
2898     if (hasAttribute(Def, NewAttribute->getKind())) {
2899       ++I;
2900       continue; // regular attr merging will take care of validating this.
2901     }
2902 
2903     if (isa<C11NoReturnAttr>(NewAttribute)) {
2904       // C's _Noreturn is allowed to be added to a function after it is defined.
2905       ++I;
2906       continue;
2907     } else if (isa<UuidAttr>(NewAttribute)) {
2908       // msvc will allow a subsequent definition to add an uuid to a class
2909       ++I;
2910       continue;
2911     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2912       if (AA->isAlignas()) {
2913         // C++11 [dcl.align]p6:
2914         //   if any declaration of an entity has an alignment-specifier,
2915         //   every defining declaration of that entity shall specify an
2916         //   equivalent alignment.
2917         // C11 6.7.5/7:
2918         //   If the definition of an object does not have an alignment
2919         //   specifier, any other declaration of that object shall also
2920         //   have no alignment specifier.
2921         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2922           << AA;
2923         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2924           << AA;
2925         NewAttributes.erase(NewAttributes.begin() + I);
2926         --E;
2927         continue;
2928       }
2929     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2930       // If there is a C definition followed by a redeclaration with this
2931       // attribute then there are two different definitions. In C++, prefer the
2932       // standard diagnostics.
2933       if (!S.getLangOpts().CPlusPlus) {
2934         S.Diag(NewAttribute->getLocation(),
2935                diag::err_loader_uninitialized_redeclaration);
2936         S.Diag(Def->getLocation(), diag::note_previous_definition);
2937         NewAttributes.erase(NewAttributes.begin() + I);
2938         --E;
2939         continue;
2940       }
2941     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2942                cast<VarDecl>(New)->isInline() &&
2943                !cast<VarDecl>(New)->isInlineSpecified()) {
2944       // Don't warn about applying selectany to implicitly inline variables.
2945       // Older compilers and language modes would require the use of selectany
2946       // to make such variables inline, and it would have no effect if we
2947       // honored it.
2948       ++I;
2949       continue;
2950     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2951       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2952       // declarations after defintions.
2953       ++I;
2954       continue;
2955     }
2956 
2957     S.Diag(NewAttribute->getLocation(),
2958            diag::warn_attribute_precede_definition);
2959     S.Diag(Def->getLocation(), diag::note_previous_definition);
2960     NewAttributes.erase(NewAttributes.begin() + I);
2961     --E;
2962   }
2963 }
2964 
2965 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2966                                      const ConstInitAttr *CIAttr,
2967                                      bool AttrBeforeInit) {
2968   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2969 
2970   // Figure out a good way to write this specifier on the old declaration.
2971   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2972   // enough of the attribute list spelling information to extract that without
2973   // heroics.
2974   std::string SuitableSpelling;
2975   if (S.getLangOpts().CPlusPlus20)
2976     SuitableSpelling = std::string(
2977         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2978   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2979     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2980         InsertLoc, {tok::l_square, tok::l_square,
2981                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2982                     S.PP.getIdentifierInfo("require_constant_initialization"),
2983                     tok::r_square, tok::r_square}));
2984   if (SuitableSpelling.empty())
2985     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2986         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2987                     S.PP.getIdentifierInfo("require_constant_initialization"),
2988                     tok::r_paren, tok::r_paren}));
2989   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2990     SuitableSpelling = "constinit";
2991   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2992     SuitableSpelling = "[[clang::require_constant_initialization]]";
2993   if (SuitableSpelling.empty())
2994     SuitableSpelling = "__attribute__((require_constant_initialization))";
2995   SuitableSpelling += " ";
2996 
2997   if (AttrBeforeInit) {
2998     // extern constinit int a;
2999     // int a = 0; // error (missing 'constinit'), accepted as extension
3000     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3001     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3002         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3003     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3004   } else {
3005     // int a = 0;
3006     // constinit extern int a; // error (missing 'constinit')
3007     S.Diag(CIAttr->getLocation(),
3008            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3009                                  : diag::warn_require_const_init_added_too_late)
3010         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3011     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3012         << CIAttr->isConstinit()
3013         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3014   }
3015 }
3016 
3017 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3018 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3019                                AvailabilityMergeKind AMK) {
3020   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3021     UsedAttr *NewAttr = OldAttr->clone(Context);
3022     NewAttr->setInherited(true);
3023     New->addAttr(NewAttr);
3024   }
3025   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3026     RetainAttr *NewAttr = OldAttr->clone(Context);
3027     NewAttr->setInherited(true);
3028     New->addAttr(NewAttr);
3029   }
3030 
3031   if (!Old->hasAttrs() && !New->hasAttrs())
3032     return;
3033 
3034   // [dcl.constinit]p1:
3035   //   If the [constinit] specifier is applied to any declaration of a
3036   //   variable, it shall be applied to the initializing declaration.
3037   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3038   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3039   if (bool(OldConstInit) != bool(NewConstInit)) {
3040     const auto *OldVD = cast<VarDecl>(Old);
3041     auto *NewVD = cast<VarDecl>(New);
3042 
3043     // Find the initializing declaration. Note that we might not have linked
3044     // the new declaration into the redeclaration chain yet.
3045     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3046     if (!InitDecl &&
3047         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3048       InitDecl = NewVD;
3049 
3050     if (InitDecl == NewVD) {
3051       // This is the initializing declaration. If it would inherit 'constinit',
3052       // that's ill-formed. (Note that we do not apply this to the attribute
3053       // form).
3054       if (OldConstInit && OldConstInit->isConstinit())
3055         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3056                                  /*AttrBeforeInit=*/true);
3057     } else if (NewConstInit) {
3058       // This is the first time we've been told that this declaration should
3059       // have a constant initializer. If we already saw the initializing
3060       // declaration, this is too late.
3061       if (InitDecl && InitDecl != NewVD) {
3062         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3063                                  /*AttrBeforeInit=*/false);
3064         NewVD->dropAttr<ConstInitAttr>();
3065       }
3066     }
3067   }
3068 
3069   // Attributes declared post-definition are currently ignored.
3070   checkNewAttributesAfterDef(*this, New, Old);
3071 
3072   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3073     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3074       if (!OldA->isEquivalent(NewA)) {
3075         // This redeclaration changes __asm__ label.
3076         Diag(New->getLocation(), diag::err_different_asm_label);
3077         Diag(OldA->getLocation(), diag::note_previous_declaration);
3078       }
3079     } else if (Old->isUsed()) {
3080       // This redeclaration adds an __asm__ label to a declaration that has
3081       // already been ODR-used.
3082       Diag(New->getLocation(), diag::err_late_asm_label_name)
3083         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3084     }
3085   }
3086 
3087   // Re-declaration cannot add abi_tag's.
3088   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3089     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3090       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3091         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3092           Diag(NewAbiTagAttr->getLocation(),
3093                diag::err_new_abi_tag_on_redeclaration)
3094               << NewTag;
3095           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3096         }
3097       }
3098     } else {
3099       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3100       Diag(Old->getLocation(), diag::note_previous_declaration);
3101     }
3102   }
3103 
3104   // This redeclaration adds a section attribute.
3105   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3106     if (auto *VD = dyn_cast<VarDecl>(New)) {
3107       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3108         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3109         Diag(Old->getLocation(), diag::note_previous_declaration);
3110       }
3111     }
3112   }
3113 
3114   // Redeclaration adds code-seg attribute.
3115   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3116   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3117       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3118     Diag(New->getLocation(), diag::warn_mismatched_section)
3119          << 0 /*codeseg*/;
3120     Diag(Old->getLocation(), diag::note_previous_declaration);
3121   }
3122 
3123   if (!Old->hasAttrs())
3124     return;
3125 
3126   bool foundAny = New->hasAttrs();
3127 
3128   // Ensure that any moving of objects within the allocated map is done before
3129   // we process them.
3130   if (!foundAny) New->setAttrs(AttrVec());
3131 
3132   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3133     // Ignore deprecated/unavailable/availability attributes if requested.
3134     AvailabilityMergeKind LocalAMK = AMK_None;
3135     if (isa<DeprecatedAttr>(I) ||
3136         isa<UnavailableAttr>(I) ||
3137         isa<AvailabilityAttr>(I)) {
3138       switch (AMK) {
3139       case AMK_None:
3140         continue;
3141 
3142       case AMK_Redeclaration:
3143       case AMK_Override:
3144       case AMK_ProtocolImplementation:
3145       case AMK_OptionalProtocolImplementation:
3146         LocalAMK = AMK;
3147         break;
3148       }
3149     }
3150 
3151     // Already handled.
3152     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3153       continue;
3154 
3155     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3156       foundAny = true;
3157   }
3158 
3159   if (mergeAlignedAttrs(*this, New, Old))
3160     foundAny = true;
3161 
3162   if (!foundAny) New->dropAttrs();
3163 }
3164 
3165 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3166 /// to the new one.
3167 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3168                                      const ParmVarDecl *oldDecl,
3169                                      Sema &S) {
3170   // C++11 [dcl.attr.depend]p2:
3171   //   The first declaration of a function shall specify the
3172   //   carries_dependency attribute for its declarator-id if any declaration
3173   //   of the function specifies the carries_dependency attribute.
3174   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3175   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3176     S.Diag(CDA->getLocation(),
3177            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3178     // Find the first declaration of the parameter.
3179     // FIXME: Should we build redeclaration chains for function parameters?
3180     const FunctionDecl *FirstFD =
3181       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3182     const ParmVarDecl *FirstVD =
3183       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3184     S.Diag(FirstVD->getLocation(),
3185            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3186   }
3187 
3188   if (!oldDecl->hasAttrs())
3189     return;
3190 
3191   bool foundAny = newDecl->hasAttrs();
3192 
3193   // Ensure that any moving of objects within the allocated map is
3194   // done before we process them.
3195   if (!foundAny) newDecl->setAttrs(AttrVec());
3196 
3197   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3198     if (!DeclHasAttr(newDecl, I)) {
3199       InheritableAttr *newAttr =
3200         cast<InheritableParamAttr>(I->clone(S.Context));
3201       newAttr->setInherited(true);
3202       newDecl->addAttr(newAttr);
3203       foundAny = true;
3204     }
3205   }
3206 
3207   if (!foundAny) newDecl->dropAttrs();
3208 }
3209 
3210 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3211                                 const ParmVarDecl *OldParam,
3212                                 Sema &S) {
3213   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3214     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3215       if (*Oldnullability != *Newnullability) {
3216         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3217           << DiagNullabilityKind(
3218                *Newnullability,
3219                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3220                 != 0))
3221           << DiagNullabilityKind(
3222                *Oldnullability,
3223                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3224                 != 0));
3225         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3226       }
3227     } else {
3228       QualType NewT = NewParam->getType();
3229       NewT = S.Context.getAttributedType(
3230                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3231                          NewT, NewT);
3232       NewParam->setType(NewT);
3233     }
3234   }
3235 }
3236 
3237 namespace {
3238 
3239 /// Used in MergeFunctionDecl to keep track of function parameters in
3240 /// C.
3241 struct GNUCompatibleParamWarning {
3242   ParmVarDecl *OldParm;
3243   ParmVarDecl *NewParm;
3244   QualType PromotedType;
3245 };
3246 
3247 } // end anonymous namespace
3248 
3249 // Determine whether the previous declaration was a definition, implicit
3250 // declaration, or a declaration.
3251 template <typename T>
3252 static std::pair<diag::kind, SourceLocation>
3253 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3254   diag::kind PrevDiag;
3255   SourceLocation OldLocation = Old->getLocation();
3256   if (Old->isThisDeclarationADefinition())
3257     PrevDiag = diag::note_previous_definition;
3258   else if (Old->isImplicit()) {
3259     PrevDiag = diag::note_previous_implicit_declaration;
3260     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3261       if (FD->getBuiltinID())
3262         PrevDiag = diag::note_previous_builtin_declaration;
3263     }
3264     if (OldLocation.isInvalid())
3265       OldLocation = New->getLocation();
3266   } else
3267     PrevDiag = diag::note_previous_declaration;
3268   return std::make_pair(PrevDiag, OldLocation);
3269 }
3270 
3271 /// canRedefineFunction - checks if a function can be redefined. Currently,
3272 /// only extern inline functions can be redefined, and even then only in
3273 /// GNU89 mode.
3274 static bool canRedefineFunction(const FunctionDecl *FD,
3275                                 const LangOptions& LangOpts) {
3276   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3277           !LangOpts.CPlusPlus &&
3278           FD->isInlineSpecified() &&
3279           FD->getStorageClass() == SC_Extern);
3280 }
3281 
3282 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3283   const AttributedType *AT = T->getAs<AttributedType>();
3284   while (AT && !AT->isCallingConv())
3285     AT = AT->getModifiedType()->getAs<AttributedType>();
3286   return AT;
3287 }
3288 
3289 template <typename T>
3290 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3291   const DeclContext *DC = Old->getDeclContext();
3292   if (DC->isRecord())
3293     return false;
3294 
3295   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3296   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3297     return true;
3298   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3299     return true;
3300   return false;
3301 }
3302 
3303 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3304 static bool isExternC(VarTemplateDecl *) { return false; }
3305 static bool isExternC(FunctionTemplateDecl *) { return false; }
3306 
3307 /// Check whether a redeclaration of an entity introduced by a
3308 /// using-declaration is valid, given that we know it's not an overload
3309 /// (nor a hidden tag declaration).
3310 template<typename ExpectedDecl>
3311 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3312                                    ExpectedDecl *New) {
3313   // C++11 [basic.scope.declarative]p4:
3314   //   Given a set of declarations in a single declarative region, each of
3315   //   which specifies the same unqualified name,
3316   //   -- they shall all refer to the same entity, or all refer to functions
3317   //      and function templates; or
3318   //   -- exactly one declaration shall declare a class name or enumeration
3319   //      name that is not a typedef name and the other declarations shall all
3320   //      refer to the same variable or enumerator, or all refer to functions
3321   //      and function templates; in this case the class name or enumeration
3322   //      name is hidden (3.3.10).
3323 
3324   // C++11 [namespace.udecl]p14:
3325   //   If a function declaration in namespace scope or block scope has the
3326   //   same name and the same parameter-type-list as a function introduced
3327   //   by a using-declaration, and the declarations do not declare the same
3328   //   function, the program is ill-formed.
3329 
3330   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3331   if (Old &&
3332       !Old->getDeclContext()->getRedeclContext()->Equals(
3333           New->getDeclContext()->getRedeclContext()) &&
3334       !(isExternC(Old) && isExternC(New)))
3335     Old = nullptr;
3336 
3337   if (!Old) {
3338     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3339     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3340     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3341     return true;
3342   }
3343   return false;
3344 }
3345 
3346 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3347                                             const FunctionDecl *B) {
3348   assert(A->getNumParams() == B->getNumParams());
3349 
3350   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3351     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3352     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3353     if (AttrA == AttrB)
3354       return true;
3355     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3356            AttrA->isDynamic() == AttrB->isDynamic();
3357   };
3358 
3359   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3360 }
3361 
3362 /// If necessary, adjust the semantic declaration context for a qualified
3363 /// declaration to name the correct inline namespace within the qualifier.
3364 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3365                                                DeclaratorDecl *OldD) {
3366   // The only case where we need to update the DeclContext is when
3367   // redeclaration lookup for a qualified name finds a declaration
3368   // in an inline namespace within the context named by the qualifier:
3369   //
3370   //   inline namespace N { int f(); }
3371   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3372   //
3373   // For unqualified declarations, the semantic context *can* change
3374   // along the redeclaration chain (for local extern declarations,
3375   // extern "C" declarations, and friend declarations in particular).
3376   if (!NewD->getQualifier())
3377     return;
3378 
3379   // NewD is probably already in the right context.
3380   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3381   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3382   if (NamedDC->Equals(SemaDC))
3383     return;
3384 
3385   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3386           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3387          "unexpected context for redeclaration");
3388 
3389   auto *LexDC = NewD->getLexicalDeclContext();
3390   auto FixSemaDC = [=](NamedDecl *D) {
3391     if (!D)
3392       return;
3393     D->setDeclContext(SemaDC);
3394     D->setLexicalDeclContext(LexDC);
3395   };
3396 
3397   FixSemaDC(NewD);
3398   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3399     FixSemaDC(FD->getDescribedFunctionTemplate());
3400   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3401     FixSemaDC(VD->getDescribedVarTemplate());
3402 }
3403 
3404 /// MergeFunctionDecl - We just parsed a function 'New' from
3405 /// declarator D which has the same name and scope as a previous
3406 /// declaration 'Old'.  Figure out how to resolve this situation,
3407 /// merging decls or emitting diagnostics as appropriate.
3408 ///
3409 /// In C++, New and Old must be declarations that are not
3410 /// overloaded. Use IsOverload to determine whether New and Old are
3411 /// overloaded, and to select the Old declaration that New should be
3412 /// merged with.
3413 ///
3414 /// Returns true if there was an error, false otherwise.
3415 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3416                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3417   // Verify the old decl was also a function.
3418   FunctionDecl *Old = OldD->getAsFunction();
3419   if (!Old) {
3420     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3421       if (New->getFriendObjectKind()) {
3422         Diag(New->getLocation(), diag::err_using_decl_friend);
3423         Diag(Shadow->getTargetDecl()->getLocation(),
3424              diag::note_using_decl_target);
3425         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3426             << 0;
3427         return true;
3428       }
3429 
3430       // Check whether the two declarations might declare the same function or
3431       // function template.
3432       if (FunctionTemplateDecl *NewTemplate =
3433               New->getDescribedFunctionTemplate()) {
3434         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3435                                                          NewTemplate))
3436           return true;
3437         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3438                          ->getAsFunction();
3439       } else {
3440         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3441           return true;
3442         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3443       }
3444     } else {
3445       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3446         << New->getDeclName();
3447       notePreviousDefinition(OldD, New->getLocation());
3448       return true;
3449     }
3450   }
3451 
3452   // If the old declaration was found in an inline namespace and the new
3453   // declaration was qualified, update the DeclContext to match.
3454   adjustDeclContextForDeclaratorDecl(New, Old);
3455 
3456   // If the old declaration is invalid, just give up here.
3457   if (Old->isInvalidDecl())
3458     return true;
3459 
3460   // Disallow redeclaration of some builtins.
3461   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3462     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3463     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3464         << Old << Old->getType();
3465     return true;
3466   }
3467 
3468   diag::kind PrevDiag;
3469   SourceLocation OldLocation;
3470   std::tie(PrevDiag, OldLocation) =
3471       getNoteDiagForInvalidRedeclaration(Old, New);
3472 
3473   // Don't complain about this if we're in GNU89 mode and the old function
3474   // is an extern inline function.
3475   // Don't complain about specializations. They are not supposed to have
3476   // storage classes.
3477   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3478       New->getStorageClass() == SC_Static &&
3479       Old->hasExternalFormalLinkage() &&
3480       !New->getTemplateSpecializationInfo() &&
3481       !canRedefineFunction(Old, getLangOpts())) {
3482     if (getLangOpts().MicrosoftExt) {
3483       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3484       Diag(OldLocation, PrevDiag);
3485     } else {
3486       Diag(New->getLocation(), diag::err_static_non_static) << New;
3487       Diag(OldLocation, PrevDiag);
3488       return true;
3489     }
3490   }
3491 
3492   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3493     if (!Old->hasAttr<InternalLinkageAttr>()) {
3494       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3495           << ILA;
3496       Diag(Old->getLocation(), diag::note_previous_declaration);
3497       New->dropAttr<InternalLinkageAttr>();
3498     }
3499 
3500   if (auto *EA = New->getAttr<ErrorAttr>()) {
3501     if (!Old->hasAttr<ErrorAttr>()) {
3502       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3503       Diag(Old->getLocation(), diag::note_previous_declaration);
3504       New->dropAttr<ErrorAttr>();
3505     }
3506   }
3507 
3508   if (CheckRedeclarationInModule(New, Old))
3509     return true;
3510 
3511   if (!getLangOpts().CPlusPlus) {
3512     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3513     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3514       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3515         << New << OldOvl;
3516 
3517       // Try our best to find a decl that actually has the overloadable
3518       // attribute for the note. In most cases (e.g. programs with only one
3519       // broken declaration/definition), this won't matter.
3520       //
3521       // FIXME: We could do this if we juggled some extra state in
3522       // OverloadableAttr, rather than just removing it.
3523       const Decl *DiagOld = Old;
3524       if (OldOvl) {
3525         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3526           const auto *A = D->getAttr<OverloadableAttr>();
3527           return A && !A->isImplicit();
3528         });
3529         // If we've implicitly added *all* of the overloadable attrs to this
3530         // chain, emitting a "previous redecl" note is pointless.
3531         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3532       }
3533 
3534       if (DiagOld)
3535         Diag(DiagOld->getLocation(),
3536              diag::note_attribute_overloadable_prev_overload)
3537           << OldOvl;
3538 
3539       if (OldOvl)
3540         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3541       else
3542         New->dropAttr<OverloadableAttr>();
3543     }
3544   }
3545 
3546   // If a function is first declared with a calling convention, but is later
3547   // declared or defined without one, all following decls assume the calling
3548   // convention of the first.
3549   //
3550   // It's OK if a function is first declared without a calling convention,
3551   // but is later declared or defined with the default calling convention.
3552   //
3553   // To test if either decl has an explicit calling convention, we look for
3554   // AttributedType sugar nodes on the type as written.  If they are missing or
3555   // were canonicalized away, we assume the calling convention was implicit.
3556   //
3557   // Note also that we DO NOT return at this point, because we still have
3558   // other tests to run.
3559   QualType OldQType = Context.getCanonicalType(Old->getType());
3560   QualType NewQType = Context.getCanonicalType(New->getType());
3561   const FunctionType *OldType = cast<FunctionType>(OldQType);
3562   const FunctionType *NewType = cast<FunctionType>(NewQType);
3563   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3564   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3565   bool RequiresAdjustment = false;
3566 
3567   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3568     FunctionDecl *First = Old->getFirstDecl();
3569     const FunctionType *FT =
3570         First->getType().getCanonicalType()->castAs<FunctionType>();
3571     FunctionType::ExtInfo FI = FT->getExtInfo();
3572     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3573     if (!NewCCExplicit) {
3574       // Inherit the CC from the previous declaration if it was specified
3575       // there but not here.
3576       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3577       RequiresAdjustment = true;
3578     } else if (Old->getBuiltinID()) {
3579       // Builtin attribute isn't propagated to the new one yet at this point,
3580       // so we check if the old one is a builtin.
3581 
3582       // Calling Conventions on a Builtin aren't really useful and setting a
3583       // default calling convention and cdecl'ing some builtin redeclarations is
3584       // common, so warn and ignore the calling convention on the redeclaration.
3585       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3586           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3587           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3588       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3589       RequiresAdjustment = true;
3590     } else {
3591       // Calling conventions aren't compatible, so complain.
3592       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3593       Diag(New->getLocation(), diag::err_cconv_change)
3594         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3595         << !FirstCCExplicit
3596         << (!FirstCCExplicit ? "" :
3597             FunctionType::getNameForCallConv(FI.getCC()));
3598 
3599       // Put the note on the first decl, since it is the one that matters.
3600       Diag(First->getLocation(), diag::note_previous_declaration);
3601       return true;
3602     }
3603   }
3604 
3605   // FIXME: diagnose the other way around?
3606   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3607     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3608     RequiresAdjustment = true;
3609   }
3610 
3611   // Merge regparm attribute.
3612   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3613       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3614     if (NewTypeInfo.getHasRegParm()) {
3615       Diag(New->getLocation(), diag::err_regparm_mismatch)
3616         << NewType->getRegParmType()
3617         << OldType->getRegParmType();
3618       Diag(OldLocation, diag::note_previous_declaration);
3619       return true;
3620     }
3621 
3622     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3623     RequiresAdjustment = true;
3624   }
3625 
3626   // Merge ns_returns_retained attribute.
3627   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3628     if (NewTypeInfo.getProducesResult()) {
3629       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3630           << "'ns_returns_retained'";
3631       Diag(OldLocation, diag::note_previous_declaration);
3632       return true;
3633     }
3634 
3635     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3636     RequiresAdjustment = true;
3637   }
3638 
3639   if (OldTypeInfo.getNoCallerSavedRegs() !=
3640       NewTypeInfo.getNoCallerSavedRegs()) {
3641     if (NewTypeInfo.getNoCallerSavedRegs()) {
3642       AnyX86NoCallerSavedRegistersAttr *Attr =
3643         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3644       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3645       Diag(OldLocation, diag::note_previous_declaration);
3646       return true;
3647     }
3648 
3649     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3650     RequiresAdjustment = true;
3651   }
3652 
3653   if (RequiresAdjustment) {
3654     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3655     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3656     New->setType(QualType(AdjustedType, 0));
3657     NewQType = Context.getCanonicalType(New->getType());
3658   }
3659 
3660   // If this redeclaration makes the function inline, we may need to add it to
3661   // UndefinedButUsed.
3662   if (!Old->isInlined() && New->isInlined() &&
3663       !New->hasAttr<GNUInlineAttr>() &&
3664       !getLangOpts().GNUInline &&
3665       Old->isUsed(false) &&
3666       !Old->isDefined() && !New->isThisDeclarationADefinition())
3667     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3668                                            SourceLocation()));
3669 
3670   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3671   // about it.
3672   if (New->hasAttr<GNUInlineAttr>() &&
3673       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3674     UndefinedButUsed.erase(Old->getCanonicalDecl());
3675   }
3676 
3677   // If pass_object_size params don't match up perfectly, this isn't a valid
3678   // redeclaration.
3679   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3680       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3681     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3682         << New->getDeclName();
3683     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3684     return true;
3685   }
3686 
3687   if (getLangOpts().CPlusPlus) {
3688     // C++1z [over.load]p2
3689     //   Certain function declarations cannot be overloaded:
3690     //     -- Function declarations that differ only in the return type,
3691     //        the exception specification, or both cannot be overloaded.
3692 
3693     // Check the exception specifications match. This may recompute the type of
3694     // both Old and New if it resolved exception specifications, so grab the
3695     // types again after this. Because this updates the type, we do this before
3696     // any of the other checks below, which may update the "de facto" NewQType
3697     // but do not necessarily update the type of New.
3698     if (CheckEquivalentExceptionSpec(Old, New))
3699       return true;
3700     OldQType = Context.getCanonicalType(Old->getType());
3701     NewQType = Context.getCanonicalType(New->getType());
3702 
3703     // Go back to the type source info to compare the declared return types,
3704     // per C++1y [dcl.type.auto]p13:
3705     //   Redeclarations or specializations of a function or function template
3706     //   with a declared return type that uses a placeholder type shall also
3707     //   use that placeholder, not a deduced type.
3708     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3709     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3710     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3711         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3712                                        OldDeclaredReturnType)) {
3713       QualType ResQT;
3714       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3715           OldDeclaredReturnType->isObjCObjectPointerType())
3716         // FIXME: This does the wrong thing for a deduced return type.
3717         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3718       if (ResQT.isNull()) {
3719         if (New->isCXXClassMember() && New->isOutOfLine())
3720           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3721               << New << New->getReturnTypeSourceRange();
3722         else
3723           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3724               << New->getReturnTypeSourceRange();
3725         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3726                                     << Old->getReturnTypeSourceRange();
3727         return true;
3728       }
3729       else
3730         NewQType = ResQT;
3731     }
3732 
3733     QualType OldReturnType = OldType->getReturnType();
3734     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3735     if (OldReturnType != NewReturnType) {
3736       // If this function has a deduced return type and has already been
3737       // defined, copy the deduced value from the old declaration.
3738       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3739       if (OldAT && OldAT->isDeduced()) {
3740         QualType DT = OldAT->getDeducedType();
3741         if (DT.isNull()) {
3742           New->setType(SubstAutoTypeDependent(New->getType()));
3743           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3744         } else {
3745           New->setType(SubstAutoType(New->getType(), DT));
3746           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3747         }
3748       }
3749     }
3750 
3751     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3752     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3753     if (OldMethod && NewMethod) {
3754       // Preserve triviality.
3755       NewMethod->setTrivial(OldMethod->isTrivial());
3756 
3757       // MSVC allows explicit template specialization at class scope:
3758       // 2 CXXMethodDecls referring to the same function will be injected.
3759       // We don't want a redeclaration error.
3760       bool IsClassScopeExplicitSpecialization =
3761                               OldMethod->isFunctionTemplateSpecialization() &&
3762                               NewMethod->isFunctionTemplateSpecialization();
3763       bool isFriend = NewMethod->getFriendObjectKind();
3764 
3765       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3766           !IsClassScopeExplicitSpecialization) {
3767         //    -- Member function declarations with the same name and the
3768         //       same parameter types cannot be overloaded if any of them
3769         //       is a static member function declaration.
3770         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3771           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3772           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3773           return true;
3774         }
3775 
3776         // C++ [class.mem]p1:
3777         //   [...] A member shall not be declared twice in the
3778         //   member-specification, except that a nested class or member
3779         //   class template can be declared and then later defined.
3780         if (!inTemplateInstantiation()) {
3781           unsigned NewDiag;
3782           if (isa<CXXConstructorDecl>(OldMethod))
3783             NewDiag = diag::err_constructor_redeclared;
3784           else if (isa<CXXDestructorDecl>(NewMethod))
3785             NewDiag = diag::err_destructor_redeclared;
3786           else if (isa<CXXConversionDecl>(NewMethod))
3787             NewDiag = diag::err_conv_function_redeclared;
3788           else
3789             NewDiag = diag::err_member_redeclared;
3790 
3791           Diag(New->getLocation(), NewDiag);
3792         } else {
3793           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3794             << New << New->getType();
3795         }
3796         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3797         return true;
3798 
3799       // Complain if this is an explicit declaration of a special
3800       // member that was initially declared implicitly.
3801       //
3802       // As an exception, it's okay to befriend such methods in order
3803       // to permit the implicit constructor/destructor/operator calls.
3804       } else if (OldMethod->isImplicit()) {
3805         if (isFriend) {
3806           NewMethod->setImplicit();
3807         } else {
3808           Diag(NewMethod->getLocation(),
3809                diag::err_definition_of_implicitly_declared_member)
3810             << New << getSpecialMember(OldMethod);
3811           return true;
3812         }
3813       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3814         Diag(NewMethod->getLocation(),
3815              diag::err_definition_of_explicitly_defaulted_member)
3816           << getSpecialMember(OldMethod);
3817         return true;
3818       }
3819     }
3820 
3821     // C++11 [dcl.attr.noreturn]p1:
3822     //   The first declaration of a function shall specify the noreturn
3823     //   attribute if any declaration of that function specifies the noreturn
3824     //   attribute.
3825     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3826       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3827         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3828             << NRA;
3829         Diag(Old->getLocation(), diag::note_previous_declaration);
3830       }
3831 
3832     // C++11 [dcl.attr.depend]p2:
3833     //   The first declaration of a function shall specify the
3834     //   carries_dependency attribute for its declarator-id if any declaration
3835     //   of the function specifies the carries_dependency attribute.
3836     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3837     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3838       Diag(CDA->getLocation(),
3839            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3840       Diag(Old->getFirstDecl()->getLocation(),
3841            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3842     }
3843 
3844     // (C++98 8.3.5p3):
3845     //   All declarations for a function shall agree exactly in both the
3846     //   return type and the parameter-type-list.
3847     // We also want to respect all the extended bits except noreturn.
3848 
3849     // noreturn should now match unless the old type info didn't have it.
3850     QualType OldQTypeForComparison = OldQType;
3851     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3852       auto *OldType = OldQType->castAs<FunctionProtoType>();
3853       const FunctionType *OldTypeForComparison
3854         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3855       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3856       assert(OldQTypeForComparison.isCanonical());
3857     }
3858 
3859     if (haveIncompatibleLanguageLinkages(Old, New)) {
3860       // As a special case, retain the language linkage from previous
3861       // declarations of a friend function as an extension.
3862       //
3863       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3864       // and is useful because there's otherwise no way to specify language
3865       // linkage within class scope.
3866       //
3867       // Check cautiously as the friend object kind isn't yet complete.
3868       if (New->getFriendObjectKind() != Decl::FOK_None) {
3869         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3870         Diag(OldLocation, PrevDiag);
3871       } else {
3872         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3873         Diag(OldLocation, PrevDiag);
3874         return true;
3875       }
3876     }
3877 
3878     // If the function types are compatible, merge the declarations. Ignore the
3879     // exception specifier because it was already checked above in
3880     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3881     // about incompatible types under -fms-compatibility.
3882     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3883                                                          NewQType))
3884       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3885 
3886     // If the types are imprecise (due to dependent constructs in friends or
3887     // local extern declarations), it's OK if they differ. We'll check again
3888     // during instantiation.
3889     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3890       return false;
3891 
3892     // Fall through for conflicting redeclarations and redefinitions.
3893   }
3894 
3895   // C: Function types need to be compatible, not identical. This handles
3896   // duplicate function decls like "void f(int); void f(enum X);" properly.
3897   if (!getLangOpts().CPlusPlus) {
3898     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3899     // type is specified by a function definition that contains a (possibly
3900     // empty) identifier list, both shall agree in the number of parameters
3901     // and the type of each parameter shall be compatible with the type that
3902     // results from the application of default argument promotions to the
3903     // type of the corresponding identifier. ...
3904     // This cannot be handled by ASTContext::typesAreCompatible() because that
3905     // doesn't know whether the function type is for a definition or not when
3906     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3907     // we need to cover here is that the number of arguments agree as the
3908     // default argument promotion rules were already checked by
3909     // ASTContext::typesAreCompatible().
3910     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3911         Old->getNumParams() != New->getNumParams()) {
3912       if (Old->hasInheritedPrototype())
3913         Old = Old->getCanonicalDecl();
3914       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3915       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3916       return true;
3917     }
3918 
3919     // If we are merging two functions where only one of them has a prototype,
3920     // we may have enough information to decide to issue a diagnostic that the
3921     // function without a protoype will change behavior in C2x. This handles
3922     // cases like:
3923     //   void i(); void i(int j);
3924     //   void i(int j); void i();
3925     //   void i(); void i(int j) {}
3926     // See ActOnFinishFunctionBody() for other cases of the behavior change
3927     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3928     // type without a prototype.
3929     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3930         !New->isImplicit() && !Old->isImplicit()) {
3931       const FunctionDecl *WithProto, *WithoutProto;
3932       if (New->hasWrittenPrototype()) {
3933         WithProto = New;
3934         WithoutProto = Old;
3935       } else {
3936         WithProto = Old;
3937         WithoutProto = New;
3938       }
3939 
3940       if (WithProto->getNumParams() != 0) {
3941         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3942           // The one without the prototype will be changing behavior in C2x, so
3943           // warn about that one so long as it's a user-visible declaration.
3944           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3945           if (WithoutProto == New)
3946             IsWithoutProtoADef = NewDeclIsDefn;
3947           else
3948             IsWithProtoADef = NewDeclIsDefn;
3949           Diag(WithoutProto->getLocation(),
3950                diag::warn_non_prototype_changes_behavior)
3951               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
3952               << (WithoutProto == Old) << IsWithProtoADef;
3953 
3954           // The reason the one without the prototype will be changing behavior
3955           // is because of the one with the prototype, so note that so long as
3956           // it's a user-visible declaration. There is one exception to this:
3957           // when the new declaration is a definition without a prototype, the
3958           // old declaration with a prototype is not the cause of the issue,
3959           // and that does not need to be noted because the one with a
3960           // prototype will not change behavior in C2x.
3961           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
3962               !IsWithoutProtoADef)
3963             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
3964         }
3965       }
3966     }
3967 
3968     if (Context.typesAreCompatible(OldQType, NewQType)) {
3969       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3970       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3971       const FunctionProtoType *OldProto = nullptr;
3972       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3973           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3974         // The old declaration provided a function prototype, but the
3975         // new declaration does not. Merge in the prototype.
3976         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3977         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3978         NewQType =
3979             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3980                                     OldProto->getExtProtoInfo());
3981         New->setType(NewQType);
3982         New->setHasInheritedPrototype();
3983 
3984         // Synthesize parameters with the same types.
3985         SmallVector<ParmVarDecl *, 16> Params;
3986         for (const auto &ParamType : OldProto->param_types()) {
3987           ParmVarDecl *Param = ParmVarDecl::Create(
3988               Context, New, SourceLocation(), SourceLocation(), nullptr,
3989               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
3990           Param->setScopeInfo(0, Params.size());
3991           Param->setImplicit();
3992           Params.push_back(Param);
3993         }
3994 
3995         New->setParams(Params);
3996       }
3997 
3998       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3999     }
4000   }
4001 
4002   // Check if the function types are compatible when pointer size address
4003   // spaces are ignored.
4004   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4005     return false;
4006 
4007   // GNU C permits a K&R definition to follow a prototype declaration
4008   // if the declared types of the parameters in the K&R definition
4009   // match the types in the prototype declaration, even when the
4010   // promoted types of the parameters from the K&R definition differ
4011   // from the types in the prototype. GCC then keeps the types from
4012   // the prototype.
4013   //
4014   // If a variadic prototype is followed by a non-variadic K&R definition,
4015   // the K&R definition becomes variadic.  This is sort of an edge case, but
4016   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4017   // C99 6.9.1p8.
4018   if (!getLangOpts().CPlusPlus &&
4019       Old->hasPrototype() && !New->hasPrototype() &&
4020       New->getType()->getAs<FunctionProtoType>() &&
4021       Old->getNumParams() == New->getNumParams()) {
4022     SmallVector<QualType, 16> ArgTypes;
4023     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4024     const FunctionProtoType *OldProto
4025       = Old->getType()->getAs<FunctionProtoType>();
4026     const FunctionProtoType *NewProto
4027       = New->getType()->getAs<FunctionProtoType>();
4028 
4029     // Determine whether this is the GNU C extension.
4030     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4031                                                NewProto->getReturnType());
4032     bool LooseCompatible = !MergedReturn.isNull();
4033     for (unsigned Idx = 0, End = Old->getNumParams();
4034          LooseCompatible && Idx != End; ++Idx) {
4035       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4036       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4037       if (Context.typesAreCompatible(OldParm->getType(),
4038                                      NewProto->getParamType(Idx))) {
4039         ArgTypes.push_back(NewParm->getType());
4040       } else if (Context.typesAreCompatible(OldParm->getType(),
4041                                             NewParm->getType(),
4042                                             /*CompareUnqualified=*/true)) {
4043         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4044                                            NewProto->getParamType(Idx) };
4045         Warnings.push_back(Warn);
4046         ArgTypes.push_back(NewParm->getType());
4047       } else
4048         LooseCompatible = false;
4049     }
4050 
4051     if (LooseCompatible) {
4052       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4053         Diag(Warnings[Warn].NewParm->getLocation(),
4054              diag::ext_param_promoted_not_compatible_with_prototype)
4055           << Warnings[Warn].PromotedType
4056           << Warnings[Warn].OldParm->getType();
4057         if (Warnings[Warn].OldParm->getLocation().isValid())
4058           Diag(Warnings[Warn].OldParm->getLocation(),
4059                diag::note_previous_declaration);
4060       }
4061 
4062       if (MergeTypeWithOld)
4063         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4064                                              OldProto->getExtProtoInfo()));
4065       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4066     }
4067 
4068     // Fall through to diagnose conflicting types.
4069   }
4070 
4071   // A function that has already been declared has been redeclared or
4072   // defined with a different type; show an appropriate diagnostic.
4073 
4074   // If the previous declaration was an implicitly-generated builtin
4075   // declaration, then at the very least we should use a specialized note.
4076   unsigned BuiltinID;
4077   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4078     // If it's actually a library-defined builtin function like 'malloc'
4079     // or 'printf', just warn about the incompatible redeclaration.
4080     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4081       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4082       Diag(OldLocation, diag::note_previous_builtin_declaration)
4083         << Old << Old->getType();
4084       return false;
4085     }
4086 
4087     PrevDiag = diag::note_previous_builtin_declaration;
4088   }
4089 
4090   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4091   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4092   return true;
4093 }
4094 
4095 /// Completes the merge of two function declarations that are
4096 /// known to be compatible.
4097 ///
4098 /// This routine handles the merging of attributes and other
4099 /// properties of function declarations from the old declaration to
4100 /// the new declaration, once we know that New is in fact a
4101 /// redeclaration of Old.
4102 ///
4103 /// \returns false
4104 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4105                                         Scope *S, bool MergeTypeWithOld) {
4106   // Merge the attributes
4107   mergeDeclAttributes(New, Old);
4108 
4109   // Merge "pure" flag.
4110   if (Old->isPure())
4111     New->setPure();
4112 
4113   // Merge "used" flag.
4114   if (Old->getMostRecentDecl()->isUsed(false))
4115     New->setIsUsed();
4116 
4117   // Merge attributes from the parameters.  These can mismatch with K&R
4118   // declarations.
4119   if (New->getNumParams() == Old->getNumParams())
4120       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4121         ParmVarDecl *NewParam = New->getParamDecl(i);
4122         ParmVarDecl *OldParam = Old->getParamDecl(i);
4123         mergeParamDeclAttributes(NewParam, OldParam, *this);
4124         mergeParamDeclTypes(NewParam, OldParam, *this);
4125       }
4126 
4127   if (getLangOpts().CPlusPlus)
4128     return MergeCXXFunctionDecl(New, Old, S);
4129 
4130   // Merge the function types so the we get the composite types for the return
4131   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4132   // was visible.
4133   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4134   if (!Merged.isNull() && MergeTypeWithOld)
4135     New->setType(Merged);
4136 
4137   return false;
4138 }
4139 
4140 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4141                                 ObjCMethodDecl *oldMethod) {
4142   // Merge the attributes, including deprecated/unavailable
4143   AvailabilityMergeKind MergeKind =
4144       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4145           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4146                                      : AMK_ProtocolImplementation)
4147           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4148                                                            : AMK_Override;
4149 
4150   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4151 
4152   // Merge attributes from the parameters.
4153   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4154                                        oe = oldMethod->param_end();
4155   for (ObjCMethodDecl::param_iterator
4156          ni = newMethod->param_begin(), ne = newMethod->param_end();
4157        ni != ne && oi != oe; ++ni, ++oi)
4158     mergeParamDeclAttributes(*ni, *oi, *this);
4159 
4160   CheckObjCMethodOverride(newMethod, oldMethod);
4161 }
4162 
4163 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4164   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4165 
4166   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4167          ? diag::err_redefinition_different_type
4168          : diag::err_redeclaration_different_type)
4169     << New->getDeclName() << New->getType() << Old->getType();
4170 
4171   diag::kind PrevDiag;
4172   SourceLocation OldLocation;
4173   std::tie(PrevDiag, OldLocation)
4174     = getNoteDiagForInvalidRedeclaration(Old, New);
4175   S.Diag(OldLocation, PrevDiag);
4176   New->setInvalidDecl();
4177 }
4178 
4179 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4180 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4181 /// emitting diagnostics as appropriate.
4182 ///
4183 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4184 /// to here in AddInitializerToDecl. We can't check them before the initializer
4185 /// is attached.
4186 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4187                              bool MergeTypeWithOld) {
4188   if (New->isInvalidDecl() || Old->isInvalidDecl())
4189     return;
4190 
4191   QualType MergedT;
4192   if (getLangOpts().CPlusPlus) {
4193     if (New->getType()->isUndeducedType()) {
4194       // We don't know what the new type is until the initializer is attached.
4195       return;
4196     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4197       // These could still be something that needs exception specs checked.
4198       return MergeVarDeclExceptionSpecs(New, Old);
4199     }
4200     // C++ [basic.link]p10:
4201     //   [...] the types specified by all declarations referring to a given
4202     //   object or function shall be identical, except that declarations for an
4203     //   array object can specify array types that differ by the presence or
4204     //   absence of a major array bound (8.3.4).
4205     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4206       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4207       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4208 
4209       // We are merging a variable declaration New into Old. If it has an array
4210       // bound, and that bound differs from Old's bound, we should diagnose the
4211       // mismatch.
4212       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4213         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4214              PrevVD = PrevVD->getPreviousDecl()) {
4215           QualType PrevVDTy = PrevVD->getType();
4216           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4217             continue;
4218 
4219           if (!Context.hasSameType(New->getType(), PrevVDTy))
4220             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4221         }
4222       }
4223 
4224       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4225         if (Context.hasSameType(OldArray->getElementType(),
4226                                 NewArray->getElementType()))
4227           MergedT = New->getType();
4228       }
4229       // FIXME: Check visibility. New is hidden but has a complete type. If New
4230       // has no array bound, it should not inherit one from Old, if Old is not
4231       // visible.
4232       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4233         if (Context.hasSameType(OldArray->getElementType(),
4234                                 NewArray->getElementType()))
4235           MergedT = Old->getType();
4236       }
4237     }
4238     else if (New->getType()->isObjCObjectPointerType() &&
4239                Old->getType()->isObjCObjectPointerType()) {
4240       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4241                                               Old->getType());
4242     }
4243   } else {
4244     // C 6.2.7p2:
4245     //   All declarations that refer to the same object or function shall have
4246     //   compatible type.
4247     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4248   }
4249   if (MergedT.isNull()) {
4250     // It's OK if we couldn't merge types if either type is dependent, for a
4251     // block-scope variable. In other cases (static data members of class
4252     // templates, variable templates, ...), we require the types to be
4253     // equivalent.
4254     // FIXME: The C++ standard doesn't say anything about this.
4255     if ((New->getType()->isDependentType() ||
4256          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4257       // If the old type was dependent, we can't merge with it, so the new type
4258       // becomes dependent for now. We'll reproduce the original type when we
4259       // instantiate the TypeSourceInfo for the variable.
4260       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4261         New->setType(Context.DependentTy);
4262       return;
4263     }
4264     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4265   }
4266 
4267   // Don't actually update the type on the new declaration if the old
4268   // declaration was an extern declaration in a different scope.
4269   if (MergeTypeWithOld)
4270     New->setType(MergedT);
4271 }
4272 
4273 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4274                                   LookupResult &Previous) {
4275   // C11 6.2.7p4:
4276   //   For an identifier with internal or external linkage declared
4277   //   in a scope in which a prior declaration of that identifier is
4278   //   visible, if the prior declaration specifies internal or
4279   //   external linkage, the type of the identifier at the later
4280   //   declaration becomes the composite type.
4281   //
4282   // If the variable isn't visible, we do not merge with its type.
4283   if (Previous.isShadowed())
4284     return false;
4285 
4286   if (S.getLangOpts().CPlusPlus) {
4287     // C++11 [dcl.array]p3:
4288     //   If there is a preceding declaration of the entity in the same
4289     //   scope in which the bound was specified, an omitted array bound
4290     //   is taken to be the same as in that earlier declaration.
4291     return NewVD->isPreviousDeclInSameBlockScope() ||
4292            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4293             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4294   } else {
4295     // If the old declaration was function-local, don't merge with its
4296     // type unless we're in the same function.
4297     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4298            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4299   }
4300 }
4301 
4302 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4303 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4304 /// situation, merging decls or emitting diagnostics as appropriate.
4305 ///
4306 /// Tentative definition rules (C99 6.9.2p2) are checked by
4307 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4308 /// definitions here, since the initializer hasn't been attached.
4309 ///
4310 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4311   // If the new decl is already invalid, don't do any other checking.
4312   if (New->isInvalidDecl())
4313     return;
4314 
4315   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4316     return;
4317 
4318   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4319 
4320   // Verify the old decl was also a variable or variable template.
4321   VarDecl *Old = nullptr;
4322   VarTemplateDecl *OldTemplate = nullptr;
4323   if (Previous.isSingleResult()) {
4324     if (NewTemplate) {
4325       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4326       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4327 
4328       if (auto *Shadow =
4329               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4330         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4331           return New->setInvalidDecl();
4332     } else {
4333       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4334 
4335       if (auto *Shadow =
4336               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4337         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4338           return New->setInvalidDecl();
4339     }
4340   }
4341   if (!Old) {
4342     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4343         << New->getDeclName();
4344     notePreviousDefinition(Previous.getRepresentativeDecl(),
4345                            New->getLocation());
4346     return New->setInvalidDecl();
4347   }
4348 
4349   // If the old declaration was found in an inline namespace and the new
4350   // declaration was qualified, update the DeclContext to match.
4351   adjustDeclContextForDeclaratorDecl(New, Old);
4352 
4353   // Ensure the template parameters are compatible.
4354   if (NewTemplate &&
4355       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4356                                       OldTemplate->getTemplateParameters(),
4357                                       /*Complain=*/true, TPL_TemplateMatch))
4358     return New->setInvalidDecl();
4359 
4360   // C++ [class.mem]p1:
4361   //   A member shall not be declared twice in the member-specification [...]
4362   //
4363   // Here, we need only consider static data members.
4364   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4365     Diag(New->getLocation(), diag::err_duplicate_member)
4366       << New->getIdentifier();
4367     Diag(Old->getLocation(), diag::note_previous_declaration);
4368     New->setInvalidDecl();
4369   }
4370 
4371   mergeDeclAttributes(New, Old);
4372   // Warn if an already-declared variable is made a weak_import in a subsequent
4373   // declaration
4374   if (New->hasAttr<WeakImportAttr>() &&
4375       Old->getStorageClass() == SC_None &&
4376       !Old->hasAttr<WeakImportAttr>()) {
4377     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4378     Diag(Old->getLocation(), diag::note_previous_declaration);
4379     // Remove weak_import attribute on new declaration.
4380     New->dropAttr<WeakImportAttr>();
4381   }
4382 
4383   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4384     if (!Old->hasAttr<InternalLinkageAttr>()) {
4385       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4386           << ILA;
4387       Diag(Old->getLocation(), diag::note_previous_declaration);
4388       New->dropAttr<InternalLinkageAttr>();
4389     }
4390 
4391   // Merge the types.
4392   VarDecl *MostRecent = Old->getMostRecentDecl();
4393   if (MostRecent != Old) {
4394     MergeVarDeclTypes(New, MostRecent,
4395                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4396     if (New->isInvalidDecl())
4397       return;
4398   }
4399 
4400   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4401   if (New->isInvalidDecl())
4402     return;
4403 
4404   diag::kind PrevDiag;
4405   SourceLocation OldLocation;
4406   std::tie(PrevDiag, OldLocation) =
4407       getNoteDiagForInvalidRedeclaration(Old, New);
4408 
4409   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4410   if (New->getStorageClass() == SC_Static &&
4411       !New->isStaticDataMember() &&
4412       Old->hasExternalFormalLinkage()) {
4413     if (getLangOpts().MicrosoftExt) {
4414       Diag(New->getLocation(), diag::ext_static_non_static)
4415           << New->getDeclName();
4416       Diag(OldLocation, PrevDiag);
4417     } else {
4418       Diag(New->getLocation(), diag::err_static_non_static)
4419           << New->getDeclName();
4420       Diag(OldLocation, PrevDiag);
4421       return New->setInvalidDecl();
4422     }
4423   }
4424   // C99 6.2.2p4:
4425   //   For an identifier declared with the storage-class specifier
4426   //   extern in a scope in which a prior declaration of that
4427   //   identifier is visible,23) if the prior declaration specifies
4428   //   internal or external linkage, the linkage of the identifier at
4429   //   the later declaration is the same as the linkage specified at
4430   //   the prior declaration. If no prior declaration is visible, or
4431   //   if the prior declaration specifies no linkage, then the
4432   //   identifier has external linkage.
4433   if (New->hasExternalStorage() && Old->hasLinkage())
4434     /* Okay */;
4435   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4436            !New->isStaticDataMember() &&
4437            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4438     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4439     Diag(OldLocation, PrevDiag);
4440     return New->setInvalidDecl();
4441   }
4442 
4443   // Check if extern is followed by non-extern and vice-versa.
4444   if (New->hasExternalStorage() &&
4445       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4446     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4447     Diag(OldLocation, PrevDiag);
4448     return New->setInvalidDecl();
4449   }
4450   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4451       !New->hasExternalStorage()) {
4452     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4453     Diag(OldLocation, PrevDiag);
4454     return New->setInvalidDecl();
4455   }
4456 
4457   if (CheckRedeclarationInModule(New, Old))
4458     return;
4459 
4460   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4461 
4462   // FIXME: The test for external storage here seems wrong? We still
4463   // need to check for mismatches.
4464   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4465       // Don't complain about out-of-line definitions of static members.
4466       !(Old->getLexicalDeclContext()->isRecord() &&
4467         !New->getLexicalDeclContext()->isRecord())) {
4468     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4469     Diag(OldLocation, PrevDiag);
4470     return New->setInvalidDecl();
4471   }
4472 
4473   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4474     if (VarDecl *Def = Old->getDefinition()) {
4475       // C++1z [dcl.fcn.spec]p4:
4476       //   If the definition of a variable appears in a translation unit before
4477       //   its first declaration as inline, the program is ill-formed.
4478       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4479       Diag(Def->getLocation(), diag::note_previous_definition);
4480     }
4481   }
4482 
4483   // If this redeclaration makes the variable inline, we may need to add it to
4484   // UndefinedButUsed.
4485   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4486       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4487     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4488                                            SourceLocation()));
4489 
4490   if (New->getTLSKind() != Old->getTLSKind()) {
4491     if (!Old->getTLSKind()) {
4492       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4493       Diag(OldLocation, PrevDiag);
4494     } else if (!New->getTLSKind()) {
4495       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4496       Diag(OldLocation, PrevDiag);
4497     } else {
4498       // Do not allow redeclaration to change the variable between requiring
4499       // static and dynamic initialization.
4500       // FIXME: GCC allows this, but uses the TLS keyword on the first
4501       // declaration to determine the kind. Do we need to be compatible here?
4502       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4503         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4504       Diag(OldLocation, PrevDiag);
4505     }
4506   }
4507 
4508   // C++ doesn't have tentative definitions, so go right ahead and check here.
4509   if (getLangOpts().CPlusPlus) {
4510     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4511         Old->getCanonicalDecl()->isConstexpr()) {
4512       // This definition won't be a definition any more once it's been merged.
4513       Diag(New->getLocation(),
4514            diag::warn_deprecated_redundant_constexpr_static_def);
4515     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4516       VarDecl *Def = Old->getDefinition();
4517       if (Def && checkVarDeclRedefinition(Def, New))
4518         return;
4519     }
4520   }
4521 
4522   if (haveIncompatibleLanguageLinkages(Old, New)) {
4523     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4524     Diag(OldLocation, PrevDiag);
4525     New->setInvalidDecl();
4526     return;
4527   }
4528 
4529   // Merge "used" flag.
4530   if (Old->getMostRecentDecl()->isUsed(false))
4531     New->setIsUsed();
4532 
4533   // Keep a chain of previous declarations.
4534   New->setPreviousDecl(Old);
4535   if (NewTemplate)
4536     NewTemplate->setPreviousDecl(OldTemplate);
4537 
4538   // Inherit access appropriately.
4539   New->setAccess(Old->getAccess());
4540   if (NewTemplate)
4541     NewTemplate->setAccess(New->getAccess());
4542 
4543   if (Old->isInline())
4544     New->setImplicitlyInline();
4545 }
4546 
4547 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4548   SourceManager &SrcMgr = getSourceManager();
4549   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4550   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4551   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4552   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4553   auto &HSI = PP.getHeaderSearchInfo();
4554   StringRef HdrFilename =
4555       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4556 
4557   auto noteFromModuleOrInclude = [&](Module *Mod,
4558                                      SourceLocation IncLoc) -> bool {
4559     // Redefinition errors with modules are common with non modular mapped
4560     // headers, example: a non-modular header H in module A that also gets
4561     // included directly in a TU. Pointing twice to the same header/definition
4562     // is confusing, try to get better diagnostics when modules is on.
4563     if (IncLoc.isValid()) {
4564       if (Mod) {
4565         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4566             << HdrFilename.str() << Mod->getFullModuleName();
4567         if (!Mod->DefinitionLoc.isInvalid())
4568           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4569               << Mod->getFullModuleName();
4570       } else {
4571         Diag(IncLoc, diag::note_redefinition_include_same_file)
4572             << HdrFilename.str();
4573       }
4574       return true;
4575     }
4576 
4577     return false;
4578   };
4579 
4580   // Is it the same file and same offset? Provide more information on why
4581   // this leads to a redefinition error.
4582   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4583     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4584     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4585     bool EmittedDiag =
4586         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4587     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4588 
4589     // If the header has no guards, emit a note suggesting one.
4590     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4591       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4592 
4593     if (EmittedDiag)
4594       return;
4595   }
4596 
4597   // Redefinition coming from different files or couldn't do better above.
4598   if (Old->getLocation().isValid())
4599     Diag(Old->getLocation(), diag::note_previous_definition);
4600 }
4601 
4602 /// We've just determined that \p Old and \p New both appear to be definitions
4603 /// of the same variable. Either diagnose or fix the problem.
4604 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4605   if (!hasVisibleDefinition(Old) &&
4606       (New->getFormalLinkage() == InternalLinkage ||
4607        New->isInline() ||
4608        New->getDescribedVarTemplate() ||
4609        New->getNumTemplateParameterLists() ||
4610        New->getDeclContext()->isDependentContext())) {
4611     // The previous definition is hidden, and multiple definitions are
4612     // permitted (in separate TUs). Demote this to a declaration.
4613     New->demoteThisDefinitionToDeclaration();
4614 
4615     // Make the canonical definition visible.
4616     if (auto *OldTD = Old->getDescribedVarTemplate())
4617       makeMergedDefinitionVisible(OldTD);
4618     makeMergedDefinitionVisible(Old);
4619     return false;
4620   } else {
4621     Diag(New->getLocation(), diag::err_redefinition) << New;
4622     notePreviousDefinition(Old, New->getLocation());
4623     New->setInvalidDecl();
4624     return true;
4625   }
4626 }
4627 
4628 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4629 /// no declarator (e.g. "struct foo;") is parsed.
4630 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4631                                        DeclSpec &DS,
4632                                        const ParsedAttributesView &DeclAttrs,
4633                                        RecordDecl *&AnonRecord) {
4634   return ParsedFreeStandingDeclSpec(
4635       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4636 }
4637 
4638 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4639 // disambiguate entities defined in different scopes.
4640 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4641 // compatibility.
4642 // We will pick our mangling number depending on which version of MSVC is being
4643 // targeted.
4644 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4645   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4646              ? S->getMSCurManglingNumber()
4647              : S->getMSLastManglingNumber();
4648 }
4649 
4650 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4651   if (!Context.getLangOpts().CPlusPlus)
4652     return;
4653 
4654   if (isa<CXXRecordDecl>(Tag->getParent())) {
4655     // If this tag is the direct child of a class, number it if
4656     // it is anonymous.
4657     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4658       return;
4659     MangleNumberingContext &MCtx =
4660         Context.getManglingNumberContext(Tag->getParent());
4661     Context.setManglingNumber(
4662         Tag, MCtx.getManglingNumber(
4663                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4664     return;
4665   }
4666 
4667   // If this tag isn't a direct child of a class, number it if it is local.
4668   MangleNumberingContext *MCtx;
4669   Decl *ManglingContextDecl;
4670   std::tie(MCtx, ManglingContextDecl) =
4671       getCurrentMangleNumberContext(Tag->getDeclContext());
4672   if (MCtx) {
4673     Context.setManglingNumber(
4674         Tag, MCtx->getManglingNumber(
4675                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4676   }
4677 }
4678 
4679 namespace {
4680 struct NonCLikeKind {
4681   enum {
4682     None,
4683     BaseClass,
4684     DefaultMemberInit,
4685     Lambda,
4686     Friend,
4687     OtherMember,
4688     Invalid,
4689   } Kind = None;
4690   SourceRange Range;
4691 
4692   explicit operator bool() { return Kind != None; }
4693 };
4694 }
4695 
4696 /// Determine whether a class is C-like, according to the rules of C++
4697 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4698 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4699   if (RD->isInvalidDecl())
4700     return {NonCLikeKind::Invalid, {}};
4701 
4702   // C++ [dcl.typedef]p9: [P1766R1]
4703   //   An unnamed class with a typedef name for linkage purposes shall not
4704   //
4705   //    -- have any base classes
4706   if (RD->getNumBases())
4707     return {NonCLikeKind::BaseClass,
4708             SourceRange(RD->bases_begin()->getBeginLoc(),
4709                         RD->bases_end()[-1].getEndLoc())};
4710   bool Invalid = false;
4711   for (Decl *D : RD->decls()) {
4712     // Don't complain about things we already diagnosed.
4713     if (D->isInvalidDecl()) {
4714       Invalid = true;
4715       continue;
4716     }
4717 
4718     //  -- have any [...] default member initializers
4719     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4720       if (FD->hasInClassInitializer()) {
4721         auto *Init = FD->getInClassInitializer();
4722         return {NonCLikeKind::DefaultMemberInit,
4723                 Init ? Init->getSourceRange() : D->getSourceRange()};
4724       }
4725       continue;
4726     }
4727 
4728     // FIXME: We don't allow friend declarations. This violates the wording of
4729     // P1766, but not the intent.
4730     if (isa<FriendDecl>(D))
4731       return {NonCLikeKind::Friend, D->getSourceRange()};
4732 
4733     //  -- declare any members other than non-static data members, member
4734     //     enumerations, or member classes,
4735     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4736         isa<EnumDecl>(D))
4737       continue;
4738     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4739     if (!MemberRD) {
4740       if (D->isImplicit())
4741         continue;
4742       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4743     }
4744 
4745     //  -- contain a lambda-expression,
4746     if (MemberRD->isLambda())
4747       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4748 
4749     //  and all member classes shall also satisfy these requirements
4750     //  (recursively).
4751     if (MemberRD->isThisDeclarationADefinition()) {
4752       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4753         return Kind;
4754     }
4755   }
4756 
4757   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4758 }
4759 
4760 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4761                                         TypedefNameDecl *NewTD) {
4762   if (TagFromDeclSpec->isInvalidDecl())
4763     return;
4764 
4765   // Do nothing if the tag already has a name for linkage purposes.
4766   if (TagFromDeclSpec->hasNameForLinkage())
4767     return;
4768 
4769   // A well-formed anonymous tag must always be a TUK_Definition.
4770   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4771 
4772   // The type must match the tag exactly;  no qualifiers allowed.
4773   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4774                            Context.getTagDeclType(TagFromDeclSpec))) {
4775     if (getLangOpts().CPlusPlus)
4776       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4777     return;
4778   }
4779 
4780   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4781   //   An unnamed class with a typedef name for linkage purposes shall [be
4782   //   C-like].
4783   //
4784   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4785   // shouldn't happen, but there are constructs that the language rule doesn't
4786   // disallow for which we can't reasonably avoid computing linkage early.
4787   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4788   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4789                              : NonCLikeKind();
4790   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4791   if (NonCLike || ChangesLinkage) {
4792     if (NonCLike.Kind == NonCLikeKind::Invalid)
4793       return;
4794 
4795     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4796     if (ChangesLinkage) {
4797       // If the linkage changes, we can't accept this as an extension.
4798       if (NonCLike.Kind == NonCLikeKind::None)
4799         DiagID = diag::err_typedef_changes_linkage;
4800       else
4801         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4802     }
4803 
4804     SourceLocation FixitLoc =
4805         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4806     llvm::SmallString<40> TextToInsert;
4807     TextToInsert += ' ';
4808     TextToInsert += NewTD->getIdentifier()->getName();
4809 
4810     Diag(FixitLoc, DiagID)
4811       << isa<TypeAliasDecl>(NewTD)
4812       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4813     if (NonCLike.Kind != NonCLikeKind::None) {
4814       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4815         << NonCLike.Kind - 1 << NonCLike.Range;
4816     }
4817     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4818       << NewTD << isa<TypeAliasDecl>(NewTD);
4819 
4820     if (ChangesLinkage)
4821       return;
4822   }
4823 
4824   // Otherwise, set this as the anon-decl typedef for the tag.
4825   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4826 }
4827 
4828 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4829   switch (T) {
4830   case DeclSpec::TST_class:
4831     return 0;
4832   case DeclSpec::TST_struct:
4833     return 1;
4834   case DeclSpec::TST_interface:
4835     return 2;
4836   case DeclSpec::TST_union:
4837     return 3;
4838   case DeclSpec::TST_enum:
4839     return 4;
4840   default:
4841     llvm_unreachable("unexpected type specifier");
4842   }
4843 }
4844 
4845 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4846 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4847 /// parameters to cope with template friend declarations.
4848 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4849                                        DeclSpec &DS,
4850                                        const ParsedAttributesView &DeclAttrs,
4851                                        MultiTemplateParamsArg TemplateParams,
4852                                        bool IsExplicitInstantiation,
4853                                        RecordDecl *&AnonRecord) {
4854   Decl *TagD = nullptr;
4855   TagDecl *Tag = nullptr;
4856   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4857       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4858       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4859       DS.getTypeSpecType() == DeclSpec::TST_union ||
4860       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4861     TagD = DS.getRepAsDecl();
4862 
4863     if (!TagD) // We probably had an error
4864       return nullptr;
4865 
4866     // Note that the above type specs guarantee that the
4867     // type rep is a Decl, whereas in many of the others
4868     // it's a Type.
4869     if (isa<TagDecl>(TagD))
4870       Tag = cast<TagDecl>(TagD);
4871     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4872       Tag = CTD->getTemplatedDecl();
4873   }
4874 
4875   if (Tag) {
4876     handleTagNumbering(Tag, S);
4877     Tag->setFreeStanding();
4878     if (Tag->isInvalidDecl())
4879       return Tag;
4880   }
4881 
4882   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4883     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4884     // or incomplete types shall not be restrict-qualified."
4885     if (TypeQuals & DeclSpec::TQ_restrict)
4886       Diag(DS.getRestrictSpecLoc(),
4887            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4888            << DS.getSourceRange();
4889   }
4890 
4891   if (DS.isInlineSpecified())
4892     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4893         << getLangOpts().CPlusPlus17;
4894 
4895   if (DS.hasConstexprSpecifier()) {
4896     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4897     // and definitions of functions and variables.
4898     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4899     // the declaration of a function or function template
4900     if (Tag)
4901       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4902           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4903           << static_cast<int>(DS.getConstexprSpecifier());
4904     else
4905       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4906           << static_cast<int>(DS.getConstexprSpecifier());
4907     // Don't emit warnings after this error.
4908     return TagD;
4909   }
4910 
4911   DiagnoseFunctionSpecifiers(DS);
4912 
4913   if (DS.isFriendSpecified()) {
4914     // If we're dealing with a decl but not a TagDecl, assume that
4915     // whatever routines created it handled the friendship aspect.
4916     if (TagD && !Tag)
4917       return nullptr;
4918     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4919   }
4920 
4921   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4922   bool IsExplicitSpecialization =
4923     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4924   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4925       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4926       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4927     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4928     // nested-name-specifier unless it is an explicit instantiation
4929     // or an explicit specialization.
4930     //
4931     // FIXME: We allow class template partial specializations here too, per the
4932     // obvious intent of DR1819.
4933     //
4934     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4935     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4936         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4937     return nullptr;
4938   }
4939 
4940   // Track whether this decl-specifier declares anything.
4941   bool DeclaresAnything = true;
4942 
4943   // Handle anonymous struct definitions.
4944   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4945     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4946         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4947       if (getLangOpts().CPlusPlus ||
4948           Record->getDeclContext()->isRecord()) {
4949         // If CurContext is a DeclContext that can contain statements,
4950         // RecursiveASTVisitor won't visit the decls that
4951         // BuildAnonymousStructOrUnion() will put into CurContext.
4952         // Also store them here so that they can be part of the
4953         // DeclStmt that gets created in this case.
4954         // FIXME: Also return the IndirectFieldDecls created by
4955         // BuildAnonymousStructOr union, for the same reason?
4956         if (CurContext->isFunctionOrMethod())
4957           AnonRecord = Record;
4958         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4959                                            Context.getPrintingPolicy());
4960       }
4961 
4962       DeclaresAnything = false;
4963     }
4964   }
4965 
4966   // C11 6.7.2.1p2:
4967   //   A struct-declaration that does not declare an anonymous structure or
4968   //   anonymous union shall contain a struct-declarator-list.
4969   //
4970   // This rule also existed in C89 and C99; the grammar for struct-declaration
4971   // did not permit a struct-declaration without a struct-declarator-list.
4972   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4973       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4974     // Check for Microsoft C extension: anonymous struct/union member.
4975     // Handle 2 kinds of anonymous struct/union:
4976     //   struct STRUCT;
4977     //   union UNION;
4978     // and
4979     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4980     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4981     if ((Tag && Tag->getDeclName()) ||
4982         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4983       RecordDecl *Record = nullptr;
4984       if (Tag)
4985         Record = dyn_cast<RecordDecl>(Tag);
4986       else if (const RecordType *RT =
4987                    DS.getRepAsType().get()->getAsStructureType())
4988         Record = RT->getDecl();
4989       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4990         Record = UT->getDecl();
4991 
4992       if (Record && getLangOpts().MicrosoftExt) {
4993         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4994             << Record->isUnion() << DS.getSourceRange();
4995         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4996       }
4997 
4998       DeclaresAnything = false;
4999     }
5000   }
5001 
5002   // Skip all the checks below if we have a type error.
5003   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5004       (TagD && TagD->isInvalidDecl()))
5005     return TagD;
5006 
5007   if (getLangOpts().CPlusPlus &&
5008       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5009     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5010       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5011           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5012         DeclaresAnything = false;
5013 
5014   if (!DS.isMissingDeclaratorOk()) {
5015     // Customize diagnostic for a typedef missing a name.
5016     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5017       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5018           << DS.getSourceRange();
5019     else
5020       DeclaresAnything = false;
5021   }
5022 
5023   if (DS.isModulePrivateSpecified() &&
5024       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5025     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5026       << Tag->getTagKind()
5027       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5028 
5029   ActOnDocumentableDecl(TagD);
5030 
5031   // C 6.7/2:
5032   //   A declaration [...] shall declare at least a declarator [...], a tag,
5033   //   or the members of an enumeration.
5034   // C++ [dcl.dcl]p3:
5035   //   [If there are no declarators], and except for the declaration of an
5036   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5037   //   names into the program, or shall redeclare a name introduced by a
5038   //   previous declaration.
5039   if (!DeclaresAnything) {
5040     // In C, we allow this as a (popular) extension / bug. Don't bother
5041     // producing further diagnostics for redundant qualifiers after this.
5042     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5043                                ? diag::err_no_declarators
5044                                : diag::ext_no_declarators)
5045         << DS.getSourceRange();
5046     return TagD;
5047   }
5048 
5049   // C++ [dcl.stc]p1:
5050   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5051   //   init-declarator-list of the declaration shall not be empty.
5052   // C++ [dcl.fct.spec]p1:
5053   //   If a cv-qualifier appears in a decl-specifier-seq, the
5054   //   init-declarator-list of the declaration shall not be empty.
5055   //
5056   // Spurious qualifiers here appear to be valid in C.
5057   unsigned DiagID = diag::warn_standalone_specifier;
5058   if (getLangOpts().CPlusPlus)
5059     DiagID = diag::ext_standalone_specifier;
5060 
5061   // Note that a linkage-specification sets a storage class, but
5062   // 'extern "C" struct foo;' is actually valid and not theoretically
5063   // useless.
5064   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5065     if (SCS == DeclSpec::SCS_mutable)
5066       // Since mutable is not a viable storage class specifier in C, there is
5067       // no reason to treat it as an extension. Instead, diagnose as an error.
5068       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5069     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5070       Diag(DS.getStorageClassSpecLoc(), DiagID)
5071         << DeclSpec::getSpecifierName(SCS);
5072   }
5073 
5074   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5075     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5076       << DeclSpec::getSpecifierName(TSCS);
5077   if (DS.getTypeQualifiers()) {
5078     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5079       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5080     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5081       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5082     // Restrict is covered above.
5083     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5084       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5085     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5086       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5087   }
5088 
5089   // Warn about ignored type attributes, for example:
5090   // __attribute__((aligned)) struct A;
5091   // Attributes should be placed after tag to apply to type declaration.
5092   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5093     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5094     if (TypeSpecType == DeclSpec::TST_class ||
5095         TypeSpecType == DeclSpec::TST_struct ||
5096         TypeSpecType == DeclSpec::TST_interface ||
5097         TypeSpecType == DeclSpec::TST_union ||
5098         TypeSpecType == DeclSpec::TST_enum) {
5099       for (const ParsedAttr &AL : DS.getAttributes())
5100         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5101             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5102       for (const ParsedAttr &AL : DeclAttrs)
5103         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5104             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5105     }
5106   }
5107 
5108   return TagD;
5109 }
5110 
5111 /// We are trying to inject an anonymous member into the given scope;
5112 /// check if there's an existing declaration that can't be overloaded.
5113 ///
5114 /// \return true if this is a forbidden redeclaration
5115 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5116                                          Scope *S,
5117                                          DeclContext *Owner,
5118                                          DeclarationName Name,
5119                                          SourceLocation NameLoc,
5120                                          bool IsUnion) {
5121   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5122                  Sema::ForVisibleRedeclaration);
5123   if (!SemaRef.LookupName(R, S)) return false;
5124 
5125   // Pick a representative declaration.
5126   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5127   assert(PrevDecl && "Expected a non-null Decl");
5128 
5129   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5130     return false;
5131 
5132   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5133     << IsUnion << Name;
5134   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5135 
5136   return true;
5137 }
5138 
5139 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5140 /// anonymous struct or union AnonRecord into the owning context Owner
5141 /// and scope S. This routine will be invoked just after we realize
5142 /// that an unnamed union or struct is actually an anonymous union or
5143 /// struct, e.g.,
5144 ///
5145 /// @code
5146 /// union {
5147 ///   int i;
5148 ///   float f;
5149 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5150 ///    // f into the surrounding scope.x
5151 /// @endcode
5152 ///
5153 /// This routine is recursive, injecting the names of nested anonymous
5154 /// structs/unions into the owning context and scope as well.
5155 static bool
5156 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5157                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5158                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5159   bool Invalid = false;
5160 
5161   // Look every FieldDecl and IndirectFieldDecl with a name.
5162   for (auto *D : AnonRecord->decls()) {
5163     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5164         cast<NamedDecl>(D)->getDeclName()) {
5165       ValueDecl *VD = cast<ValueDecl>(D);
5166       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5167                                        VD->getLocation(),
5168                                        AnonRecord->isUnion())) {
5169         // C++ [class.union]p2:
5170         //   The names of the members of an anonymous union shall be
5171         //   distinct from the names of any other entity in the
5172         //   scope in which the anonymous union is declared.
5173         Invalid = true;
5174       } else {
5175         // C++ [class.union]p2:
5176         //   For the purpose of name lookup, after the anonymous union
5177         //   definition, the members of the anonymous union are
5178         //   considered to have been defined in the scope in which the
5179         //   anonymous union is declared.
5180         unsigned OldChainingSize = Chaining.size();
5181         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5182           Chaining.append(IF->chain_begin(), IF->chain_end());
5183         else
5184           Chaining.push_back(VD);
5185 
5186         assert(Chaining.size() >= 2);
5187         NamedDecl **NamedChain =
5188           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5189         for (unsigned i = 0; i < Chaining.size(); i++)
5190           NamedChain[i] = Chaining[i];
5191 
5192         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5193             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5194             VD->getType(), {NamedChain, Chaining.size()});
5195 
5196         for (const auto *Attr : VD->attrs())
5197           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5198 
5199         IndirectField->setAccess(AS);
5200         IndirectField->setImplicit();
5201         SemaRef.PushOnScopeChains(IndirectField, S);
5202 
5203         // That includes picking up the appropriate access specifier.
5204         if (AS != AS_none) IndirectField->setAccess(AS);
5205 
5206         Chaining.resize(OldChainingSize);
5207       }
5208     }
5209   }
5210 
5211   return Invalid;
5212 }
5213 
5214 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5215 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5216 /// illegal input values are mapped to SC_None.
5217 static StorageClass
5218 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5219   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5220   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5221          "Parser allowed 'typedef' as storage class VarDecl.");
5222   switch (StorageClassSpec) {
5223   case DeclSpec::SCS_unspecified:    return SC_None;
5224   case DeclSpec::SCS_extern:
5225     if (DS.isExternInLinkageSpec())
5226       return SC_None;
5227     return SC_Extern;
5228   case DeclSpec::SCS_static:         return SC_Static;
5229   case DeclSpec::SCS_auto:           return SC_Auto;
5230   case DeclSpec::SCS_register:       return SC_Register;
5231   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5232     // Illegal SCSs map to None: error reporting is up to the caller.
5233   case DeclSpec::SCS_mutable:        // Fall through.
5234   case DeclSpec::SCS_typedef:        return SC_None;
5235   }
5236   llvm_unreachable("unknown storage class specifier");
5237 }
5238 
5239 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5240   assert(Record->hasInClassInitializer());
5241 
5242   for (const auto *I : Record->decls()) {
5243     const auto *FD = dyn_cast<FieldDecl>(I);
5244     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5245       FD = IFD->getAnonField();
5246     if (FD && FD->hasInClassInitializer())
5247       return FD->getLocation();
5248   }
5249 
5250   llvm_unreachable("couldn't find in-class initializer");
5251 }
5252 
5253 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5254                                       SourceLocation DefaultInitLoc) {
5255   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5256     return;
5257 
5258   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5259   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5260 }
5261 
5262 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5263                                       CXXRecordDecl *AnonUnion) {
5264   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5265     return;
5266 
5267   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5268 }
5269 
5270 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5271 /// anonymous structure or union. Anonymous unions are a C++ feature
5272 /// (C++ [class.union]) and a C11 feature; anonymous structures
5273 /// are a C11 feature and GNU C++ extension.
5274 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5275                                         AccessSpecifier AS,
5276                                         RecordDecl *Record,
5277                                         const PrintingPolicy &Policy) {
5278   DeclContext *Owner = Record->getDeclContext();
5279 
5280   // Diagnose whether this anonymous struct/union is an extension.
5281   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5282     Diag(Record->getLocation(), diag::ext_anonymous_union);
5283   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5284     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5285   else if (!Record->isUnion() && !getLangOpts().C11)
5286     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5287 
5288   // C and C++ require different kinds of checks for anonymous
5289   // structs/unions.
5290   bool Invalid = false;
5291   if (getLangOpts().CPlusPlus) {
5292     const char *PrevSpec = nullptr;
5293     if (Record->isUnion()) {
5294       // C++ [class.union]p6:
5295       // C++17 [class.union.anon]p2:
5296       //   Anonymous unions declared in a named namespace or in the
5297       //   global namespace shall be declared static.
5298       unsigned DiagID;
5299       DeclContext *OwnerScope = Owner->getRedeclContext();
5300       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5301           (OwnerScope->isTranslationUnit() ||
5302            (OwnerScope->isNamespace() &&
5303             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5304         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5305           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5306 
5307         // Recover by adding 'static'.
5308         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5309                                PrevSpec, DiagID, Policy);
5310       }
5311       // C++ [class.union]p6:
5312       //   A storage class is not allowed in a declaration of an
5313       //   anonymous union in a class scope.
5314       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5315                isa<RecordDecl>(Owner)) {
5316         Diag(DS.getStorageClassSpecLoc(),
5317              diag::err_anonymous_union_with_storage_spec)
5318           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5319 
5320         // Recover by removing the storage specifier.
5321         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5322                                SourceLocation(),
5323                                PrevSpec, DiagID, Context.getPrintingPolicy());
5324       }
5325     }
5326 
5327     // Ignore const/volatile/restrict qualifiers.
5328     if (DS.getTypeQualifiers()) {
5329       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5330         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5331           << Record->isUnion() << "const"
5332           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5333       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5334         Diag(DS.getVolatileSpecLoc(),
5335              diag::ext_anonymous_struct_union_qualified)
5336           << Record->isUnion() << "volatile"
5337           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5338       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5339         Diag(DS.getRestrictSpecLoc(),
5340              diag::ext_anonymous_struct_union_qualified)
5341           << Record->isUnion() << "restrict"
5342           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5343       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5344         Diag(DS.getAtomicSpecLoc(),
5345              diag::ext_anonymous_struct_union_qualified)
5346           << Record->isUnion() << "_Atomic"
5347           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5348       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5349         Diag(DS.getUnalignedSpecLoc(),
5350              diag::ext_anonymous_struct_union_qualified)
5351           << Record->isUnion() << "__unaligned"
5352           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5353 
5354       DS.ClearTypeQualifiers();
5355     }
5356 
5357     // C++ [class.union]p2:
5358     //   The member-specification of an anonymous union shall only
5359     //   define non-static data members. [Note: nested types and
5360     //   functions cannot be declared within an anonymous union. ]
5361     for (auto *Mem : Record->decls()) {
5362       // Ignore invalid declarations; we already diagnosed them.
5363       if (Mem->isInvalidDecl())
5364         continue;
5365 
5366       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5367         // C++ [class.union]p3:
5368         //   An anonymous union shall not have private or protected
5369         //   members (clause 11).
5370         assert(FD->getAccess() != AS_none);
5371         if (FD->getAccess() != AS_public) {
5372           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5373             << Record->isUnion() << (FD->getAccess() == AS_protected);
5374           Invalid = true;
5375         }
5376 
5377         // C++ [class.union]p1
5378         //   An object of a class with a non-trivial constructor, a non-trivial
5379         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5380         //   assignment operator cannot be a member of a union, nor can an
5381         //   array of such objects.
5382         if (CheckNontrivialField(FD))
5383           Invalid = true;
5384       } else if (Mem->isImplicit()) {
5385         // Any implicit members are fine.
5386       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5387         // This is a type that showed up in an
5388         // elaborated-type-specifier inside the anonymous struct or
5389         // union, but which actually declares a type outside of the
5390         // anonymous struct or union. It's okay.
5391       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5392         if (!MemRecord->isAnonymousStructOrUnion() &&
5393             MemRecord->getDeclName()) {
5394           // Visual C++ allows type definition in anonymous struct or union.
5395           if (getLangOpts().MicrosoftExt)
5396             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5397               << Record->isUnion();
5398           else {
5399             // This is a nested type declaration.
5400             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5401               << Record->isUnion();
5402             Invalid = true;
5403           }
5404         } else {
5405           // This is an anonymous type definition within another anonymous type.
5406           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5407           // not part of standard C++.
5408           Diag(MemRecord->getLocation(),
5409                diag::ext_anonymous_record_with_anonymous_type)
5410             << Record->isUnion();
5411         }
5412       } else if (isa<AccessSpecDecl>(Mem)) {
5413         // Any access specifier is fine.
5414       } else if (isa<StaticAssertDecl>(Mem)) {
5415         // In C++1z, static_assert declarations are also fine.
5416       } else {
5417         // We have something that isn't a non-static data
5418         // member. Complain about it.
5419         unsigned DK = diag::err_anonymous_record_bad_member;
5420         if (isa<TypeDecl>(Mem))
5421           DK = diag::err_anonymous_record_with_type;
5422         else if (isa<FunctionDecl>(Mem))
5423           DK = diag::err_anonymous_record_with_function;
5424         else if (isa<VarDecl>(Mem))
5425           DK = diag::err_anonymous_record_with_static;
5426 
5427         // Visual C++ allows type definition in anonymous struct or union.
5428         if (getLangOpts().MicrosoftExt &&
5429             DK == diag::err_anonymous_record_with_type)
5430           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5431             << Record->isUnion();
5432         else {
5433           Diag(Mem->getLocation(), DK) << Record->isUnion();
5434           Invalid = true;
5435         }
5436       }
5437     }
5438 
5439     // C++11 [class.union]p8 (DR1460):
5440     //   At most one variant member of a union may have a
5441     //   brace-or-equal-initializer.
5442     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5443         Owner->isRecord())
5444       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5445                                 cast<CXXRecordDecl>(Record));
5446   }
5447 
5448   if (!Record->isUnion() && !Owner->isRecord()) {
5449     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5450       << getLangOpts().CPlusPlus;
5451     Invalid = true;
5452   }
5453 
5454   // C++ [dcl.dcl]p3:
5455   //   [If there are no declarators], and except for the declaration of an
5456   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5457   //   names into the program
5458   // C++ [class.mem]p2:
5459   //   each such member-declaration shall either declare at least one member
5460   //   name of the class or declare at least one unnamed bit-field
5461   //
5462   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5463   if (getLangOpts().CPlusPlus && Record->field_empty())
5464     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5465 
5466   // Mock up a declarator.
5467   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5468   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5469   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5470 
5471   // Create a declaration for this anonymous struct/union.
5472   NamedDecl *Anon = nullptr;
5473   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5474     Anon = FieldDecl::Create(
5475         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5476         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5477         /*BitWidth=*/nullptr, /*Mutable=*/false,
5478         /*InitStyle=*/ICIS_NoInit);
5479     Anon->setAccess(AS);
5480     ProcessDeclAttributes(S, Anon, Dc);
5481 
5482     if (getLangOpts().CPlusPlus)
5483       FieldCollector->Add(cast<FieldDecl>(Anon));
5484   } else {
5485     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5486     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5487     if (SCSpec == DeclSpec::SCS_mutable) {
5488       // mutable can only appear on non-static class members, so it's always
5489       // an error here
5490       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5491       Invalid = true;
5492       SC = SC_None;
5493     }
5494 
5495     assert(DS.getAttributes().empty() && "No attribute expected");
5496     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5497                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5498                            Context.getTypeDeclType(Record), TInfo, SC);
5499 
5500     // Default-initialize the implicit variable. This initialization will be
5501     // trivial in almost all cases, except if a union member has an in-class
5502     // initializer:
5503     //   union { int n = 0; };
5504     ActOnUninitializedDecl(Anon);
5505   }
5506   Anon->setImplicit();
5507 
5508   // Mark this as an anonymous struct/union type.
5509   Record->setAnonymousStructOrUnion(true);
5510 
5511   // Add the anonymous struct/union object to the current
5512   // context. We'll be referencing this object when we refer to one of
5513   // its members.
5514   Owner->addDecl(Anon);
5515 
5516   // Inject the members of the anonymous struct/union into the owning
5517   // context and into the identifier resolver chain for name lookup
5518   // purposes.
5519   SmallVector<NamedDecl*, 2> Chain;
5520   Chain.push_back(Anon);
5521 
5522   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5523     Invalid = true;
5524 
5525   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5526     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5527       MangleNumberingContext *MCtx;
5528       Decl *ManglingContextDecl;
5529       std::tie(MCtx, ManglingContextDecl) =
5530           getCurrentMangleNumberContext(NewVD->getDeclContext());
5531       if (MCtx) {
5532         Context.setManglingNumber(
5533             NewVD, MCtx->getManglingNumber(
5534                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5535         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5536       }
5537     }
5538   }
5539 
5540   if (Invalid)
5541     Anon->setInvalidDecl();
5542 
5543   return Anon;
5544 }
5545 
5546 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5547 /// Microsoft C anonymous structure.
5548 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5549 /// Example:
5550 ///
5551 /// struct A { int a; };
5552 /// struct B { struct A; int b; };
5553 ///
5554 /// void foo() {
5555 ///   B var;
5556 ///   var.a = 3;
5557 /// }
5558 ///
5559 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5560                                            RecordDecl *Record) {
5561   assert(Record && "expected a record!");
5562 
5563   // Mock up a declarator.
5564   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5565   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5566   assert(TInfo && "couldn't build declarator info for anonymous struct");
5567 
5568   auto *ParentDecl = cast<RecordDecl>(CurContext);
5569   QualType RecTy = Context.getTypeDeclType(Record);
5570 
5571   // Create a declaration for this anonymous struct.
5572   NamedDecl *Anon =
5573       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5574                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5575                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5576                         /*InitStyle=*/ICIS_NoInit);
5577   Anon->setImplicit();
5578 
5579   // Add the anonymous struct object to the current context.
5580   CurContext->addDecl(Anon);
5581 
5582   // Inject the members of the anonymous struct into the current
5583   // context and into the identifier resolver chain for name lookup
5584   // purposes.
5585   SmallVector<NamedDecl*, 2> Chain;
5586   Chain.push_back(Anon);
5587 
5588   RecordDecl *RecordDef = Record->getDefinition();
5589   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5590                                diag::err_field_incomplete_or_sizeless) ||
5591       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5592                                           AS_none, Chain)) {
5593     Anon->setInvalidDecl();
5594     ParentDecl->setInvalidDecl();
5595   }
5596 
5597   return Anon;
5598 }
5599 
5600 /// GetNameForDeclarator - Determine the full declaration name for the
5601 /// given Declarator.
5602 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5603   return GetNameFromUnqualifiedId(D.getName());
5604 }
5605 
5606 /// Retrieves the declaration name from a parsed unqualified-id.
5607 DeclarationNameInfo
5608 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5609   DeclarationNameInfo NameInfo;
5610   NameInfo.setLoc(Name.StartLocation);
5611 
5612   switch (Name.getKind()) {
5613 
5614   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5615   case UnqualifiedIdKind::IK_Identifier:
5616     NameInfo.setName(Name.Identifier);
5617     return NameInfo;
5618 
5619   case UnqualifiedIdKind::IK_DeductionGuideName: {
5620     // C++ [temp.deduct.guide]p3:
5621     //   The simple-template-id shall name a class template specialization.
5622     //   The template-name shall be the same identifier as the template-name
5623     //   of the simple-template-id.
5624     // These together intend to imply that the template-name shall name a
5625     // class template.
5626     // FIXME: template<typename T> struct X {};
5627     //        template<typename T> using Y = X<T>;
5628     //        Y(int) -> Y<int>;
5629     //   satisfies these rules but does not name a class template.
5630     TemplateName TN = Name.TemplateName.get().get();
5631     auto *Template = TN.getAsTemplateDecl();
5632     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5633       Diag(Name.StartLocation,
5634            diag::err_deduction_guide_name_not_class_template)
5635         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5636       if (Template)
5637         Diag(Template->getLocation(), diag::note_template_decl_here);
5638       return DeclarationNameInfo();
5639     }
5640 
5641     NameInfo.setName(
5642         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5643     return NameInfo;
5644   }
5645 
5646   case UnqualifiedIdKind::IK_OperatorFunctionId:
5647     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5648                                            Name.OperatorFunctionId.Operator));
5649     NameInfo.setCXXOperatorNameRange(SourceRange(
5650         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5651     return NameInfo;
5652 
5653   case UnqualifiedIdKind::IK_LiteralOperatorId:
5654     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5655                                                            Name.Identifier));
5656     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5657     return NameInfo;
5658 
5659   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5660     TypeSourceInfo *TInfo;
5661     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5662     if (Ty.isNull())
5663       return DeclarationNameInfo();
5664     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5665                                                Context.getCanonicalType(Ty)));
5666     NameInfo.setNamedTypeInfo(TInfo);
5667     return NameInfo;
5668   }
5669 
5670   case UnqualifiedIdKind::IK_ConstructorName: {
5671     TypeSourceInfo *TInfo;
5672     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5673     if (Ty.isNull())
5674       return DeclarationNameInfo();
5675     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5676                                               Context.getCanonicalType(Ty)));
5677     NameInfo.setNamedTypeInfo(TInfo);
5678     return NameInfo;
5679   }
5680 
5681   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5682     // In well-formed code, we can only have a constructor
5683     // template-id that refers to the current context, so go there
5684     // to find the actual type being constructed.
5685     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5686     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5687       return DeclarationNameInfo();
5688 
5689     // Determine the type of the class being constructed.
5690     QualType CurClassType = Context.getTypeDeclType(CurClass);
5691 
5692     // FIXME: Check two things: that the template-id names the same type as
5693     // CurClassType, and that the template-id does not occur when the name
5694     // was qualified.
5695 
5696     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5697                                     Context.getCanonicalType(CurClassType)));
5698     // FIXME: should we retrieve TypeSourceInfo?
5699     NameInfo.setNamedTypeInfo(nullptr);
5700     return NameInfo;
5701   }
5702 
5703   case UnqualifiedIdKind::IK_DestructorName: {
5704     TypeSourceInfo *TInfo;
5705     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5706     if (Ty.isNull())
5707       return DeclarationNameInfo();
5708     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5709                                               Context.getCanonicalType(Ty)));
5710     NameInfo.setNamedTypeInfo(TInfo);
5711     return NameInfo;
5712   }
5713 
5714   case UnqualifiedIdKind::IK_TemplateId: {
5715     TemplateName TName = Name.TemplateId->Template.get();
5716     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5717     return Context.getNameForTemplate(TName, TNameLoc);
5718   }
5719 
5720   } // switch (Name.getKind())
5721 
5722   llvm_unreachable("Unknown name kind");
5723 }
5724 
5725 static QualType getCoreType(QualType Ty) {
5726   do {
5727     if (Ty->isPointerType() || Ty->isReferenceType())
5728       Ty = Ty->getPointeeType();
5729     else if (Ty->isArrayType())
5730       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5731     else
5732       return Ty.withoutLocalFastQualifiers();
5733   } while (true);
5734 }
5735 
5736 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5737 /// and Definition have "nearly" matching parameters. This heuristic is
5738 /// used to improve diagnostics in the case where an out-of-line function
5739 /// definition doesn't match any declaration within the class or namespace.
5740 /// Also sets Params to the list of indices to the parameters that differ
5741 /// between the declaration and the definition. If hasSimilarParameters
5742 /// returns true and Params is empty, then all of the parameters match.
5743 static bool hasSimilarParameters(ASTContext &Context,
5744                                      FunctionDecl *Declaration,
5745                                      FunctionDecl *Definition,
5746                                      SmallVectorImpl<unsigned> &Params) {
5747   Params.clear();
5748   if (Declaration->param_size() != Definition->param_size())
5749     return false;
5750   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5751     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5752     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5753 
5754     // The parameter types are identical
5755     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5756       continue;
5757 
5758     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5759     QualType DefParamBaseTy = getCoreType(DefParamTy);
5760     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5761     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5762 
5763     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5764         (DeclTyName && DeclTyName == DefTyName))
5765       Params.push_back(Idx);
5766     else  // The two parameters aren't even close
5767       return false;
5768   }
5769 
5770   return true;
5771 }
5772 
5773 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5774 /// declarator needs to be rebuilt in the current instantiation.
5775 /// Any bits of declarator which appear before the name are valid for
5776 /// consideration here.  That's specifically the type in the decl spec
5777 /// and the base type in any member-pointer chunks.
5778 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5779                                                     DeclarationName Name) {
5780   // The types we specifically need to rebuild are:
5781   //   - typenames, typeofs, and decltypes
5782   //   - types which will become injected class names
5783   // Of course, we also need to rebuild any type referencing such a
5784   // type.  It's safest to just say "dependent", but we call out a
5785   // few cases here.
5786 
5787   DeclSpec &DS = D.getMutableDeclSpec();
5788   switch (DS.getTypeSpecType()) {
5789   case DeclSpec::TST_typename:
5790   case DeclSpec::TST_typeofType:
5791   case DeclSpec::TST_underlyingType:
5792   case DeclSpec::TST_atomic: {
5793     // Grab the type from the parser.
5794     TypeSourceInfo *TSI = nullptr;
5795     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5796     if (T.isNull() || !T->isInstantiationDependentType()) break;
5797 
5798     // Make sure there's a type source info.  This isn't really much
5799     // of a waste; most dependent types should have type source info
5800     // attached already.
5801     if (!TSI)
5802       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5803 
5804     // Rebuild the type in the current instantiation.
5805     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5806     if (!TSI) return true;
5807 
5808     // Store the new type back in the decl spec.
5809     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5810     DS.UpdateTypeRep(LocType);
5811     break;
5812   }
5813 
5814   case DeclSpec::TST_decltype:
5815   case DeclSpec::TST_typeofExpr: {
5816     Expr *E = DS.getRepAsExpr();
5817     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5818     if (Result.isInvalid()) return true;
5819     DS.UpdateExprRep(Result.get());
5820     break;
5821   }
5822 
5823   default:
5824     // Nothing to do for these decl specs.
5825     break;
5826   }
5827 
5828   // It doesn't matter what order we do this in.
5829   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5830     DeclaratorChunk &Chunk = D.getTypeObject(I);
5831 
5832     // The only type information in the declarator which can come
5833     // before the declaration name is the base type of a member
5834     // pointer.
5835     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5836       continue;
5837 
5838     // Rebuild the scope specifier in-place.
5839     CXXScopeSpec &SS = Chunk.Mem.Scope();
5840     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5841       return true;
5842   }
5843 
5844   return false;
5845 }
5846 
5847 /// Returns true if the declaration is declared in a system header or from a
5848 /// system macro.
5849 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5850   return SM.isInSystemHeader(D->getLocation()) ||
5851          SM.isInSystemMacro(D->getLocation());
5852 }
5853 
5854 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5855   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5856   // of system decl.
5857   if (D->getPreviousDecl() || D->isImplicit())
5858     return;
5859   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5860   if (Status != ReservedIdentifierStatus::NotReserved &&
5861       !isFromSystemHeader(Context.getSourceManager(), D)) {
5862     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5863         << D << static_cast<int>(Status);
5864   }
5865 }
5866 
5867 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5868   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5869 
5870   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5871   // declaration only if the `bind_to_declaration` extension is set.
5872   SmallVector<FunctionDecl *, 4> Bases;
5873   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
5874     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
5875               implementation_extension_bind_to_declaration))
5876     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
5877         S, D, MultiTemplateParamsArg(), Bases);
5878 
5879   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5880 
5881   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5882       Dcl && Dcl->getDeclContext()->isFileContext())
5883     Dcl->setTopLevelDeclInObjCContainer();
5884 
5885   if (!Bases.empty())
5886     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
5887 
5888   return Dcl;
5889 }
5890 
5891 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5892 ///   If T is the name of a class, then each of the following shall have a
5893 ///   name different from T:
5894 ///     - every static data member of class T;
5895 ///     - every member function of class T
5896 ///     - every member of class T that is itself a type;
5897 /// \returns true if the declaration name violates these rules.
5898 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5899                                    DeclarationNameInfo NameInfo) {
5900   DeclarationName Name = NameInfo.getName();
5901 
5902   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5903   while (Record && Record->isAnonymousStructOrUnion())
5904     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5905   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5906     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5907     return true;
5908   }
5909 
5910   return false;
5911 }
5912 
5913 /// Diagnose a declaration whose declarator-id has the given
5914 /// nested-name-specifier.
5915 ///
5916 /// \param SS The nested-name-specifier of the declarator-id.
5917 ///
5918 /// \param DC The declaration context to which the nested-name-specifier
5919 /// resolves.
5920 ///
5921 /// \param Name The name of the entity being declared.
5922 ///
5923 /// \param Loc The location of the name of the entity being declared.
5924 ///
5925 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5926 /// we're declaring an explicit / partial specialization / instantiation.
5927 ///
5928 /// \returns true if we cannot safely recover from this error, false otherwise.
5929 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5930                                         DeclarationName Name,
5931                                         SourceLocation Loc, bool IsTemplateId) {
5932   DeclContext *Cur = CurContext;
5933   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5934     Cur = Cur->getParent();
5935 
5936   // If the user provided a superfluous scope specifier that refers back to the
5937   // class in which the entity is already declared, diagnose and ignore it.
5938   //
5939   // class X {
5940   //   void X::f();
5941   // };
5942   //
5943   // Note, it was once ill-formed to give redundant qualification in all
5944   // contexts, but that rule was removed by DR482.
5945   if (Cur->Equals(DC)) {
5946     if (Cur->isRecord()) {
5947       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5948                                       : diag::err_member_extra_qualification)
5949         << Name << FixItHint::CreateRemoval(SS.getRange());
5950       SS.clear();
5951     } else {
5952       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5953     }
5954     return false;
5955   }
5956 
5957   // Check whether the qualifying scope encloses the scope of the original
5958   // declaration. For a template-id, we perform the checks in
5959   // CheckTemplateSpecializationScope.
5960   if (!Cur->Encloses(DC) && !IsTemplateId) {
5961     if (Cur->isRecord())
5962       Diag(Loc, diag::err_member_qualification)
5963         << Name << SS.getRange();
5964     else if (isa<TranslationUnitDecl>(DC))
5965       Diag(Loc, diag::err_invalid_declarator_global_scope)
5966         << Name << SS.getRange();
5967     else if (isa<FunctionDecl>(Cur))
5968       Diag(Loc, diag::err_invalid_declarator_in_function)
5969         << Name << SS.getRange();
5970     else if (isa<BlockDecl>(Cur))
5971       Diag(Loc, diag::err_invalid_declarator_in_block)
5972         << Name << SS.getRange();
5973     else if (isa<ExportDecl>(Cur)) {
5974       if (!isa<NamespaceDecl>(DC))
5975         Diag(Loc, diag::err_export_non_namespace_scope_name)
5976             << Name << SS.getRange();
5977       else
5978         // The cases that DC is not NamespaceDecl should be handled in
5979         // CheckRedeclarationExported.
5980         return false;
5981     } else
5982       Diag(Loc, diag::err_invalid_declarator_scope)
5983       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5984 
5985     return true;
5986   }
5987 
5988   if (Cur->isRecord()) {
5989     // Cannot qualify members within a class.
5990     Diag(Loc, diag::err_member_qualification)
5991       << Name << SS.getRange();
5992     SS.clear();
5993 
5994     // C++ constructors and destructors with incorrect scopes can break
5995     // our AST invariants by having the wrong underlying types. If
5996     // that's the case, then drop this declaration entirely.
5997     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5998          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5999         !Context.hasSameType(Name.getCXXNameType(),
6000                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6001       return true;
6002 
6003     return false;
6004   }
6005 
6006   // C++11 [dcl.meaning]p1:
6007   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6008   //   not begin with a decltype-specifer"
6009   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6010   while (SpecLoc.getPrefix())
6011     SpecLoc = SpecLoc.getPrefix();
6012   if (isa_and_nonnull<DecltypeType>(
6013           SpecLoc.getNestedNameSpecifier()->getAsType()))
6014     Diag(Loc, diag::err_decltype_in_declarator)
6015       << SpecLoc.getTypeLoc().getSourceRange();
6016 
6017   return false;
6018 }
6019 
6020 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6021                                   MultiTemplateParamsArg TemplateParamLists) {
6022   // TODO: consider using NameInfo for diagnostic.
6023   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6024   DeclarationName Name = NameInfo.getName();
6025 
6026   // All of these full declarators require an identifier.  If it doesn't have
6027   // one, the ParsedFreeStandingDeclSpec action should be used.
6028   if (D.isDecompositionDeclarator()) {
6029     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6030   } else if (!Name) {
6031     if (!D.isInvalidType())  // Reject this if we think it is valid.
6032       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6033           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6034     return nullptr;
6035   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6036     return nullptr;
6037 
6038   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6039   // we find one that is.
6040   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6041          (S->getFlags() & Scope::TemplateParamScope) != 0)
6042     S = S->getParent();
6043 
6044   DeclContext *DC = CurContext;
6045   if (D.getCXXScopeSpec().isInvalid())
6046     D.setInvalidType();
6047   else if (D.getCXXScopeSpec().isSet()) {
6048     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6049                                         UPPC_DeclarationQualifier))
6050       return nullptr;
6051 
6052     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6053     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6054     if (!DC || isa<EnumDecl>(DC)) {
6055       // If we could not compute the declaration context, it's because the
6056       // declaration context is dependent but does not refer to a class,
6057       // class template, or class template partial specialization. Complain
6058       // and return early, to avoid the coming semantic disaster.
6059       Diag(D.getIdentifierLoc(),
6060            diag::err_template_qualified_declarator_no_match)
6061         << D.getCXXScopeSpec().getScopeRep()
6062         << D.getCXXScopeSpec().getRange();
6063       return nullptr;
6064     }
6065     bool IsDependentContext = DC->isDependentContext();
6066 
6067     if (!IsDependentContext &&
6068         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6069       return nullptr;
6070 
6071     // If a class is incomplete, do not parse entities inside it.
6072     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6073       Diag(D.getIdentifierLoc(),
6074            diag::err_member_def_undefined_record)
6075         << Name << DC << D.getCXXScopeSpec().getRange();
6076       return nullptr;
6077     }
6078     if (!D.getDeclSpec().isFriendSpecified()) {
6079       if (diagnoseQualifiedDeclaration(
6080               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6081               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6082         if (DC->isRecord())
6083           return nullptr;
6084 
6085         D.setInvalidType();
6086       }
6087     }
6088 
6089     // Check whether we need to rebuild the type of the given
6090     // declaration in the current instantiation.
6091     if (EnteringContext && IsDependentContext &&
6092         TemplateParamLists.size() != 0) {
6093       ContextRAII SavedContext(*this, DC);
6094       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6095         D.setInvalidType();
6096     }
6097   }
6098 
6099   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6100   QualType R = TInfo->getType();
6101 
6102   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6103                                       UPPC_DeclarationType))
6104     D.setInvalidType();
6105 
6106   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6107                         forRedeclarationInCurContext());
6108 
6109   // See if this is a redefinition of a variable in the same scope.
6110   if (!D.getCXXScopeSpec().isSet()) {
6111     bool IsLinkageLookup = false;
6112     bool CreateBuiltins = false;
6113 
6114     // If the declaration we're planning to build will be a function
6115     // or object with linkage, then look for another declaration with
6116     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6117     //
6118     // If the declaration we're planning to build will be declared with
6119     // external linkage in the translation unit, create any builtin with
6120     // the same name.
6121     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6122       /* Do nothing*/;
6123     else if (CurContext->isFunctionOrMethod() &&
6124              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6125               R->isFunctionType())) {
6126       IsLinkageLookup = true;
6127       CreateBuiltins =
6128           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6129     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6130                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6131       CreateBuiltins = true;
6132 
6133     if (IsLinkageLookup) {
6134       Previous.clear(LookupRedeclarationWithLinkage);
6135       Previous.setRedeclarationKind(ForExternalRedeclaration);
6136     }
6137 
6138     LookupName(Previous, S, CreateBuiltins);
6139   } else { // Something like "int foo::x;"
6140     LookupQualifiedName(Previous, DC);
6141 
6142     // C++ [dcl.meaning]p1:
6143     //   When the declarator-id is qualified, the declaration shall refer to a
6144     //  previously declared member of the class or namespace to which the
6145     //  qualifier refers (or, in the case of a namespace, of an element of the
6146     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6147     //  thereof; [...]
6148     //
6149     // Note that we already checked the context above, and that we do not have
6150     // enough information to make sure that Previous contains the declaration
6151     // we want to match. For example, given:
6152     //
6153     //   class X {
6154     //     void f();
6155     //     void f(float);
6156     //   };
6157     //
6158     //   void X::f(int) { } // ill-formed
6159     //
6160     // In this case, Previous will point to the overload set
6161     // containing the two f's declared in X, but neither of them
6162     // matches.
6163 
6164     // C++ [dcl.meaning]p1:
6165     //   [...] the member shall not merely have been introduced by a
6166     //   using-declaration in the scope of the class or namespace nominated by
6167     //   the nested-name-specifier of the declarator-id.
6168     RemoveUsingDecls(Previous);
6169   }
6170 
6171   if (Previous.isSingleResult() &&
6172       Previous.getFoundDecl()->isTemplateParameter()) {
6173     // Maybe we will complain about the shadowed template parameter.
6174     if (!D.isInvalidType())
6175       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6176                                       Previous.getFoundDecl());
6177 
6178     // Just pretend that we didn't see the previous declaration.
6179     Previous.clear();
6180   }
6181 
6182   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6183     // Forget that the previous declaration is the injected-class-name.
6184     Previous.clear();
6185 
6186   // In C++, the previous declaration we find might be a tag type
6187   // (class or enum). In this case, the new declaration will hide the
6188   // tag type. Note that this applies to functions, function templates, and
6189   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6190   if (Previous.isSingleTagDecl() &&
6191       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6192       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6193     Previous.clear();
6194 
6195   // Check that there are no default arguments other than in the parameters
6196   // of a function declaration (C++ only).
6197   if (getLangOpts().CPlusPlus)
6198     CheckExtraCXXDefaultArguments(D);
6199 
6200   NamedDecl *New;
6201 
6202   bool AddToScope = true;
6203   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6204     if (TemplateParamLists.size()) {
6205       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6206       return nullptr;
6207     }
6208 
6209     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6210   } else if (R->isFunctionType()) {
6211     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6212                                   TemplateParamLists,
6213                                   AddToScope);
6214   } else {
6215     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6216                                   AddToScope);
6217   }
6218 
6219   if (!New)
6220     return nullptr;
6221 
6222   // If this has an identifier and is not a function template specialization,
6223   // add it to the scope stack.
6224   if (New->getDeclName() && AddToScope)
6225     PushOnScopeChains(New, S);
6226 
6227   if (isInOpenMPDeclareTargetContext())
6228     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6229 
6230   return New;
6231 }
6232 
6233 /// Helper method to turn variable array types into constant array
6234 /// types in certain situations which would otherwise be errors (for
6235 /// GCC compatibility).
6236 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6237                                                     ASTContext &Context,
6238                                                     bool &SizeIsNegative,
6239                                                     llvm::APSInt &Oversized) {
6240   // This method tries to turn a variable array into a constant
6241   // array even when the size isn't an ICE.  This is necessary
6242   // for compatibility with code that depends on gcc's buggy
6243   // constant expression folding, like struct {char x[(int)(char*)2];}
6244   SizeIsNegative = false;
6245   Oversized = 0;
6246 
6247   if (T->isDependentType())
6248     return QualType();
6249 
6250   QualifierCollector Qs;
6251   const Type *Ty = Qs.strip(T);
6252 
6253   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6254     QualType Pointee = PTy->getPointeeType();
6255     QualType FixedType =
6256         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6257                                             Oversized);
6258     if (FixedType.isNull()) return FixedType;
6259     FixedType = Context.getPointerType(FixedType);
6260     return Qs.apply(Context, FixedType);
6261   }
6262   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6263     QualType Inner = PTy->getInnerType();
6264     QualType FixedType =
6265         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6266                                             Oversized);
6267     if (FixedType.isNull()) return FixedType;
6268     FixedType = Context.getParenType(FixedType);
6269     return Qs.apply(Context, FixedType);
6270   }
6271 
6272   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6273   if (!VLATy)
6274     return QualType();
6275 
6276   QualType ElemTy = VLATy->getElementType();
6277   if (ElemTy->isVariablyModifiedType()) {
6278     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6279                                                  SizeIsNegative, Oversized);
6280     if (ElemTy.isNull())
6281       return QualType();
6282   }
6283 
6284   Expr::EvalResult Result;
6285   if (!VLATy->getSizeExpr() ||
6286       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6287     return QualType();
6288 
6289   llvm::APSInt Res = Result.Val.getInt();
6290 
6291   // Check whether the array size is negative.
6292   if (Res.isSigned() && Res.isNegative()) {
6293     SizeIsNegative = true;
6294     return QualType();
6295   }
6296 
6297   // Check whether the array is too large to be addressed.
6298   unsigned ActiveSizeBits =
6299       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6300        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6301           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6302           : Res.getActiveBits();
6303   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6304     Oversized = Res;
6305     return QualType();
6306   }
6307 
6308   QualType FoldedArrayType = Context.getConstantArrayType(
6309       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6310   return Qs.apply(Context, FoldedArrayType);
6311 }
6312 
6313 static void
6314 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6315   SrcTL = SrcTL.getUnqualifiedLoc();
6316   DstTL = DstTL.getUnqualifiedLoc();
6317   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6318     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6319     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6320                                       DstPTL.getPointeeLoc());
6321     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6322     return;
6323   }
6324   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6325     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6326     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6327                                       DstPTL.getInnerLoc());
6328     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6329     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6330     return;
6331   }
6332   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6333   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6334   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6335   TypeLoc DstElemTL = DstATL.getElementLoc();
6336   if (VariableArrayTypeLoc SrcElemATL =
6337           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6338     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6339     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6340   } else {
6341     DstElemTL.initializeFullCopy(SrcElemTL);
6342   }
6343   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6344   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6345   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6346 }
6347 
6348 /// Helper method to turn variable array types into constant array
6349 /// types in certain situations which would otherwise be errors (for
6350 /// GCC compatibility).
6351 static TypeSourceInfo*
6352 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6353                                               ASTContext &Context,
6354                                               bool &SizeIsNegative,
6355                                               llvm::APSInt &Oversized) {
6356   QualType FixedTy
6357     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6358                                           SizeIsNegative, Oversized);
6359   if (FixedTy.isNull())
6360     return nullptr;
6361   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6362   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6363                                     FixedTInfo->getTypeLoc());
6364   return FixedTInfo;
6365 }
6366 
6367 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6368 /// true if we were successful.
6369 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6370                                            QualType &T, SourceLocation Loc,
6371                                            unsigned FailedFoldDiagID) {
6372   bool SizeIsNegative;
6373   llvm::APSInt Oversized;
6374   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6375       TInfo, Context, SizeIsNegative, Oversized);
6376   if (FixedTInfo) {
6377     Diag(Loc, diag::ext_vla_folded_to_constant);
6378     TInfo = FixedTInfo;
6379     T = FixedTInfo->getType();
6380     return true;
6381   }
6382 
6383   if (SizeIsNegative)
6384     Diag(Loc, diag::err_typecheck_negative_array_size);
6385   else if (Oversized.getBoolValue())
6386     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6387   else if (FailedFoldDiagID)
6388     Diag(Loc, FailedFoldDiagID);
6389   return false;
6390 }
6391 
6392 /// Register the given locally-scoped extern "C" declaration so
6393 /// that it can be found later for redeclarations. We include any extern "C"
6394 /// declaration that is not visible in the translation unit here, not just
6395 /// function-scope declarations.
6396 void
6397 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6398   if (!getLangOpts().CPlusPlus &&
6399       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6400     // Don't need to track declarations in the TU in C.
6401     return;
6402 
6403   // Note that we have a locally-scoped external with this name.
6404   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6405 }
6406 
6407 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6408   // FIXME: We can have multiple results via __attribute__((overloadable)).
6409   auto Result = Context.getExternCContextDecl()->lookup(Name);
6410   return Result.empty() ? nullptr : *Result.begin();
6411 }
6412 
6413 /// Diagnose function specifiers on a declaration of an identifier that
6414 /// does not identify a function.
6415 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6416   // FIXME: We should probably indicate the identifier in question to avoid
6417   // confusion for constructs like "virtual int a(), b;"
6418   if (DS.isVirtualSpecified())
6419     Diag(DS.getVirtualSpecLoc(),
6420          diag::err_virtual_non_function);
6421 
6422   if (DS.hasExplicitSpecifier())
6423     Diag(DS.getExplicitSpecLoc(),
6424          diag::err_explicit_non_function);
6425 
6426   if (DS.isNoreturnSpecified())
6427     Diag(DS.getNoreturnSpecLoc(),
6428          diag::err_noreturn_non_function);
6429 }
6430 
6431 NamedDecl*
6432 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6433                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6434   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6435   if (D.getCXXScopeSpec().isSet()) {
6436     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6437       << D.getCXXScopeSpec().getRange();
6438     D.setInvalidType();
6439     // Pretend we didn't see the scope specifier.
6440     DC = CurContext;
6441     Previous.clear();
6442   }
6443 
6444   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6445 
6446   if (D.getDeclSpec().isInlineSpecified())
6447     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6448         << getLangOpts().CPlusPlus17;
6449   if (D.getDeclSpec().hasConstexprSpecifier())
6450     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6451         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6452 
6453   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6454     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6455       Diag(D.getName().StartLocation,
6456            diag::err_deduction_guide_invalid_specifier)
6457           << "typedef";
6458     else
6459       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6460           << D.getName().getSourceRange();
6461     return nullptr;
6462   }
6463 
6464   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6465   if (!NewTD) return nullptr;
6466 
6467   // Handle attributes prior to checking for duplicates in MergeVarDecl
6468   ProcessDeclAttributes(S, NewTD, D);
6469 
6470   CheckTypedefForVariablyModifiedType(S, NewTD);
6471 
6472   bool Redeclaration = D.isRedeclaration();
6473   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6474   D.setRedeclaration(Redeclaration);
6475   return ND;
6476 }
6477 
6478 void
6479 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6480   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6481   // then it shall have block scope.
6482   // Note that variably modified types must be fixed before merging the decl so
6483   // that redeclarations will match.
6484   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6485   QualType T = TInfo->getType();
6486   if (T->isVariablyModifiedType()) {
6487     setFunctionHasBranchProtectedScope();
6488 
6489     if (S->getFnParent() == nullptr) {
6490       bool SizeIsNegative;
6491       llvm::APSInt Oversized;
6492       TypeSourceInfo *FixedTInfo =
6493         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6494                                                       SizeIsNegative,
6495                                                       Oversized);
6496       if (FixedTInfo) {
6497         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6498         NewTD->setTypeSourceInfo(FixedTInfo);
6499       } else {
6500         if (SizeIsNegative)
6501           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6502         else if (T->isVariableArrayType())
6503           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6504         else if (Oversized.getBoolValue())
6505           Diag(NewTD->getLocation(), diag::err_array_too_large)
6506             << toString(Oversized, 10);
6507         else
6508           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6509         NewTD->setInvalidDecl();
6510       }
6511     }
6512   }
6513 }
6514 
6515 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6516 /// declares a typedef-name, either using the 'typedef' type specifier or via
6517 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6518 NamedDecl*
6519 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6520                            LookupResult &Previous, bool &Redeclaration) {
6521 
6522   // Find the shadowed declaration before filtering for scope.
6523   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6524 
6525   // Merge the decl with the existing one if appropriate. If the decl is
6526   // in an outer scope, it isn't the same thing.
6527   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6528                        /*AllowInlineNamespace*/false);
6529   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6530   if (!Previous.empty()) {
6531     Redeclaration = true;
6532     MergeTypedefNameDecl(S, NewTD, Previous);
6533   } else {
6534     inferGslPointerAttribute(NewTD);
6535   }
6536 
6537   if (ShadowedDecl && !Redeclaration)
6538     CheckShadow(NewTD, ShadowedDecl, Previous);
6539 
6540   // If this is the C FILE type, notify the AST context.
6541   if (IdentifierInfo *II = NewTD->getIdentifier())
6542     if (!NewTD->isInvalidDecl() &&
6543         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6544       if (II->isStr("FILE"))
6545         Context.setFILEDecl(NewTD);
6546       else if (II->isStr("jmp_buf"))
6547         Context.setjmp_bufDecl(NewTD);
6548       else if (II->isStr("sigjmp_buf"))
6549         Context.setsigjmp_bufDecl(NewTD);
6550       else if (II->isStr("ucontext_t"))
6551         Context.setucontext_tDecl(NewTD);
6552     }
6553 
6554   return NewTD;
6555 }
6556 
6557 /// Determines whether the given declaration is an out-of-scope
6558 /// previous declaration.
6559 ///
6560 /// This routine should be invoked when name lookup has found a
6561 /// previous declaration (PrevDecl) that is not in the scope where a
6562 /// new declaration by the same name is being introduced. If the new
6563 /// declaration occurs in a local scope, previous declarations with
6564 /// linkage may still be considered previous declarations (C99
6565 /// 6.2.2p4-5, C++ [basic.link]p6).
6566 ///
6567 /// \param PrevDecl the previous declaration found by name
6568 /// lookup
6569 ///
6570 /// \param DC the context in which the new declaration is being
6571 /// declared.
6572 ///
6573 /// \returns true if PrevDecl is an out-of-scope previous declaration
6574 /// for a new delcaration with the same name.
6575 static bool
6576 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6577                                 ASTContext &Context) {
6578   if (!PrevDecl)
6579     return false;
6580 
6581   if (!PrevDecl->hasLinkage())
6582     return false;
6583 
6584   if (Context.getLangOpts().CPlusPlus) {
6585     // C++ [basic.link]p6:
6586     //   If there is a visible declaration of an entity with linkage
6587     //   having the same name and type, ignoring entities declared
6588     //   outside the innermost enclosing namespace scope, the block
6589     //   scope declaration declares that same entity and receives the
6590     //   linkage of the previous declaration.
6591     DeclContext *OuterContext = DC->getRedeclContext();
6592     if (!OuterContext->isFunctionOrMethod())
6593       // This rule only applies to block-scope declarations.
6594       return false;
6595 
6596     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6597     if (PrevOuterContext->isRecord())
6598       // We found a member function: ignore it.
6599       return false;
6600 
6601     // Find the innermost enclosing namespace for the new and
6602     // previous declarations.
6603     OuterContext = OuterContext->getEnclosingNamespaceContext();
6604     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6605 
6606     // The previous declaration is in a different namespace, so it
6607     // isn't the same function.
6608     if (!OuterContext->Equals(PrevOuterContext))
6609       return false;
6610   }
6611 
6612   return true;
6613 }
6614 
6615 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6616   CXXScopeSpec &SS = D.getCXXScopeSpec();
6617   if (!SS.isSet()) return;
6618   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6619 }
6620 
6621 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6622   QualType type = decl->getType();
6623   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6624   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6625     // Various kinds of declaration aren't allowed to be __autoreleasing.
6626     unsigned kind = -1U;
6627     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6628       if (var->hasAttr<BlocksAttr>())
6629         kind = 0; // __block
6630       else if (!var->hasLocalStorage())
6631         kind = 1; // global
6632     } else if (isa<ObjCIvarDecl>(decl)) {
6633       kind = 3; // ivar
6634     } else if (isa<FieldDecl>(decl)) {
6635       kind = 2; // field
6636     }
6637 
6638     if (kind != -1U) {
6639       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6640         << kind;
6641     }
6642   } else if (lifetime == Qualifiers::OCL_None) {
6643     // Try to infer lifetime.
6644     if (!type->isObjCLifetimeType())
6645       return false;
6646 
6647     lifetime = type->getObjCARCImplicitLifetime();
6648     type = Context.getLifetimeQualifiedType(type, lifetime);
6649     decl->setType(type);
6650   }
6651 
6652   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6653     // Thread-local variables cannot have lifetime.
6654     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6655         var->getTLSKind()) {
6656       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6657         << var->getType();
6658       return true;
6659     }
6660   }
6661 
6662   return false;
6663 }
6664 
6665 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6666   if (Decl->getType().hasAddressSpace())
6667     return;
6668   if (Decl->getType()->isDependentType())
6669     return;
6670   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6671     QualType Type = Var->getType();
6672     if (Type->isSamplerT() || Type->isVoidType())
6673       return;
6674     LangAS ImplAS = LangAS::opencl_private;
6675     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6676     // __opencl_c_program_scope_global_variables feature, the address space
6677     // for a variable at program scope or a static or extern variable inside
6678     // a function are inferred to be __global.
6679     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6680         Var->hasGlobalStorage())
6681       ImplAS = LangAS::opencl_global;
6682     // If the original type from a decayed type is an array type and that array
6683     // type has no address space yet, deduce it now.
6684     if (auto DT = dyn_cast<DecayedType>(Type)) {
6685       auto OrigTy = DT->getOriginalType();
6686       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6687         // Add the address space to the original array type and then propagate
6688         // that to the element type through `getAsArrayType`.
6689         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6690         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6691         // Re-generate the decayed type.
6692         Type = Context.getDecayedType(OrigTy);
6693       }
6694     }
6695     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6696     // Apply any qualifiers (including address space) from the array type to
6697     // the element type. This implements C99 6.7.3p8: "If the specification of
6698     // an array type includes any type qualifiers, the element type is so
6699     // qualified, not the array type."
6700     if (Type->isArrayType())
6701       Type = QualType(Context.getAsArrayType(Type), 0);
6702     Decl->setType(Type);
6703   }
6704 }
6705 
6706 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6707   // Ensure that an auto decl is deduced otherwise the checks below might cache
6708   // the wrong linkage.
6709   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6710 
6711   // 'weak' only applies to declarations with external linkage.
6712   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6713     if (!ND.isExternallyVisible()) {
6714       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6715       ND.dropAttr<WeakAttr>();
6716     }
6717   }
6718   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6719     if (ND.isExternallyVisible()) {
6720       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6721       ND.dropAttr<WeakRefAttr>();
6722       ND.dropAttr<AliasAttr>();
6723     }
6724   }
6725 
6726   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6727     if (VD->hasInit()) {
6728       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6729         assert(VD->isThisDeclarationADefinition() &&
6730                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6731         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6732         VD->dropAttr<AliasAttr>();
6733       }
6734     }
6735   }
6736 
6737   // 'selectany' only applies to externally visible variable declarations.
6738   // It does not apply to functions.
6739   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6740     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6741       S.Diag(Attr->getLocation(),
6742              diag::err_attribute_selectany_non_extern_data);
6743       ND.dropAttr<SelectAnyAttr>();
6744     }
6745   }
6746 
6747   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6748     auto *VD = dyn_cast<VarDecl>(&ND);
6749     bool IsAnonymousNS = false;
6750     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6751     if (VD) {
6752       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6753       while (NS && !IsAnonymousNS) {
6754         IsAnonymousNS = NS->isAnonymousNamespace();
6755         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6756       }
6757     }
6758     // dll attributes require external linkage. Static locals may have external
6759     // linkage but still cannot be explicitly imported or exported.
6760     // In Microsoft mode, a variable defined in anonymous namespace must have
6761     // external linkage in order to be exported.
6762     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6763     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6764         (!AnonNSInMicrosoftMode &&
6765          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6766       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6767         << &ND << Attr;
6768       ND.setInvalidDecl();
6769     }
6770   }
6771 
6772   // Check the attributes on the function type, if any.
6773   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6774     // Don't declare this variable in the second operand of the for-statement;
6775     // GCC miscompiles that by ending its lifetime before evaluating the
6776     // third operand. See gcc.gnu.org/PR86769.
6777     AttributedTypeLoc ATL;
6778     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6779          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6780          TL = ATL.getModifiedLoc()) {
6781       // The [[lifetimebound]] attribute can be applied to the implicit object
6782       // parameter of a non-static member function (other than a ctor or dtor)
6783       // by applying it to the function type.
6784       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6785         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6786         if (!MD || MD->isStatic()) {
6787           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6788               << !MD << A->getRange();
6789         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6790           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6791               << isa<CXXDestructorDecl>(MD) << A->getRange();
6792         }
6793       }
6794     }
6795   }
6796 }
6797 
6798 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6799                                            NamedDecl *NewDecl,
6800                                            bool IsSpecialization,
6801                                            bool IsDefinition) {
6802   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6803     return;
6804 
6805   bool IsTemplate = false;
6806   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6807     OldDecl = OldTD->getTemplatedDecl();
6808     IsTemplate = true;
6809     if (!IsSpecialization)
6810       IsDefinition = false;
6811   }
6812   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6813     NewDecl = NewTD->getTemplatedDecl();
6814     IsTemplate = true;
6815   }
6816 
6817   if (!OldDecl || !NewDecl)
6818     return;
6819 
6820   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6821   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6822   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6823   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6824 
6825   // dllimport and dllexport are inheritable attributes so we have to exclude
6826   // inherited attribute instances.
6827   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6828                     (NewExportAttr && !NewExportAttr->isInherited());
6829 
6830   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6831   // the only exception being explicit specializations.
6832   // Implicitly generated declarations are also excluded for now because there
6833   // is no other way to switch these to use dllimport or dllexport.
6834   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6835 
6836   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6837     // Allow with a warning for free functions and global variables.
6838     bool JustWarn = false;
6839     if (!OldDecl->isCXXClassMember()) {
6840       auto *VD = dyn_cast<VarDecl>(OldDecl);
6841       if (VD && !VD->getDescribedVarTemplate())
6842         JustWarn = true;
6843       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6844       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6845         JustWarn = true;
6846     }
6847 
6848     // We cannot change a declaration that's been used because IR has already
6849     // been emitted. Dllimported functions will still work though (modulo
6850     // address equality) as they can use the thunk.
6851     if (OldDecl->isUsed())
6852       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6853         JustWarn = false;
6854 
6855     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6856                                : diag::err_attribute_dll_redeclaration;
6857     S.Diag(NewDecl->getLocation(), DiagID)
6858         << NewDecl
6859         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6860     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6861     if (!JustWarn) {
6862       NewDecl->setInvalidDecl();
6863       return;
6864     }
6865   }
6866 
6867   // A redeclaration is not allowed to drop a dllimport attribute, the only
6868   // exceptions being inline function definitions (except for function
6869   // templates), local extern declarations, qualified friend declarations or
6870   // special MSVC extension: in the last case, the declaration is treated as if
6871   // it were marked dllexport.
6872   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6873   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6874   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6875     // Ignore static data because out-of-line definitions are diagnosed
6876     // separately.
6877     IsStaticDataMember = VD->isStaticDataMember();
6878     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6879                    VarDecl::DeclarationOnly;
6880   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6881     IsInline = FD->isInlined();
6882     IsQualifiedFriend = FD->getQualifier() &&
6883                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6884   }
6885 
6886   if (OldImportAttr && !HasNewAttr &&
6887       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6888       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6889     if (IsMicrosoftABI && IsDefinition) {
6890       S.Diag(NewDecl->getLocation(),
6891              diag::warn_redeclaration_without_import_attribute)
6892           << NewDecl;
6893       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6894       NewDecl->dropAttr<DLLImportAttr>();
6895       NewDecl->addAttr(
6896           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6897     } else {
6898       S.Diag(NewDecl->getLocation(),
6899              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6900           << NewDecl << OldImportAttr;
6901       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6902       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6903       OldDecl->dropAttr<DLLImportAttr>();
6904       NewDecl->dropAttr<DLLImportAttr>();
6905     }
6906   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6907     // In MinGW, seeing a function declared inline drops the dllimport
6908     // attribute.
6909     OldDecl->dropAttr<DLLImportAttr>();
6910     NewDecl->dropAttr<DLLImportAttr>();
6911     S.Diag(NewDecl->getLocation(),
6912            diag::warn_dllimport_dropped_from_inline_function)
6913         << NewDecl << OldImportAttr;
6914   }
6915 
6916   // A specialization of a class template member function is processed here
6917   // since it's a redeclaration. If the parent class is dllexport, the
6918   // specialization inherits that attribute. This doesn't happen automatically
6919   // since the parent class isn't instantiated until later.
6920   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6921     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6922         !NewImportAttr && !NewExportAttr) {
6923       if (const DLLExportAttr *ParentExportAttr =
6924               MD->getParent()->getAttr<DLLExportAttr>()) {
6925         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6926         NewAttr->setInherited(true);
6927         NewDecl->addAttr(NewAttr);
6928       }
6929     }
6930   }
6931 }
6932 
6933 /// Given that we are within the definition of the given function,
6934 /// will that definition behave like C99's 'inline', where the
6935 /// definition is discarded except for optimization purposes?
6936 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6937   // Try to avoid calling GetGVALinkageForFunction.
6938 
6939   // All cases of this require the 'inline' keyword.
6940   if (!FD->isInlined()) return false;
6941 
6942   // This is only possible in C++ with the gnu_inline attribute.
6943   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6944     return false;
6945 
6946   // Okay, go ahead and call the relatively-more-expensive function.
6947   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6948 }
6949 
6950 /// Determine whether a variable is extern "C" prior to attaching
6951 /// an initializer. We can't just call isExternC() here, because that
6952 /// will also compute and cache whether the declaration is externally
6953 /// visible, which might change when we attach the initializer.
6954 ///
6955 /// This can only be used if the declaration is known to not be a
6956 /// redeclaration of an internal linkage declaration.
6957 ///
6958 /// For instance:
6959 ///
6960 ///   auto x = []{};
6961 ///
6962 /// Attaching the initializer here makes this declaration not externally
6963 /// visible, because its type has internal linkage.
6964 ///
6965 /// FIXME: This is a hack.
6966 template<typename T>
6967 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6968   if (S.getLangOpts().CPlusPlus) {
6969     // In C++, the overloadable attribute negates the effects of extern "C".
6970     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6971       return false;
6972 
6973     // So do CUDA's host/device attributes.
6974     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6975                                  D->template hasAttr<CUDAHostAttr>()))
6976       return false;
6977   }
6978   return D->isExternC();
6979 }
6980 
6981 static bool shouldConsiderLinkage(const VarDecl *VD) {
6982   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6983   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6984       isa<OMPDeclareMapperDecl>(DC))
6985     return VD->hasExternalStorage();
6986   if (DC->isFileContext())
6987     return true;
6988   if (DC->isRecord())
6989     return false;
6990   if (isa<RequiresExprBodyDecl>(DC))
6991     return false;
6992   llvm_unreachable("Unexpected context");
6993 }
6994 
6995 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6996   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6997   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6998       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6999     return true;
7000   if (DC->isRecord())
7001     return false;
7002   llvm_unreachable("Unexpected context");
7003 }
7004 
7005 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7006                           ParsedAttr::Kind Kind) {
7007   // Check decl attributes on the DeclSpec.
7008   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7009     return true;
7010 
7011   // Walk the declarator structure, checking decl attributes that were in a type
7012   // position to the decl itself.
7013   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7014     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7015       return true;
7016   }
7017 
7018   // Finally, check attributes on the decl itself.
7019   return PD.getAttributes().hasAttribute(Kind) ||
7020          PD.getDeclarationAttributes().hasAttribute(Kind);
7021 }
7022 
7023 /// Adjust the \c DeclContext for a function or variable that might be a
7024 /// function-local external declaration.
7025 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7026   if (!DC->isFunctionOrMethod())
7027     return false;
7028 
7029   // If this is a local extern function or variable declared within a function
7030   // template, don't add it into the enclosing namespace scope until it is
7031   // instantiated; it might have a dependent type right now.
7032   if (DC->isDependentContext())
7033     return true;
7034 
7035   // C++11 [basic.link]p7:
7036   //   When a block scope declaration of an entity with linkage is not found to
7037   //   refer to some other declaration, then that entity is a member of the
7038   //   innermost enclosing namespace.
7039   //
7040   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7041   // semantically-enclosing namespace, not a lexically-enclosing one.
7042   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7043     DC = DC->getParent();
7044   return true;
7045 }
7046 
7047 /// Returns true if given declaration has external C language linkage.
7048 static bool isDeclExternC(const Decl *D) {
7049   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7050     return FD->isExternC();
7051   if (const auto *VD = dyn_cast<VarDecl>(D))
7052     return VD->isExternC();
7053 
7054   llvm_unreachable("Unknown type of decl!");
7055 }
7056 
7057 /// Returns true if there hasn't been any invalid type diagnosed.
7058 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7059   DeclContext *DC = NewVD->getDeclContext();
7060   QualType R = NewVD->getType();
7061 
7062   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7063   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7064   // argument.
7065   if (R->isImageType() || R->isPipeType()) {
7066     Se.Diag(NewVD->getLocation(),
7067             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7068         << R;
7069     NewVD->setInvalidDecl();
7070     return false;
7071   }
7072 
7073   // OpenCL v1.2 s6.9.r:
7074   // The event type cannot be used to declare a program scope variable.
7075   // OpenCL v2.0 s6.9.q:
7076   // The clk_event_t and reserve_id_t types cannot be declared in program
7077   // scope.
7078   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7079     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7080       Se.Diag(NewVD->getLocation(),
7081               diag::err_invalid_type_for_program_scope_var)
7082           << R;
7083       NewVD->setInvalidDecl();
7084       return false;
7085     }
7086   }
7087 
7088   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7089   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7090                                                Se.getLangOpts())) {
7091     QualType NR = R.getCanonicalType();
7092     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7093            NR->isReferenceType()) {
7094       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7095           NR->isFunctionReferenceType()) {
7096         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7097             << NR->isReferenceType();
7098         NewVD->setInvalidDecl();
7099         return false;
7100       }
7101       NR = NR->getPointeeType();
7102     }
7103   }
7104 
7105   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7106                                                Se.getLangOpts())) {
7107     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7108     // half array type (unless the cl_khr_fp16 extension is enabled).
7109     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7110       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7111       NewVD->setInvalidDecl();
7112       return false;
7113     }
7114   }
7115 
7116   // OpenCL v1.2 s6.9.r:
7117   // The event type cannot be used with the __local, __constant and __global
7118   // address space qualifiers.
7119   if (R->isEventT()) {
7120     if (R.getAddressSpace() != LangAS::opencl_private) {
7121       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7122       NewVD->setInvalidDecl();
7123       return false;
7124     }
7125   }
7126 
7127   if (R->isSamplerT()) {
7128     // OpenCL v1.2 s6.9.b p4:
7129     // The sampler type cannot be used with the __local and __global address
7130     // space qualifiers.
7131     if (R.getAddressSpace() == LangAS::opencl_local ||
7132         R.getAddressSpace() == LangAS::opencl_global) {
7133       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7134       NewVD->setInvalidDecl();
7135     }
7136 
7137     // OpenCL v1.2 s6.12.14.1:
7138     // A global sampler must be declared with either the constant address
7139     // space qualifier or with the const qualifier.
7140     if (DC->isTranslationUnit() &&
7141         !(R.getAddressSpace() == LangAS::opencl_constant ||
7142           R.isConstQualified())) {
7143       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7144       NewVD->setInvalidDecl();
7145     }
7146     if (NewVD->isInvalidDecl())
7147       return false;
7148   }
7149 
7150   return true;
7151 }
7152 
7153 template <typename AttrTy>
7154 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7155   const TypedefNameDecl *TND = TT->getDecl();
7156   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7157     AttrTy *Clone = Attribute->clone(S.Context);
7158     Clone->setInherited(true);
7159     D->addAttr(Clone);
7160   }
7161 }
7162 
7163 NamedDecl *Sema::ActOnVariableDeclarator(
7164     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7165     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7166     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7167   QualType R = TInfo->getType();
7168   DeclarationName Name = GetNameForDeclarator(D).getName();
7169 
7170   IdentifierInfo *II = Name.getAsIdentifierInfo();
7171 
7172   if (D.isDecompositionDeclarator()) {
7173     // Take the name of the first declarator as our name for diagnostic
7174     // purposes.
7175     auto &Decomp = D.getDecompositionDeclarator();
7176     if (!Decomp.bindings().empty()) {
7177       II = Decomp.bindings()[0].Name;
7178       Name = II;
7179     }
7180   } else if (!II) {
7181     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7182     return nullptr;
7183   }
7184 
7185 
7186   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7187   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7188 
7189   // dllimport globals without explicit storage class are treated as extern. We
7190   // have to change the storage class this early to get the right DeclContext.
7191   if (SC == SC_None && !DC->isRecord() &&
7192       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7193       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7194     SC = SC_Extern;
7195 
7196   DeclContext *OriginalDC = DC;
7197   bool IsLocalExternDecl = SC == SC_Extern &&
7198                            adjustContextForLocalExternDecl(DC);
7199 
7200   if (SCSpec == DeclSpec::SCS_mutable) {
7201     // mutable can only appear on non-static class members, so it's always
7202     // an error here
7203     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7204     D.setInvalidType();
7205     SC = SC_None;
7206   }
7207 
7208   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7209       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7210                               D.getDeclSpec().getStorageClassSpecLoc())) {
7211     // In C++11, the 'register' storage class specifier is deprecated.
7212     // Suppress the warning in system macros, it's used in macros in some
7213     // popular C system headers, such as in glibc's htonl() macro.
7214     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7215          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7216                                    : diag::warn_deprecated_register)
7217       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7218   }
7219 
7220   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7221 
7222   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7223     // C99 6.9p2: The storage-class specifiers auto and register shall not
7224     // appear in the declaration specifiers in an external declaration.
7225     // Global Register+Asm is a GNU extension we support.
7226     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7227       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7228       D.setInvalidType();
7229     }
7230   }
7231 
7232   // If this variable has a VLA type and an initializer, try to
7233   // fold to a constant-sized type. This is otherwise invalid.
7234   if (D.hasInitializer() && R->isVariableArrayType())
7235     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7236                                     /*DiagID=*/0);
7237 
7238   bool IsMemberSpecialization = false;
7239   bool IsVariableTemplateSpecialization = false;
7240   bool IsPartialSpecialization = false;
7241   bool IsVariableTemplate = false;
7242   VarDecl *NewVD = nullptr;
7243   VarTemplateDecl *NewTemplate = nullptr;
7244   TemplateParameterList *TemplateParams = nullptr;
7245   if (!getLangOpts().CPlusPlus) {
7246     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7247                             II, R, TInfo, SC);
7248 
7249     if (R->getContainedDeducedType())
7250       ParsingInitForAutoVars.insert(NewVD);
7251 
7252     if (D.isInvalidType())
7253       NewVD->setInvalidDecl();
7254 
7255     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7256         NewVD->hasLocalStorage())
7257       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7258                             NTCUC_AutoVar, NTCUK_Destruct);
7259   } else {
7260     bool Invalid = false;
7261 
7262     if (DC->isRecord() && !CurContext->isRecord()) {
7263       // This is an out-of-line definition of a static data member.
7264       switch (SC) {
7265       case SC_None:
7266         break;
7267       case SC_Static:
7268         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7269              diag::err_static_out_of_line)
7270           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7271         break;
7272       case SC_Auto:
7273       case SC_Register:
7274       case SC_Extern:
7275         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7276         // to names of variables declared in a block or to function parameters.
7277         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7278         // of class members
7279 
7280         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7281              diag::err_storage_class_for_static_member)
7282           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7283         break;
7284       case SC_PrivateExtern:
7285         llvm_unreachable("C storage class in c++!");
7286       }
7287     }
7288 
7289     if (SC == SC_Static && CurContext->isRecord()) {
7290       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7291         // Walk up the enclosing DeclContexts to check for any that are
7292         // incompatible with static data members.
7293         const DeclContext *FunctionOrMethod = nullptr;
7294         const CXXRecordDecl *AnonStruct = nullptr;
7295         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7296           if (Ctxt->isFunctionOrMethod()) {
7297             FunctionOrMethod = Ctxt;
7298             break;
7299           }
7300           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7301           if (ParentDecl && !ParentDecl->getDeclName()) {
7302             AnonStruct = ParentDecl;
7303             break;
7304           }
7305         }
7306         if (FunctionOrMethod) {
7307           // C++ [class.static.data]p5: A local class shall not have static data
7308           // members.
7309           Diag(D.getIdentifierLoc(),
7310                diag::err_static_data_member_not_allowed_in_local_class)
7311             << Name << RD->getDeclName() << RD->getTagKind();
7312         } else if (AnonStruct) {
7313           // C++ [class.static.data]p4: Unnamed classes and classes contained
7314           // directly or indirectly within unnamed classes shall not contain
7315           // static data members.
7316           Diag(D.getIdentifierLoc(),
7317                diag::err_static_data_member_not_allowed_in_anon_struct)
7318             << Name << AnonStruct->getTagKind();
7319           Invalid = true;
7320         } else if (RD->isUnion()) {
7321           // C++98 [class.union]p1: If a union contains a static data member,
7322           // the program is ill-formed. C++11 drops this restriction.
7323           Diag(D.getIdentifierLoc(),
7324                getLangOpts().CPlusPlus11
7325                  ? diag::warn_cxx98_compat_static_data_member_in_union
7326                  : diag::ext_static_data_member_in_union) << Name;
7327         }
7328       }
7329     }
7330 
7331     // Match up the template parameter lists with the scope specifier, then
7332     // determine whether we have a template or a template specialization.
7333     bool InvalidScope = false;
7334     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7335         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7336         D.getCXXScopeSpec(),
7337         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7338             ? D.getName().TemplateId
7339             : nullptr,
7340         TemplateParamLists,
7341         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7342     Invalid |= InvalidScope;
7343 
7344     if (TemplateParams) {
7345       if (!TemplateParams->size() &&
7346           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7347         // There is an extraneous 'template<>' for this variable. Complain
7348         // about it, but allow the declaration of the variable.
7349         Diag(TemplateParams->getTemplateLoc(),
7350              diag::err_template_variable_noparams)
7351           << II
7352           << SourceRange(TemplateParams->getTemplateLoc(),
7353                          TemplateParams->getRAngleLoc());
7354         TemplateParams = nullptr;
7355       } else {
7356         // Check that we can declare a template here.
7357         if (CheckTemplateDeclScope(S, TemplateParams))
7358           return nullptr;
7359 
7360         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7361           // This is an explicit specialization or a partial specialization.
7362           IsVariableTemplateSpecialization = true;
7363           IsPartialSpecialization = TemplateParams->size() > 0;
7364         } else { // if (TemplateParams->size() > 0)
7365           // This is a template declaration.
7366           IsVariableTemplate = true;
7367 
7368           // Only C++1y supports variable templates (N3651).
7369           Diag(D.getIdentifierLoc(),
7370                getLangOpts().CPlusPlus14
7371                    ? diag::warn_cxx11_compat_variable_template
7372                    : diag::ext_variable_template);
7373         }
7374       }
7375     } else {
7376       // Check that we can declare a member specialization here.
7377       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7378           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7379         return nullptr;
7380       assert((Invalid ||
7381               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7382              "should have a 'template<>' for this decl");
7383     }
7384 
7385     if (IsVariableTemplateSpecialization) {
7386       SourceLocation TemplateKWLoc =
7387           TemplateParamLists.size() > 0
7388               ? TemplateParamLists[0]->getTemplateLoc()
7389               : SourceLocation();
7390       DeclResult Res = ActOnVarTemplateSpecialization(
7391           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7392           IsPartialSpecialization);
7393       if (Res.isInvalid())
7394         return nullptr;
7395       NewVD = cast<VarDecl>(Res.get());
7396       AddToScope = false;
7397     } else if (D.isDecompositionDeclarator()) {
7398       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7399                                         D.getIdentifierLoc(), R, TInfo, SC,
7400                                         Bindings);
7401     } else
7402       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7403                               D.getIdentifierLoc(), II, R, TInfo, SC);
7404 
7405     // If this is supposed to be a variable template, create it as such.
7406     if (IsVariableTemplate) {
7407       NewTemplate =
7408           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7409                                   TemplateParams, NewVD);
7410       NewVD->setDescribedVarTemplate(NewTemplate);
7411     }
7412 
7413     // If this decl has an auto type in need of deduction, make a note of the
7414     // Decl so we can diagnose uses of it in its own initializer.
7415     if (R->getContainedDeducedType())
7416       ParsingInitForAutoVars.insert(NewVD);
7417 
7418     if (D.isInvalidType() || Invalid) {
7419       NewVD->setInvalidDecl();
7420       if (NewTemplate)
7421         NewTemplate->setInvalidDecl();
7422     }
7423 
7424     SetNestedNameSpecifier(*this, NewVD, D);
7425 
7426     // If we have any template parameter lists that don't directly belong to
7427     // the variable (matching the scope specifier), store them.
7428     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7429     if (TemplateParamLists.size() > VDTemplateParamLists)
7430       NewVD->setTemplateParameterListsInfo(
7431           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7432   }
7433 
7434   if (D.getDeclSpec().isInlineSpecified()) {
7435     if (!getLangOpts().CPlusPlus) {
7436       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7437           << 0;
7438     } else if (CurContext->isFunctionOrMethod()) {
7439       // 'inline' is not allowed on block scope variable declaration.
7440       Diag(D.getDeclSpec().getInlineSpecLoc(),
7441            diag::err_inline_declaration_block_scope) << Name
7442         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7443     } else {
7444       Diag(D.getDeclSpec().getInlineSpecLoc(),
7445            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7446                                      : diag::ext_inline_variable);
7447       NewVD->setInlineSpecified();
7448     }
7449   }
7450 
7451   // Set the lexical context. If the declarator has a C++ scope specifier, the
7452   // lexical context will be different from the semantic context.
7453   NewVD->setLexicalDeclContext(CurContext);
7454   if (NewTemplate)
7455     NewTemplate->setLexicalDeclContext(CurContext);
7456 
7457   if (IsLocalExternDecl) {
7458     if (D.isDecompositionDeclarator())
7459       for (auto *B : Bindings)
7460         B->setLocalExternDecl();
7461     else
7462       NewVD->setLocalExternDecl();
7463   }
7464 
7465   bool EmitTLSUnsupportedError = false;
7466   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7467     // C++11 [dcl.stc]p4:
7468     //   When thread_local is applied to a variable of block scope the
7469     //   storage-class-specifier static is implied if it does not appear
7470     //   explicitly.
7471     // Core issue: 'static' is not implied if the variable is declared
7472     //   'extern'.
7473     if (NewVD->hasLocalStorage() &&
7474         (SCSpec != DeclSpec::SCS_unspecified ||
7475          TSCS != DeclSpec::TSCS_thread_local ||
7476          !DC->isFunctionOrMethod()))
7477       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7478            diag::err_thread_non_global)
7479         << DeclSpec::getSpecifierName(TSCS);
7480     else if (!Context.getTargetInfo().isTLSSupported()) {
7481       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7482           getLangOpts().SYCLIsDevice) {
7483         // Postpone error emission until we've collected attributes required to
7484         // figure out whether it's a host or device variable and whether the
7485         // error should be ignored.
7486         EmitTLSUnsupportedError = true;
7487         // We still need to mark the variable as TLS so it shows up in AST with
7488         // proper storage class for other tools to use even if we're not going
7489         // to emit any code for it.
7490         NewVD->setTSCSpec(TSCS);
7491       } else
7492         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7493              diag::err_thread_unsupported);
7494     } else
7495       NewVD->setTSCSpec(TSCS);
7496   }
7497 
7498   switch (D.getDeclSpec().getConstexprSpecifier()) {
7499   case ConstexprSpecKind::Unspecified:
7500     break;
7501 
7502   case ConstexprSpecKind::Consteval:
7503     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7504          diag::err_constexpr_wrong_decl_kind)
7505         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7506     LLVM_FALLTHROUGH;
7507 
7508   case ConstexprSpecKind::Constexpr:
7509     NewVD->setConstexpr(true);
7510     // C++1z [dcl.spec.constexpr]p1:
7511     //   A static data member declared with the constexpr specifier is
7512     //   implicitly an inline variable.
7513     if (NewVD->isStaticDataMember() &&
7514         (getLangOpts().CPlusPlus17 ||
7515          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7516       NewVD->setImplicitlyInline();
7517     break;
7518 
7519   case ConstexprSpecKind::Constinit:
7520     if (!NewVD->hasGlobalStorage())
7521       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7522            diag::err_constinit_local_variable);
7523     else
7524       NewVD->addAttr(ConstInitAttr::Create(
7525           Context, D.getDeclSpec().getConstexprSpecLoc(),
7526           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7527     break;
7528   }
7529 
7530   // C99 6.7.4p3
7531   //   An inline definition of a function with external linkage shall
7532   //   not contain a definition of a modifiable object with static or
7533   //   thread storage duration...
7534   // We only apply this when the function is required to be defined
7535   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7536   // that a local variable with thread storage duration still has to
7537   // be marked 'static'.  Also note that it's possible to get these
7538   // semantics in C++ using __attribute__((gnu_inline)).
7539   if (SC == SC_Static && S->getFnParent() != nullptr &&
7540       !NewVD->getType().isConstQualified()) {
7541     FunctionDecl *CurFD = getCurFunctionDecl();
7542     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7543       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7544            diag::warn_static_local_in_extern_inline);
7545       MaybeSuggestAddingStaticToDecl(CurFD);
7546     }
7547   }
7548 
7549   if (D.getDeclSpec().isModulePrivateSpecified()) {
7550     if (IsVariableTemplateSpecialization)
7551       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7552           << (IsPartialSpecialization ? 1 : 0)
7553           << FixItHint::CreateRemoval(
7554                  D.getDeclSpec().getModulePrivateSpecLoc());
7555     else if (IsMemberSpecialization)
7556       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7557         << 2
7558         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7559     else if (NewVD->hasLocalStorage())
7560       Diag(NewVD->getLocation(), diag::err_module_private_local)
7561           << 0 << NewVD
7562           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7563           << FixItHint::CreateRemoval(
7564                  D.getDeclSpec().getModulePrivateSpecLoc());
7565     else {
7566       NewVD->setModulePrivate();
7567       if (NewTemplate)
7568         NewTemplate->setModulePrivate();
7569       for (auto *B : Bindings)
7570         B->setModulePrivate();
7571     }
7572   }
7573 
7574   if (getLangOpts().OpenCL) {
7575     deduceOpenCLAddressSpace(NewVD);
7576 
7577     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7578     if (TSC != TSCS_unspecified) {
7579       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7580            diag::err_opencl_unknown_type_specifier)
7581           << getLangOpts().getOpenCLVersionString()
7582           << DeclSpec::getSpecifierName(TSC) << 1;
7583       NewVD->setInvalidDecl();
7584     }
7585   }
7586 
7587   // Handle attributes prior to checking for duplicates in MergeVarDecl
7588   ProcessDeclAttributes(S, NewVD, D);
7589 
7590   // FIXME: This is probably the wrong location to be doing this and we should
7591   // probably be doing this for more attributes (especially for function
7592   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7593   // the code to copy attributes would be generated by TableGen.
7594   if (R->isFunctionPointerType())
7595     if (const auto *TT = R->getAs<TypedefType>())
7596       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7597 
7598   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7599       getLangOpts().SYCLIsDevice) {
7600     if (EmitTLSUnsupportedError &&
7601         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7602          (getLangOpts().OpenMPIsDevice &&
7603           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7604       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7605            diag::err_thread_unsupported);
7606 
7607     if (EmitTLSUnsupportedError &&
7608         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7609       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7610     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7611     // storage [duration]."
7612     if (SC == SC_None && S->getFnParent() != nullptr &&
7613         (NewVD->hasAttr<CUDASharedAttr>() ||
7614          NewVD->hasAttr<CUDAConstantAttr>())) {
7615       NewVD->setStorageClass(SC_Static);
7616     }
7617   }
7618 
7619   // Ensure that dllimport globals without explicit storage class are treated as
7620   // extern. The storage class is set above using parsed attributes. Now we can
7621   // check the VarDecl itself.
7622   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7623          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7624          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7625 
7626   // In auto-retain/release, infer strong retension for variables of
7627   // retainable type.
7628   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7629     NewVD->setInvalidDecl();
7630 
7631   // Handle GNU asm-label extension (encoded as an attribute).
7632   if (Expr *E = (Expr*)D.getAsmLabel()) {
7633     // The parser guarantees this is a string.
7634     StringLiteral *SE = cast<StringLiteral>(E);
7635     StringRef Label = SE->getString();
7636     if (S->getFnParent() != nullptr) {
7637       switch (SC) {
7638       case SC_None:
7639       case SC_Auto:
7640         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7641         break;
7642       case SC_Register:
7643         // Local Named register
7644         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7645             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7646           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7647         break;
7648       case SC_Static:
7649       case SC_Extern:
7650       case SC_PrivateExtern:
7651         break;
7652       }
7653     } else if (SC == SC_Register) {
7654       // Global Named register
7655       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7656         const auto &TI = Context.getTargetInfo();
7657         bool HasSizeMismatch;
7658 
7659         if (!TI.isValidGCCRegisterName(Label))
7660           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7661         else if (!TI.validateGlobalRegisterVariable(Label,
7662                                                     Context.getTypeSize(R),
7663                                                     HasSizeMismatch))
7664           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7665         else if (HasSizeMismatch)
7666           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7667       }
7668 
7669       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7670         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7671         NewVD->setInvalidDecl(true);
7672       }
7673     }
7674 
7675     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7676                                         /*IsLiteralLabel=*/true,
7677                                         SE->getStrTokenLoc(0)));
7678   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7679     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7680       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7681     if (I != ExtnameUndeclaredIdentifiers.end()) {
7682       if (isDeclExternC(NewVD)) {
7683         NewVD->addAttr(I->second);
7684         ExtnameUndeclaredIdentifiers.erase(I);
7685       } else
7686         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7687             << /*Variable*/1 << NewVD;
7688     }
7689   }
7690 
7691   // Find the shadowed declaration before filtering for scope.
7692   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7693                                 ? getShadowedDeclaration(NewVD, Previous)
7694                                 : nullptr;
7695 
7696   // Don't consider existing declarations that are in a different
7697   // scope and are out-of-semantic-context declarations (if the new
7698   // declaration has linkage).
7699   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7700                        D.getCXXScopeSpec().isNotEmpty() ||
7701                        IsMemberSpecialization ||
7702                        IsVariableTemplateSpecialization);
7703 
7704   // Check whether the previous declaration is in the same block scope. This
7705   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7706   if (getLangOpts().CPlusPlus &&
7707       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7708     NewVD->setPreviousDeclInSameBlockScope(
7709         Previous.isSingleResult() && !Previous.isShadowed() &&
7710         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7711 
7712   if (!getLangOpts().CPlusPlus) {
7713     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7714   } else {
7715     // If this is an explicit specialization of a static data member, check it.
7716     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7717         CheckMemberSpecialization(NewVD, Previous))
7718       NewVD->setInvalidDecl();
7719 
7720     // Merge the decl with the existing one if appropriate.
7721     if (!Previous.empty()) {
7722       if (Previous.isSingleResult() &&
7723           isa<FieldDecl>(Previous.getFoundDecl()) &&
7724           D.getCXXScopeSpec().isSet()) {
7725         // The user tried to define a non-static data member
7726         // out-of-line (C++ [dcl.meaning]p1).
7727         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7728           << D.getCXXScopeSpec().getRange();
7729         Previous.clear();
7730         NewVD->setInvalidDecl();
7731       }
7732     } else if (D.getCXXScopeSpec().isSet()) {
7733       // No previous declaration in the qualifying scope.
7734       Diag(D.getIdentifierLoc(), diag::err_no_member)
7735         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7736         << D.getCXXScopeSpec().getRange();
7737       NewVD->setInvalidDecl();
7738     }
7739 
7740     if (!IsVariableTemplateSpecialization)
7741       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7742 
7743     if (NewTemplate) {
7744       VarTemplateDecl *PrevVarTemplate =
7745           NewVD->getPreviousDecl()
7746               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7747               : nullptr;
7748 
7749       // Check the template parameter list of this declaration, possibly
7750       // merging in the template parameter list from the previous variable
7751       // template declaration.
7752       if (CheckTemplateParameterList(
7753               TemplateParams,
7754               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7755                               : nullptr,
7756               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7757                DC->isDependentContext())
7758                   ? TPC_ClassTemplateMember
7759                   : TPC_VarTemplate))
7760         NewVD->setInvalidDecl();
7761 
7762       // If we are providing an explicit specialization of a static variable
7763       // template, make a note of that.
7764       if (PrevVarTemplate &&
7765           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7766         PrevVarTemplate->setMemberSpecialization();
7767     }
7768   }
7769 
7770   // Diagnose shadowed variables iff this isn't a redeclaration.
7771   if (ShadowedDecl && !D.isRedeclaration())
7772     CheckShadow(NewVD, ShadowedDecl, Previous);
7773 
7774   ProcessPragmaWeak(S, NewVD);
7775 
7776   // If this is the first declaration of an extern C variable, update
7777   // the map of such variables.
7778   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7779       isIncompleteDeclExternC(*this, NewVD))
7780     RegisterLocallyScopedExternCDecl(NewVD, S);
7781 
7782   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7783     MangleNumberingContext *MCtx;
7784     Decl *ManglingContextDecl;
7785     std::tie(MCtx, ManglingContextDecl) =
7786         getCurrentMangleNumberContext(NewVD->getDeclContext());
7787     if (MCtx) {
7788       Context.setManglingNumber(
7789           NewVD, MCtx->getManglingNumber(
7790                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7791       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7792     }
7793   }
7794 
7795   // Special handling of variable named 'main'.
7796   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7797       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7798       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7799 
7800     // C++ [basic.start.main]p3
7801     // A program that declares a variable main at global scope is ill-formed.
7802     if (getLangOpts().CPlusPlus)
7803       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7804 
7805     // In C, and external-linkage variable named main results in undefined
7806     // behavior.
7807     else if (NewVD->hasExternalFormalLinkage())
7808       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7809   }
7810 
7811   if (D.isRedeclaration() && !Previous.empty()) {
7812     NamedDecl *Prev = Previous.getRepresentativeDecl();
7813     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7814                                    D.isFunctionDefinition());
7815   }
7816 
7817   if (NewTemplate) {
7818     if (NewVD->isInvalidDecl())
7819       NewTemplate->setInvalidDecl();
7820     ActOnDocumentableDecl(NewTemplate);
7821     return NewTemplate;
7822   }
7823 
7824   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7825     CompleteMemberSpecialization(NewVD, Previous);
7826 
7827   return NewVD;
7828 }
7829 
7830 /// Enum describing the %select options in diag::warn_decl_shadow.
7831 enum ShadowedDeclKind {
7832   SDK_Local,
7833   SDK_Global,
7834   SDK_StaticMember,
7835   SDK_Field,
7836   SDK_Typedef,
7837   SDK_Using,
7838   SDK_StructuredBinding
7839 };
7840 
7841 /// Determine what kind of declaration we're shadowing.
7842 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7843                                                 const DeclContext *OldDC) {
7844   if (isa<TypeAliasDecl>(ShadowedDecl))
7845     return SDK_Using;
7846   else if (isa<TypedefDecl>(ShadowedDecl))
7847     return SDK_Typedef;
7848   else if (isa<BindingDecl>(ShadowedDecl))
7849     return SDK_StructuredBinding;
7850   else if (isa<RecordDecl>(OldDC))
7851     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7852 
7853   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7854 }
7855 
7856 /// Return the location of the capture if the given lambda captures the given
7857 /// variable \p VD, or an invalid source location otherwise.
7858 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7859                                          const VarDecl *VD) {
7860   for (const Capture &Capture : LSI->Captures) {
7861     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7862       return Capture.getLocation();
7863   }
7864   return SourceLocation();
7865 }
7866 
7867 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7868                                      const LookupResult &R) {
7869   // Only diagnose if we're shadowing an unambiguous field or variable.
7870   if (R.getResultKind() != LookupResult::Found)
7871     return false;
7872 
7873   // Return false if warning is ignored.
7874   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7875 }
7876 
7877 /// Return the declaration shadowed by the given variable \p D, or null
7878 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7879 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7880                                         const LookupResult &R) {
7881   if (!shouldWarnIfShadowedDecl(Diags, R))
7882     return nullptr;
7883 
7884   // Don't diagnose declarations at file scope.
7885   if (D->hasGlobalStorage())
7886     return nullptr;
7887 
7888   NamedDecl *ShadowedDecl = R.getFoundDecl();
7889   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7890                                                             : nullptr;
7891 }
7892 
7893 /// Return the declaration shadowed by the given typedef \p D, or null
7894 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7895 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7896                                         const LookupResult &R) {
7897   // Don't warn if typedef declaration is part of a class
7898   if (D->getDeclContext()->isRecord())
7899     return nullptr;
7900 
7901   if (!shouldWarnIfShadowedDecl(Diags, R))
7902     return nullptr;
7903 
7904   NamedDecl *ShadowedDecl = R.getFoundDecl();
7905   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7906 }
7907 
7908 /// Return the declaration shadowed by the given variable \p D, or null
7909 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7910 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7911                                         const LookupResult &R) {
7912   if (!shouldWarnIfShadowedDecl(Diags, R))
7913     return nullptr;
7914 
7915   NamedDecl *ShadowedDecl = R.getFoundDecl();
7916   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7917                                                             : nullptr;
7918 }
7919 
7920 /// Diagnose variable or built-in function shadowing.  Implements
7921 /// -Wshadow.
7922 ///
7923 /// This method is called whenever a VarDecl is added to a "useful"
7924 /// scope.
7925 ///
7926 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7927 /// \param R the lookup of the name
7928 ///
7929 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7930                        const LookupResult &R) {
7931   DeclContext *NewDC = D->getDeclContext();
7932 
7933   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7934     // Fields are not shadowed by variables in C++ static methods.
7935     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7936       if (MD->isStatic())
7937         return;
7938 
7939     // Fields shadowed by constructor parameters are a special case. Usually
7940     // the constructor initializes the field with the parameter.
7941     if (isa<CXXConstructorDecl>(NewDC))
7942       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7943         // Remember that this was shadowed so we can either warn about its
7944         // modification or its existence depending on warning settings.
7945         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7946         return;
7947       }
7948   }
7949 
7950   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7951     if (shadowedVar->isExternC()) {
7952       // For shadowing external vars, make sure that we point to the global
7953       // declaration, not a locally scoped extern declaration.
7954       for (auto I : shadowedVar->redecls())
7955         if (I->isFileVarDecl()) {
7956           ShadowedDecl = I;
7957           break;
7958         }
7959     }
7960 
7961   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7962 
7963   unsigned WarningDiag = diag::warn_decl_shadow;
7964   SourceLocation CaptureLoc;
7965   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7966       isa<CXXMethodDecl>(NewDC)) {
7967     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7968       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7969         if (RD->getLambdaCaptureDefault() == LCD_None) {
7970           // Try to avoid warnings for lambdas with an explicit capture list.
7971           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7972           // Warn only when the lambda captures the shadowed decl explicitly.
7973           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7974           if (CaptureLoc.isInvalid())
7975             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7976         } else {
7977           // Remember that this was shadowed so we can avoid the warning if the
7978           // shadowed decl isn't captured and the warning settings allow it.
7979           cast<LambdaScopeInfo>(getCurFunction())
7980               ->ShadowingDecls.push_back(
7981                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7982           return;
7983         }
7984       }
7985 
7986       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7987         // A variable can't shadow a local variable in an enclosing scope, if
7988         // they are separated by a non-capturing declaration context.
7989         for (DeclContext *ParentDC = NewDC;
7990              ParentDC && !ParentDC->Equals(OldDC);
7991              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7992           // Only block literals, captured statements, and lambda expressions
7993           // can capture; other scopes don't.
7994           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7995               !isLambdaCallOperator(ParentDC)) {
7996             return;
7997           }
7998         }
7999       }
8000     }
8001   }
8002 
8003   // Only warn about certain kinds of shadowing for class members.
8004   if (NewDC && NewDC->isRecord()) {
8005     // In particular, don't warn about shadowing non-class members.
8006     if (!OldDC->isRecord())
8007       return;
8008 
8009     // TODO: should we warn about static data members shadowing
8010     // static data members from base classes?
8011 
8012     // TODO: don't diagnose for inaccessible shadowed members.
8013     // This is hard to do perfectly because we might friend the
8014     // shadowing context, but that's just a false negative.
8015   }
8016 
8017 
8018   DeclarationName Name = R.getLookupName();
8019 
8020   // Emit warning and note.
8021   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8022   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8023   if (!CaptureLoc.isInvalid())
8024     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8025         << Name << /*explicitly*/ 1;
8026   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8027 }
8028 
8029 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8030 /// when these variables are captured by the lambda.
8031 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8032   for (const auto &Shadow : LSI->ShadowingDecls) {
8033     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8034     // Try to avoid the warning when the shadowed decl isn't captured.
8035     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8036     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8037     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8038                                        ? diag::warn_decl_shadow_uncaptured_local
8039                                        : diag::warn_decl_shadow)
8040         << Shadow.VD->getDeclName()
8041         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8042     if (!CaptureLoc.isInvalid())
8043       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8044           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8045     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8046   }
8047 }
8048 
8049 /// Check -Wshadow without the advantage of a previous lookup.
8050 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8051   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8052     return;
8053 
8054   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8055                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8056   LookupName(R, S);
8057   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8058     CheckShadow(D, ShadowedDecl, R);
8059 }
8060 
8061 /// Check if 'E', which is an expression that is about to be modified, refers
8062 /// to a constructor parameter that shadows a field.
8063 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8064   // Quickly ignore expressions that can't be shadowing ctor parameters.
8065   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8066     return;
8067   E = E->IgnoreParenImpCasts();
8068   auto *DRE = dyn_cast<DeclRefExpr>(E);
8069   if (!DRE)
8070     return;
8071   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8072   auto I = ShadowingDecls.find(D);
8073   if (I == ShadowingDecls.end())
8074     return;
8075   const NamedDecl *ShadowedDecl = I->second;
8076   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8077   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8078   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8079   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8080 
8081   // Avoid issuing multiple warnings about the same decl.
8082   ShadowingDecls.erase(I);
8083 }
8084 
8085 /// Check for conflict between this global or extern "C" declaration and
8086 /// previous global or extern "C" declarations. This is only used in C++.
8087 template<typename T>
8088 static bool checkGlobalOrExternCConflict(
8089     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8090   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8091   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8092 
8093   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8094     // The common case: this global doesn't conflict with any extern "C"
8095     // declaration.
8096     return false;
8097   }
8098 
8099   if (Prev) {
8100     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8101       // Both the old and new declarations have C language linkage. This is a
8102       // redeclaration.
8103       Previous.clear();
8104       Previous.addDecl(Prev);
8105       return true;
8106     }
8107 
8108     // This is a global, non-extern "C" declaration, and there is a previous
8109     // non-global extern "C" declaration. Diagnose if this is a variable
8110     // declaration.
8111     if (!isa<VarDecl>(ND))
8112       return false;
8113   } else {
8114     // The declaration is extern "C". Check for any declaration in the
8115     // translation unit which might conflict.
8116     if (IsGlobal) {
8117       // We have already performed the lookup into the translation unit.
8118       IsGlobal = false;
8119       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8120            I != E; ++I) {
8121         if (isa<VarDecl>(*I)) {
8122           Prev = *I;
8123           break;
8124         }
8125       }
8126     } else {
8127       DeclContext::lookup_result R =
8128           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8129       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8130            I != E; ++I) {
8131         if (isa<VarDecl>(*I)) {
8132           Prev = *I;
8133           break;
8134         }
8135         // FIXME: If we have any other entity with this name in global scope,
8136         // the declaration is ill-formed, but that is a defect: it breaks the
8137         // 'stat' hack, for instance. Only variables can have mangled name
8138         // clashes with extern "C" declarations, so only they deserve a
8139         // diagnostic.
8140       }
8141     }
8142 
8143     if (!Prev)
8144       return false;
8145   }
8146 
8147   // Use the first declaration's location to ensure we point at something which
8148   // is lexically inside an extern "C" linkage-spec.
8149   assert(Prev && "should have found a previous declaration to diagnose");
8150   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8151     Prev = FD->getFirstDecl();
8152   else
8153     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8154 
8155   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8156     << IsGlobal << ND;
8157   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8158     << IsGlobal;
8159   return false;
8160 }
8161 
8162 /// Apply special rules for handling extern "C" declarations. Returns \c true
8163 /// if we have found that this is a redeclaration of some prior entity.
8164 ///
8165 /// Per C++ [dcl.link]p6:
8166 ///   Two declarations [for a function or variable] with C language linkage
8167 ///   with the same name that appear in different scopes refer to the same
8168 ///   [entity]. An entity with C language linkage shall not be declared with
8169 ///   the same name as an entity in global scope.
8170 template<typename T>
8171 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8172                                                   LookupResult &Previous) {
8173   if (!S.getLangOpts().CPlusPlus) {
8174     // In C, when declaring a global variable, look for a corresponding 'extern'
8175     // variable declared in function scope. We don't need this in C++, because
8176     // we find local extern decls in the surrounding file-scope DeclContext.
8177     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8178       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8179         Previous.clear();
8180         Previous.addDecl(Prev);
8181         return true;
8182       }
8183     }
8184     return false;
8185   }
8186 
8187   // A declaration in the translation unit can conflict with an extern "C"
8188   // declaration.
8189   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8190     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8191 
8192   // An extern "C" declaration can conflict with a declaration in the
8193   // translation unit or can be a redeclaration of an extern "C" declaration
8194   // in another scope.
8195   if (isIncompleteDeclExternC(S,ND))
8196     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8197 
8198   // Neither global nor extern "C": nothing to do.
8199   return false;
8200 }
8201 
8202 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8203   // If the decl is already known invalid, don't check it.
8204   if (NewVD->isInvalidDecl())
8205     return;
8206 
8207   QualType T = NewVD->getType();
8208 
8209   // Defer checking an 'auto' type until its initializer is attached.
8210   if (T->isUndeducedType())
8211     return;
8212 
8213   if (NewVD->hasAttrs())
8214     CheckAlignasUnderalignment(NewVD);
8215 
8216   if (T->isObjCObjectType()) {
8217     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8218       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8219     T = Context.getObjCObjectPointerType(T);
8220     NewVD->setType(T);
8221   }
8222 
8223   // Emit an error if an address space was applied to decl with local storage.
8224   // This includes arrays of objects with address space qualifiers, but not
8225   // automatic variables that point to other address spaces.
8226   // ISO/IEC TR 18037 S5.1.2
8227   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8228       T.getAddressSpace() != LangAS::Default) {
8229     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8230     NewVD->setInvalidDecl();
8231     return;
8232   }
8233 
8234   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8235   // scope.
8236   if (getLangOpts().OpenCLVersion == 120 &&
8237       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8238                                             getLangOpts()) &&
8239       NewVD->isStaticLocal()) {
8240     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8241     NewVD->setInvalidDecl();
8242     return;
8243   }
8244 
8245   if (getLangOpts().OpenCL) {
8246     if (!diagnoseOpenCLTypes(*this, NewVD))
8247       return;
8248 
8249     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8250     if (NewVD->hasAttr<BlocksAttr>()) {
8251       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8252       return;
8253     }
8254 
8255     if (T->isBlockPointerType()) {
8256       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8257       // can't use 'extern' storage class.
8258       if (!T.isConstQualified()) {
8259         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8260             << 0 /*const*/;
8261         NewVD->setInvalidDecl();
8262         return;
8263       }
8264       if (NewVD->hasExternalStorage()) {
8265         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8266         NewVD->setInvalidDecl();
8267         return;
8268       }
8269     }
8270 
8271     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8272     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8273         NewVD->hasExternalStorage()) {
8274       if (!T->isSamplerT() && !T->isDependentType() &&
8275           !(T.getAddressSpace() == LangAS::opencl_constant ||
8276             (T.getAddressSpace() == LangAS::opencl_global &&
8277              getOpenCLOptions().areProgramScopeVariablesSupported(
8278                  getLangOpts())))) {
8279         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8280         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8281           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8282               << Scope << "global or constant";
8283         else
8284           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8285               << Scope << "constant";
8286         NewVD->setInvalidDecl();
8287         return;
8288       }
8289     } else {
8290       if (T.getAddressSpace() == LangAS::opencl_global) {
8291         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8292             << 1 /*is any function*/ << "global";
8293         NewVD->setInvalidDecl();
8294         return;
8295       }
8296       if (T.getAddressSpace() == LangAS::opencl_constant ||
8297           T.getAddressSpace() == LangAS::opencl_local) {
8298         FunctionDecl *FD = getCurFunctionDecl();
8299         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8300         // in functions.
8301         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8302           if (T.getAddressSpace() == LangAS::opencl_constant)
8303             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8304                 << 0 /*non-kernel only*/ << "constant";
8305           else
8306             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8307                 << 0 /*non-kernel only*/ << "local";
8308           NewVD->setInvalidDecl();
8309           return;
8310         }
8311         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8312         // in the outermost scope of a kernel function.
8313         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8314           if (!getCurScope()->isFunctionScope()) {
8315             if (T.getAddressSpace() == LangAS::opencl_constant)
8316               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8317                   << "constant";
8318             else
8319               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8320                   << "local";
8321             NewVD->setInvalidDecl();
8322             return;
8323           }
8324         }
8325       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8326                  // If we are parsing a template we didn't deduce an addr
8327                  // space yet.
8328                  T.getAddressSpace() != LangAS::Default) {
8329         // Do not allow other address spaces on automatic variable.
8330         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8331         NewVD->setInvalidDecl();
8332         return;
8333       }
8334     }
8335   }
8336 
8337   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8338       && !NewVD->hasAttr<BlocksAttr>()) {
8339     if (getLangOpts().getGC() != LangOptions::NonGC)
8340       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8341     else {
8342       assert(!getLangOpts().ObjCAutoRefCount);
8343       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8344     }
8345   }
8346 
8347   bool isVM = T->isVariablyModifiedType();
8348   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8349       NewVD->hasAttr<BlocksAttr>())
8350     setFunctionHasBranchProtectedScope();
8351 
8352   if ((isVM && NewVD->hasLinkage()) ||
8353       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8354     bool SizeIsNegative;
8355     llvm::APSInt Oversized;
8356     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8357         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8358     QualType FixedT;
8359     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8360       FixedT = FixedTInfo->getType();
8361     else if (FixedTInfo) {
8362       // Type and type-as-written are canonically different. We need to fix up
8363       // both types separately.
8364       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8365                                                    Oversized);
8366     }
8367     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8368       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8369       // FIXME: This won't give the correct result for
8370       // int a[10][n];
8371       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8372 
8373       if (NewVD->isFileVarDecl())
8374         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8375         << SizeRange;
8376       else if (NewVD->isStaticLocal())
8377         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8378         << SizeRange;
8379       else
8380         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8381         << SizeRange;
8382       NewVD->setInvalidDecl();
8383       return;
8384     }
8385 
8386     if (!FixedTInfo) {
8387       if (NewVD->isFileVarDecl())
8388         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8389       else
8390         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8391       NewVD->setInvalidDecl();
8392       return;
8393     }
8394 
8395     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8396     NewVD->setType(FixedT);
8397     NewVD->setTypeSourceInfo(FixedTInfo);
8398   }
8399 
8400   if (T->isVoidType()) {
8401     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8402     //                    of objects and functions.
8403     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8404       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8405         << T;
8406       NewVD->setInvalidDecl();
8407       return;
8408     }
8409   }
8410 
8411   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8412     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8413     NewVD->setInvalidDecl();
8414     return;
8415   }
8416 
8417   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8418     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8419     NewVD->setInvalidDecl();
8420     return;
8421   }
8422 
8423   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8424     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8425     NewVD->setInvalidDecl();
8426     return;
8427   }
8428 
8429   if (NewVD->isConstexpr() && !T->isDependentType() &&
8430       RequireLiteralType(NewVD->getLocation(), T,
8431                          diag::err_constexpr_var_non_literal)) {
8432     NewVD->setInvalidDecl();
8433     return;
8434   }
8435 
8436   // PPC MMA non-pointer types are not allowed as non-local variable types.
8437   if (Context.getTargetInfo().getTriple().isPPC64() &&
8438       !NewVD->isLocalVarDecl() &&
8439       CheckPPCMMAType(T, NewVD->getLocation())) {
8440     NewVD->setInvalidDecl();
8441     return;
8442   }
8443 }
8444 
8445 /// Perform semantic checking on a newly-created variable
8446 /// declaration.
8447 ///
8448 /// This routine performs all of the type-checking required for a
8449 /// variable declaration once it has been built. It is used both to
8450 /// check variables after they have been parsed and their declarators
8451 /// have been translated into a declaration, and to check variables
8452 /// that have been instantiated from a template.
8453 ///
8454 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8455 ///
8456 /// Returns true if the variable declaration is a redeclaration.
8457 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8458   CheckVariableDeclarationType(NewVD);
8459 
8460   // If the decl is already known invalid, don't check it.
8461   if (NewVD->isInvalidDecl())
8462     return false;
8463 
8464   // If we did not find anything by this name, look for a non-visible
8465   // extern "C" declaration with the same name.
8466   if (Previous.empty() &&
8467       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8468     Previous.setShadowed();
8469 
8470   if (!Previous.empty()) {
8471     MergeVarDecl(NewVD, Previous);
8472     return true;
8473   }
8474   return false;
8475 }
8476 
8477 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8478 /// and if so, check that it's a valid override and remember it.
8479 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8480   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8481 
8482   // Look for methods in base classes that this method might override.
8483   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8484                      /*DetectVirtual=*/false);
8485   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8486     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8487     DeclarationName Name = MD->getDeclName();
8488 
8489     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8490       // We really want to find the base class destructor here.
8491       QualType T = Context.getTypeDeclType(BaseRecord);
8492       CanQualType CT = Context.getCanonicalType(T);
8493       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8494     }
8495 
8496     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8497       CXXMethodDecl *BaseMD =
8498           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8499       if (!BaseMD || !BaseMD->isVirtual() ||
8500           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8501                      /*ConsiderCudaAttrs=*/true,
8502                      // C++2a [class.virtual]p2 does not consider requires
8503                      // clauses when overriding.
8504                      /*ConsiderRequiresClauses=*/false))
8505         continue;
8506 
8507       if (Overridden.insert(BaseMD).second) {
8508         MD->addOverriddenMethod(BaseMD);
8509         CheckOverridingFunctionReturnType(MD, BaseMD);
8510         CheckOverridingFunctionAttributes(MD, BaseMD);
8511         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8512         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8513       }
8514 
8515       // A method can only override one function from each base class. We
8516       // don't track indirectly overridden methods from bases of bases.
8517       return true;
8518     }
8519 
8520     return false;
8521   };
8522 
8523   DC->lookupInBases(VisitBase, Paths);
8524   return !Overridden.empty();
8525 }
8526 
8527 namespace {
8528   // Struct for holding all of the extra arguments needed by
8529   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8530   struct ActOnFDArgs {
8531     Scope *S;
8532     Declarator &D;
8533     MultiTemplateParamsArg TemplateParamLists;
8534     bool AddToScope;
8535   };
8536 } // end anonymous namespace
8537 
8538 namespace {
8539 
8540 // Callback to only accept typo corrections that have a non-zero edit distance.
8541 // Also only accept corrections that have the same parent decl.
8542 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8543  public:
8544   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8545                             CXXRecordDecl *Parent)
8546       : Context(Context), OriginalFD(TypoFD),
8547         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8548 
8549   bool ValidateCandidate(const TypoCorrection &candidate) override {
8550     if (candidate.getEditDistance() == 0)
8551       return false;
8552 
8553     SmallVector<unsigned, 1> MismatchedParams;
8554     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8555                                           CDeclEnd = candidate.end();
8556          CDecl != CDeclEnd; ++CDecl) {
8557       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8558 
8559       if (FD && !FD->hasBody() &&
8560           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8561         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8562           CXXRecordDecl *Parent = MD->getParent();
8563           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8564             return true;
8565         } else if (!ExpectedParent) {
8566           return true;
8567         }
8568       }
8569     }
8570 
8571     return false;
8572   }
8573 
8574   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8575     return std::make_unique<DifferentNameValidatorCCC>(*this);
8576   }
8577 
8578  private:
8579   ASTContext &Context;
8580   FunctionDecl *OriginalFD;
8581   CXXRecordDecl *ExpectedParent;
8582 };
8583 
8584 } // end anonymous namespace
8585 
8586 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8587   TypoCorrectedFunctionDefinitions.insert(F);
8588 }
8589 
8590 /// Generate diagnostics for an invalid function redeclaration.
8591 ///
8592 /// This routine handles generating the diagnostic messages for an invalid
8593 /// function redeclaration, including finding possible similar declarations
8594 /// or performing typo correction if there are no previous declarations with
8595 /// the same name.
8596 ///
8597 /// Returns a NamedDecl iff typo correction was performed and substituting in
8598 /// the new declaration name does not cause new errors.
8599 static NamedDecl *DiagnoseInvalidRedeclaration(
8600     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8601     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8602   DeclarationName Name = NewFD->getDeclName();
8603   DeclContext *NewDC = NewFD->getDeclContext();
8604   SmallVector<unsigned, 1> MismatchedParams;
8605   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8606   TypoCorrection Correction;
8607   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8608   unsigned DiagMsg =
8609     IsLocalFriend ? diag::err_no_matching_local_friend :
8610     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8611     diag::err_member_decl_does_not_match;
8612   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8613                     IsLocalFriend ? Sema::LookupLocalFriendName
8614                                   : Sema::LookupOrdinaryName,
8615                     Sema::ForVisibleRedeclaration);
8616 
8617   NewFD->setInvalidDecl();
8618   if (IsLocalFriend)
8619     SemaRef.LookupName(Prev, S);
8620   else
8621     SemaRef.LookupQualifiedName(Prev, NewDC);
8622   assert(!Prev.isAmbiguous() &&
8623          "Cannot have an ambiguity in previous-declaration lookup");
8624   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8625   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8626                                 MD ? MD->getParent() : nullptr);
8627   if (!Prev.empty()) {
8628     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8629          Func != FuncEnd; ++Func) {
8630       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8631       if (FD &&
8632           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8633         // Add 1 to the index so that 0 can mean the mismatch didn't
8634         // involve a parameter
8635         unsigned ParamNum =
8636             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8637         NearMatches.push_back(std::make_pair(FD, ParamNum));
8638       }
8639     }
8640   // If the qualified name lookup yielded nothing, try typo correction
8641   } else if ((Correction = SemaRef.CorrectTypo(
8642                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8643                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8644                   IsLocalFriend ? nullptr : NewDC))) {
8645     // Set up everything for the call to ActOnFunctionDeclarator
8646     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8647                               ExtraArgs.D.getIdentifierLoc());
8648     Previous.clear();
8649     Previous.setLookupName(Correction.getCorrection());
8650     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8651                                     CDeclEnd = Correction.end();
8652          CDecl != CDeclEnd; ++CDecl) {
8653       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8654       if (FD && !FD->hasBody() &&
8655           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8656         Previous.addDecl(FD);
8657       }
8658     }
8659     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8660 
8661     NamedDecl *Result;
8662     // Retry building the function declaration with the new previous
8663     // declarations, and with errors suppressed.
8664     {
8665       // Trap errors.
8666       Sema::SFINAETrap Trap(SemaRef);
8667 
8668       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8669       // pieces need to verify the typo-corrected C++ declaration and hopefully
8670       // eliminate the need for the parameter pack ExtraArgs.
8671       Result = SemaRef.ActOnFunctionDeclarator(
8672           ExtraArgs.S, ExtraArgs.D,
8673           Correction.getCorrectionDecl()->getDeclContext(),
8674           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8675           ExtraArgs.AddToScope);
8676 
8677       if (Trap.hasErrorOccurred())
8678         Result = nullptr;
8679     }
8680 
8681     if (Result) {
8682       // Determine which correction we picked.
8683       Decl *Canonical = Result->getCanonicalDecl();
8684       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8685            I != E; ++I)
8686         if ((*I)->getCanonicalDecl() == Canonical)
8687           Correction.setCorrectionDecl(*I);
8688 
8689       // Let Sema know about the correction.
8690       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8691       SemaRef.diagnoseTypo(
8692           Correction,
8693           SemaRef.PDiag(IsLocalFriend
8694                           ? diag::err_no_matching_local_friend_suggest
8695                           : diag::err_member_decl_does_not_match_suggest)
8696             << Name << NewDC << IsDefinition);
8697       return Result;
8698     }
8699 
8700     // Pretend the typo correction never occurred
8701     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8702                               ExtraArgs.D.getIdentifierLoc());
8703     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8704     Previous.clear();
8705     Previous.setLookupName(Name);
8706   }
8707 
8708   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8709       << Name << NewDC << IsDefinition << NewFD->getLocation();
8710 
8711   bool NewFDisConst = false;
8712   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8713     NewFDisConst = NewMD->isConst();
8714 
8715   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8716        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8717        NearMatch != NearMatchEnd; ++NearMatch) {
8718     FunctionDecl *FD = NearMatch->first;
8719     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8720     bool FDisConst = MD && MD->isConst();
8721     bool IsMember = MD || !IsLocalFriend;
8722 
8723     // FIXME: These notes are poorly worded for the local friend case.
8724     if (unsigned Idx = NearMatch->second) {
8725       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8726       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8727       if (Loc.isInvalid()) Loc = FD->getLocation();
8728       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8729                                  : diag::note_local_decl_close_param_match)
8730         << Idx << FDParam->getType()
8731         << NewFD->getParamDecl(Idx - 1)->getType();
8732     } else if (FDisConst != NewFDisConst) {
8733       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8734           << NewFDisConst << FD->getSourceRange().getEnd()
8735           << (NewFDisConst
8736                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8737                                                  .getConstQualifierLoc())
8738                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8739                                                    .getRParenLoc()
8740                                                    .getLocWithOffset(1),
8741                                                " const"));
8742     } else
8743       SemaRef.Diag(FD->getLocation(),
8744                    IsMember ? diag::note_member_def_close_match
8745                             : diag::note_local_decl_close_match);
8746   }
8747   return nullptr;
8748 }
8749 
8750 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8751   switch (D.getDeclSpec().getStorageClassSpec()) {
8752   default: llvm_unreachable("Unknown storage class!");
8753   case DeclSpec::SCS_auto:
8754   case DeclSpec::SCS_register:
8755   case DeclSpec::SCS_mutable:
8756     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8757                  diag::err_typecheck_sclass_func);
8758     D.getMutableDeclSpec().ClearStorageClassSpecs();
8759     D.setInvalidType();
8760     break;
8761   case DeclSpec::SCS_unspecified: break;
8762   case DeclSpec::SCS_extern:
8763     if (D.getDeclSpec().isExternInLinkageSpec())
8764       return SC_None;
8765     return SC_Extern;
8766   case DeclSpec::SCS_static: {
8767     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8768       // C99 6.7.1p5:
8769       //   The declaration of an identifier for a function that has
8770       //   block scope shall have no explicit storage-class specifier
8771       //   other than extern
8772       // See also (C++ [dcl.stc]p4).
8773       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8774                    diag::err_static_block_func);
8775       break;
8776     } else
8777       return SC_Static;
8778   }
8779   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8780   }
8781 
8782   // No explicit storage class has already been returned
8783   return SC_None;
8784 }
8785 
8786 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8787                                            DeclContext *DC, QualType &R,
8788                                            TypeSourceInfo *TInfo,
8789                                            StorageClass SC,
8790                                            bool &IsVirtualOkay) {
8791   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8792   DeclarationName Name = NameInfo.getName();
8793 
8794   FunctionDecl *NewFD = nullptr;
8795   bool isInline = D.getDeclSpec().isInlineSpecified();
8796 
8797   if (!SemaRef.getLangOpts().CPlusPlus) {
8798     // Determine whether the function was written with a prototype. This is
8799     // true when:
8800     //   - there is a prototype in the declarator, or
8801     //   - the type R of the function is some kind of typedef or other non-
8802     //     attributed reference to a type name (which eventually refers to a
8803     //     function type). Note, we can't always look at the adjusted type to
8804     //     check this case because attributes may cause a non-function
8805     //     declarator to still have a function type. e.g.,
8806     //       typedef void func(int a);
8807     //       __attribute__((noreturn)) func other_func; // This has a prototype
8808     bool HasPrototype =
8809         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8810         (D.getDeclSpec().isTypeRep() &&
8811          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8812         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8813     assert(
8814         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8815         "Strict prototypes are required");
8816 
8817     NewFD = FunctionDecl::Create(
8818         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8819         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8820         ConstexprSpecKind::Unspecified,
8821         /*TrailingRequiresClause=*/nullptr);
8822     if (D.isInvalidType())
8823       NewFD->setInvalidDecl();
8824 
8825     return NewFD;
8826   }
8827 
8828   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8829 
8830   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8831   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8832     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8833                  diag::err_constexpr_wrong_decl_kind)
8834         << static_cast<int>(ConstexprKind);
8835     ConstexprKind = ConstexprSpecKind::Unspecified;
8836     D.getMutableDeclSpec().ClearConstexprSpec();
8837   }
8838   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8839 
8840   // Check that the return type is not an abstract class type.
8841   // For record types, this is done by the AbstractClassUsageDiagnoser once
8842   // the class has been completely parsed.
8843   if (!DC->isRecord() &&
8844       SemaRef.RequireNonAbstractType(
8845           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8846           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8847     D.setInvalidType();
8848 
8849   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8850     // This is a C++ constructor declaration.
8851     assert(DC->isRecord() &&
8852            "Constructors can only be declared in a member context");
8853 
8854     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8855     return CXXConstructorDecl::Create(
8856         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8857         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8858         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8859         InheritedConstructor(), TrailingRequiresClause);
8860 
8861   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8862     // This is a C++ destructor declaration.
8863     if (DC->isRecord()) {
8864       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8865       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8866       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8867           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8868           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8869           /*isImplicitlyDeclared=*/false, ConstexprKind,
8870           TrailingRequiresClause);
8871       // User defined destructors start as not selected if the class definition is still
8872       // not done.
8873       if (Record->isBeingDefined())
8874         NewDD->setIneligibleOrNotSelected(true);
8875 
8876       // If the destructor needs an implicit exception specification, set it
8877       // now. FIXME: It'd be nice to be able to create the right type to start
8878       // with, but the type needs to reference the destructor declaration.
8879       if (SemaRef.getLangOpts().CPlusPlus11)
8880         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8881 
8882       IsVirtualOkay = true;
8883       return NewDD;
8884 
8885     } else {
8886       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8887       D.setInvalidType();
8888 
8889       // Create a FunctionDecl to satisfy the function definition parsing
8890       // code path.
8891       return FunctionDecl::Create(
8892           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8893           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8894           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8895     }
8896 
8897   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8898     if (!DC->isRecord()) {
8899       SemaRef.Diag(D.getIdentifierLoc(),
8900            diag::err_conv_function_not_member);
8901       return nullptr;
8902     }
8903 
8904     SemaRef.CheckConversionDeclarator(D, R, SC);
8905     if (D.isInvalidType())
8906       return nullptr;
8907 
8908     IsVirtualOkay = true;
8909     return CXXConversionDecl::Create(
8910         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8911         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8912         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8913         TrailingRequiresClause);
8914 
8915   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8916     if (TrailingRequiresClause)
8917       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8918                    diag::err_trailing_requires_clause_on_deduction_guide)
8919           << TrailingRequiresClause->getSourceRange();
8920     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8921 
8922     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8923                                          ExplicitSpecifier, NameInfo, R, TInfo,
8924                                          D.getEndLoc());
8925   } else if (DC->isRecord()) {
8926     // If the name of the function is the same as the name of the record,
8927     // then this must be an invalid constructor that has a return type.
8928     // (The parser checks for a return type and makes the declarator a
8929     // constructor if it has no return type).
8930     if (Name.getAsIdentifierInfo() &&
8931         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8932       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8933         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8934         << SourceRange(D.getIdentifierLoc());
8935       return nullptr;
8936     }
8937 
8938     // This is a C++ method declaration.
8939     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8940         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8941         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8942         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8943     IsVirtualOkay = !Ret->isStatic();
8944     return Ret;
8945   } else {
8946     bool isFriend =
8947         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8948     if (!isFriend && SemaRef.CurContext->isRecord())
8949       return nullptr;
8950 
8951     // Determine whether the function was written with a
8952     // prototype. This true when:
8953     //   - we're in C++ (where every function has a prototype),
8954     return FunctionDecl::Create(
8955         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8956         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8957         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8958   }
8959 }
8960 
8961 enum OpenCLParamType {
8962   ValidKernelParam,
8963   PtrPtrKernelParam,
8964   PtrKernelParam,
8965   InvalidAddrSpacePtrKernelParam,
8966   InvalidKernelParam,
8967   RecordKernelParam
8968 };
8969 
8970 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8971   // Size dependent types are just typedefs to normal integer types
8972   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8973   // integers other than by their names.
8974   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8975 
8976   // Remove typedefs one by one until we reach a typedef
8977   // for a size dependent type.
8978   QualType DesugaredTy = Ty;
8979   do {
8980     ArrayRef<StringRef> Names(SizeTypeNames);
8981     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8982     if (Names.end() != Match)
8983       return true;
8984 
8985     Ty = DesugaredTy;
8986     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8987   } while (DesugaredTy != Ty);
8988 
8989   return false;
8990 }
8991 
8992 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8993   if (PT->isDependentType())
8994     return InvalidKernelParam;
8995 
8996   if (PT->isPointerType() || PT->isReferenceType()) {
8997     QualType PointeeType = PT->getPointeeType();
8998     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8999         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9000         PointeeType.getAddressSpace() == LangAS::Default)
9001       return InvalidAddrSpacePtrKernelParam;
9002 
9003     if (PointeeType->isPointerType()) {
9004       // This is a pointer to pointer parameter.
9005       // Recursively check inner type.
9006       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9007       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9008           ParamKind == InvalidKernelParam)
9009         return ParamKind;
9010 
9011       return PtrPtrKernelParam;
9012     }
9013 
9014     // C++ for OpenCL v1.0 s2.4:
9015     // Moreover the types used in parameters of the kernel functions must be:
9016     // Standard layout types for pointer parameters. The same applies to
9017     // reference if an implementation supports them in kernel parameters.
9018     if (S.getLangOpts().OpenCLCPlusPlus &&
9019         !S.getOpenCLOptions().isAvailableOption(
9020             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9021         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9022         !PointeeType->isStandardLayoutType())
9023       return InvalidKernelParam;
9024 
9025     return PtrKernelParam;
9026   }
9027 
9028   // OpenCL v1.2 s6.9.k:
9029   // Arguments to kernel functions in a program cannot be declared with the
9030   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9031   // uintptr_t or a struct and/or union that contain fields declared to be one
9032   // of these built-in scalar types.
9033   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9034     return InvalidKernelParam;
9035 
9036   if (PT->isImageType())
9037     return PtrKernelParam;
9038 
9039   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9040     return InvalidKernelParam;
9041 
9042   // OpenCL extension spec v1.2 s9.5:
9043   // This extension adds support for half scalar and vector types as built-in
9044   // types that can be used for arithmetic operations, conversions etc.
9045   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9046       PT->isHalfType())
9047     return InvalidKernelParam;
9048 
9049   // Look into an array argument to check if it has a forbidden type.
9050   if (PT->isArrayType()) {
9051     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9052     // Call ourself to check an underlying type of an array. Since the
9053     // getPointeeOrArrayElementType returns an innermost type which is not an
9054     // array, this recursive call only happens once.
9055     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9056   }
9057 
9058   // C++ for OpenCL v1.0 s2.4:
9059   // Moreover the types used in parameters of the kernel functions must be:
9060   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9061   // types) for parameters passed by value;
9062   if (S.getLangOpts().OpenCLCPlusPlus &&
9063       !S.getOpenCLOptions().isAvailableOption(
9064           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9065       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9066     return InvalidKernelParam;
9067 
9068   if (PT->isRecordType())
9069     return RecordKernelParam;
9070 
9071   return ValidKernelParam;
9072 }
9073 
9074 static void checkIsValidOpenCLKernelParameter(
9075   Sema &S,
9076   Declarator &D,
9077   ParmVarDecl *Param,
9078   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9079   QualType PT = Param->getType();
9080 
9081   // Cache the valid types we encounter to avoid rechecking structs that are
9082   // used again
9083   if (ValidTypes.count(PT.getTypePtr()))
9084     return;
9085 
9086   switch (getOpenCLKernelParameterType(S, PT)) {
9087   case PtrPtrKernelParam:
9088     // OpenCL v3.0 s6.11.a:
9089     // A kernel function argument cannot be declared as a pointer to a pointer
9090     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9091     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9092       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9093       D.setInvalidType();
9094       return;
9095     }
9096 
9097     ValidTypes.insert(PT.getTypePtr());
9098     return;
9099 
9100   case InvalidAddrSpacePtrKernelParam:
9101     // OpenCL v1.0 s6.5:
9102     // __kernel function arguments declared to be a pointer of a type can point
9103     // to one of the following address spaces only : __global, __local or
9104     // __constant.
9105     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9106     D.setInvalidType();
9107     return;
9108 
9109     // OpenCL v1.2 s6.9.k:
9110     // Arguments to kernel functions in a program cannot be declared with the
9111     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9112     // uintptr_t or a struct and/or union that contain fields declared to be
9113     // one of these built-in scalar types.
9114 
9115   case InvalidKernelParam:
9116     // OpenCL v1.2 s6.8 n:
9117     // A kernel function argument cannot be declared
9118     // of event_t type.
9119     // Do not diagnose half type since it is diagnosed as invalid argument
9120     // type for any function elsewhere.
9121     if (!PT->isHalfType()) {
9122       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9123 
9124       // Explain what typedefs are involved.
9125       const TypedefType *Typedef = nullptr;
9126       while ((Typedef = PT->getAs<TypedefType>())) {
9127         SourceLocation Loc = Typedef->getDecl()->getLocation();
9128         // SourceLocation may be invalid for a built-in type.
9129         if (Loc.isValid())
9130           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9131         PT = Typedef->desugar();
9132       }
9133     }
9134 
9135     D.setInvalidType();
9136     return;
9137 
9138   case PtrKernelParam:
9139   case ValidKernelParam:
9140     ValidTypes.insert(PT.getTypePtr());
9141     return;
9142 
9143   case RecordKernelParam:
9144     break;
9145   }
9146 
9147   // Track nested structs we will inspect
9148   SmallVector<const Decl *, 4> VisitStack;
9149 
9150   // Track where we are in the nested structs. Items will migrate from
9151   // VisitStack to HistoryStack as we do the DFS for bad field.
9152   SmallVector<const FieldDecl *, 4> HistoryStack;
9153   HistoryStack.push_back(nullptr);
9154 
9155   // At this point we already handled everything except of a RecordType or
9156   // an ArrayType of a RecordType.
9157   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9158   const RecordType *RecTy =
9159       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9160   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9161 
9162   VisitStack.push_back(RecTy->getDecl());
9163   assert(VisitStack.back() && "First decl null?");
9164 
9165   do {
9166     const Decl *Next = VisitStack.pop_back_val();
9167     if (!Next) {
9168       assert(!HistoryStack.empty());
9169       // Found a marker, we have gone up a level
9170       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9171         ValidTypes.insert(Hist->getType().getTypePtr());
9172 
9173       continue;
9174     }
9175 
9176     // Adds everything except the original parameter declaration (which is not a
9177     // field itself) to the history stack.
9178     const RecordDecl *RD;
9179     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9180       HistoryStack.push_back(Field);
9181 
9182       QualType FieldTy = Field->getType();
9183       // Other field types (known to be valid or invalid) are handled while we
9184       // walk around RecordDecl::fields().
9185       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9186              "Unexpected type.");
9187       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9188 
9189       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9190     } else {
9191       RD = cast<RecordDecl>(Next);
9192     }
9193 
9194     // Add a null marker so we know when we've gone back up a level
9195     VisitStack.push_back(nullptr);
9196 
9197     for (const auto *FD : RD->fields()) {
9198       QualType QT = FD->getType();
9199 
9200       if (ValidTypes.count(QT.getTypePtr()))
9201         continue;
9202 
9203       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9204       if (ParamType == ValidKernelParam)
9205         continue;
9206 
9207       if (ParamType == RecordKernelParam) {
9208         VisitStack.push_back(FD);
9209         continue;
9210       }
9211 
9212       // OpenCL v1.2 s6.9.p:
9213       // Arguments to kernel functions that are declared to be a struct or union
9214       // do not allow OpenCL objects to be passed as elements of the struct or
9215       // union.
9216       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9217           ParamType == InvalidAddrSpacePtrKernelParam) {
9218         S.Diag(Param->getLocation(),
9219                diag::err_record_with_pointers_kernel_param)
9220           << PT->isUnionType()
9221           << PT;
9222       } else {
9223         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9224       }
9225 
9226       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9227           << OrigRecDecl->getDeclName();
9228 
9229       // We have an error, now let's go back up through history and show where
9230       // the offending field came from
9231       for (ArrayRef<const FieldDecl *>::const_iterator
9232                I = HistoryStack.begin() + 1,
9233                E = HistoryStack.end();
9234            I != E; ++I) {
9235         const FieldDecl *OuterField = *I;
9236         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9237           << OuterField->getType();
9238       }
9239 
9240       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9241         << QT->isPointerType()
9242         << QT;
9243       D.setInvalidType();
9244       return;
9245     }
9246   } while (!VisitStack.empty());
9247 }
9248 
9249 /// Find the DeclContext in which a tag is implicitly declared if we see an
9250 /// elaborated type specifier in the specified context, and lookup finds
9251 /// nothing.
9252 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9253   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9254     DC = DC->getParent();
9255   return DC;
9256 }
9257 
9258 /// Find the Scope in which a tag is implicitly declared if we see an
9259 /// elaborated type specifier in the specified context, and lookup finds
9260 /// nothing.
9261 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9262   while (S->isClassScope() ||
9263          (LangOpts.CPlusPlus &&
9264           S->isFunctionPrototypeScope()) ||
9265          ((S->getFlags() & Scope::DeclScope) == 0) ||
9266          (S->getEntity() && S->getEntity()->isTransparentContext()))
9267     S = S->getParent();
9268   return S;
9269 }
9270 
9271 /// Determine whether a declaration matches a known function in namespace std.
9272 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9273                          unsigned BuiltinID) {
9274   switch (BuiltinID) {
9275   case Builtin::BI__GetExceptionInfo:
9276     // No type checking whatsoever.
9277     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9278 
9279   case Builtin::BIaddressof:
9280   case Builtin::BI__addressof:
9281   case Builtin::BIforward:
9282   case Builtin::BImove:
9283   case Builtin::BImove_if_noexcept:
9284   case Builtin::BIas_const: {
9285     // Ensure that we don't treat the algorithm
9286     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9287     // as the builtin std::move.
9288     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9289     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9290   }
9291 
9292   default:
9293     return false;
9294   }
9295 }
9296 
9297 NamedDecl*
9298 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9299                               TypeSourceInfo *TInfo, LookupResult &Previous,
9300                               MultiTemplateParamsArg TemplateParamListsRef,
9301                               bool &AddToScope) {
9302   QualType R = TInfo->getType();
9303 
9304   assert(R->isFunctionType());
9305   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9306     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9307 
9308   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9309   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9310   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9311     if (!TemplateParamLists.empty() &&
9312         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9313       TemplateParamLists.back() = Invented;
9314     else
9315       TemplateParamLists.push_back(Invented);
9316   }
9317 
9318   // TODO: consider using NameInfo for diagnostic.
9319   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9320   DeclarationName Name = NameInfo.getName();
9321   StorageClass SC = getFunctionStorageClass(*this, D);
9322 
9323   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9324     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9325          diag::err_invalid_thread)
9326       << DeclSpec::getSpecifierName(TSCS);
9327 
9328   if (D.isFirstDeclarationOfMember())
9329     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9330                            D.getIdentifierLoc());
9331 
9332   bool isFriend = false;
9333   FunctionTemplateDecl *FunctionTemplate = nullptr;
9334   bool isMemberSpecialization = false;
9335   bool isFunctionTemplateSpecialization = false;
9336 
9337   bool isDependentClassScopeExplicitSpecialization = false;
9338   bool HasExplicitTemplateArgs = false;
9339   TemplateArgumentListInfo TemplateArgs;
9340 
9341   bool isVirtualOkay = false;
9342 
9343   DeclContext *OriginalDC = DC;
9344   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9345 
9346   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9347                                               isVirtualOkay);
9348   if (!NewFD) return nullptr;
9349 
9350   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9351     NewFD->setTopLevelDeclInObjCContainer();
9352 
9353   // Set the lexical context. If this is a function-scope declaration, or has a
9354   // C++ scope specifier, or is the object of a friend declaration, the lexical
9355   // context will be different from the semantic context.
9356   NewFD->setLexicalDeclContext(CurContext);
9357 
9358   if (IsLocalExternDecl)
9359     NewFD->setLocalExternDecl();
9360 
9361   if (getLangOpts().CPlusPlus) {
9362     bool isInline = D.getDeclSpec().isInlineSpecified();
9363     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9364     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9365     isFriend = D.getDeclSpec().isFriendSpecified();
9366     if (isFriend && !isInline && D.isFunctionDefinition()) {
9367       // C++ [class.friend]p5
9368       //   A function can be defined in a friend declaration of a
9369       //   class . . . . Such a function is implicitly inline.
9370       NewFD->setImplicitlyInline();
9371     }
9372 
9373     // If this is a method defined in an __interface, and is not a constructor
9374     // or an overloaded operator, then set the pure flag (isVirtual will already
9375     // return true).
9376     if (const CXXRecordDecl *Parent =
9377           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9378       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9379         NewFD->setPure(true);
9380 
9381       // C++ [class.union]p2
9382       //   A union can have member functions, but not virtual functions.
9383       if (isVirtual && Parent->isUnion()) {
9384         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9385         NewFD->setInvalidDecl();
9386       }
9387       if ((Parent->isClass() || Parent->isStruct()) &&
9388           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9389           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9390           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9391         if (auto *Def = Parent->getDefinition())
9392           Def->setInitMethod(true);
9393       }
9394     }
9395 
9396     SetNestedNameSpecifier(*this, NewFD, D);
9397     isMemberSpecialization = false;
9398     isFunctionTemplateSpecialization = false;
9399     if (D.isInvalidType())
9400       NewFD->setInvalidDecl();
9401 
9402     // Match up the template parameter lists with the scope specifier, then
9403     // determine whether we have a template or a template specialization.
9404     bool Invalid = false;
9405     TemplateParameterList *TemplateParams =
9406         MatchTemplateParametersToScopeSpecifier(
9407             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9408             D.getCXXScopeSpec(),
9409             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9410                 ? D.getName().TemplateId
9411                 : nullptr,
9412             TemplateParamLists, isFriend, isMemberSpecialization,
9413             Invalid);
9414     if (TemplateParams) {
9415       // Check that we can declare a template here.
9416       if (CheckTemplateDeclScope(S, TemplateParams))
9417         NewFD->setInvalidDecl();
9418 
9419       if (TemplateParams->size() > 0) {
9420         // This is a function template
9421 
9422         // A destructor cannot be a template.
9423         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9424           Diag(NewFD->getLocation(), diag::err_destructor_template);
9425           NewFD->setInvalidDecl();
9426         }
9427 
9428         // If we're adding a template to a dependent context, we may need to
9429         // rebuilding some of the types used within the template parameter list,
9430         // now that we know what the current instantiation is.
9431         if (DC->isDependentContext()) {
9432           ContextRAII SavedContext(*this, DC);
9433           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9434             Invalid = true;
9435         }
9436 
9437         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9438                                                         NewFD->getLocation(),
9439                                                         Name, TemplateParams,
9440                                                         NewFD);
9441         FunctionTemplate->setLexicalDeclContext(CurContext);
9442         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9443 
9444         // For source fidelity, store the other template param lists.
9445         if (TemplateParamLists.size() > 1) {
9446           NewFD->setTemplateParameterListsInfo(Context,
9447               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9448                   .drop_back(1));
9449         }
9450       } else {
9451         // This is a function template specialization.
9452         isFunctionTemplateSpecialization = true;
9453         // For source fidelity, store all the template param lists.
9454         if (TemplateParamLists.size() > 0)
9455           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9456 
9457         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9458         if (isFriend) {
9459           // We want to remove the "template<>", found here.
9460           SourceRange RemoveRange = TemplateParams->getSourceRange();
9461 
9462           // If we remove the template<> and the name is not a
9463           // template-id, we're actually silently creating a problem:
9464           // the friend declaration will refer to an untemplated decl,
9465           // and clearly the user wants a template specialization.  So
9466           // we need to insert '<>' after the name.
9467           SourceLocation InsertLoc;
9468           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9469             InsertLoc = D.getName().getSourceRange().getEnd();
9470             InsertLoc = getLocForEndOfToken(InsertLoc);
9471           }
9472 
9473           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9474             << Name << RemoveRange
9475             << FixItHint::CreateRemoval(RemoveRange)
9476             << FixItHint::CreateInsertion(InsertLoc, "<>");
9477           Invalid = true;
9478         }
9479       }
9480     } else {
9481       // Check that we can declare a template here.
9482       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9483           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9484         NewFD->setInvalidDecl();
9485 
9486       // All template param lists were matched against the scope specifier:
9487       // this is NOT (an explicit specialization of) a template.
9488       if (TemplateParamLists.size() > 0)
9489         // For source fidelity, store all the template param lists.
9490         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9491     }
9492 
9493     if (Invalid) {
9494       NewFD->setInvalidDecl();
9495       if (FunctionTemplate)
9496         FunctionTemplate->setInvalidDecl();
9497     }
9498 
9499     // C++ [dcl.fct.spec]p5:
9500     //   The virtual specifier shall only be used in declarations of
9501     //   nonstatic class member functions that appear within a
9502     //   member-specification of a class declaration; see 10.3.
9503     //
9504     if (isVirtual && !NewFD->isInvalidDecl()) {
9505       if (!isVirtualOkay) {
9506         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9507              diag::err_virtual_non_function);
9508       } else if (!CurContext->isRecord()) {
9509         // 'virtual' was specified outside of the class.
9510         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9511              diag::err_virtual_out_of_class)
9512           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9513       } else if (NewFD->getDescribedFunctionTemplate()) {
9514         // C++ [temp.mem]p3:
9515         //  A member function template shall not be virtual.
9516         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9517              diag::err_virtual_member_function_template)
9518           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9519       } else {
9520         // Okay: Add virtual to the method.
9521         NewFD->setVirtualAsWritten(true);
9522       }
9523 
9524       if (getLangOpts().CPlusPlus14 &&
9525           NewFD->getReturnType()->isUndeducedType())
9526         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9527     }
9528 
9529     if (getLangOpts().CPlusPlus14 &&
9530         (NewFD->isDependentContext() ||
9531          (isFriend && CurContext->isDependentContext())) &&
9532         NewFD->getReturnType()->isUndeducedType()) {
9533       // If the function template is referenced directly (for instance, as a
9534       // member of the current instantiation), pretend it has a dependent type.
9535       // This is not really justified by the standard, but is the only sane
9536       // thing to do.
9537       // FIXME: For a friend function, we have not marked the function as being
9538       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9539       const FunctionProtoType *FPT =
9540           NewFD->getType()->castAs<FunctionProtoType>();
9541       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9542       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9543                                              FPT->getExtProtoInfo()));
9544     }
9545 
9546     // C++ [dcl.fct.spec]p3:
9547     //  The inline specifier shall not appear on a block scope function
9548     //  declaration.
9549     if (isInline && !NewFD->isInvalidDecl()) {
9550       if (CurContext->isFunctionOrMethod()) {
9551         // 'inline' is not allowed on block scope function declaration.
9552         Diag(D.getDeclSpec().getInlineSpecLoc(),
9553              diag::err_inline_declaration_block_scope) << Name
9554           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9555       }
9556     }
9557 
9558     // C++ [dcl.fct.spec]p6:
9559     //  The explicit specifier shall be used only in the declaration of a
9560     //  constructor or conversion function within its class definition;
9561     //  see 12.3.1 and 12.3.2.
9562     if (hasExplicit && !NewFD->isInvalidDecl() &&
9563         !isa<CXXDeductionGuideDecl>(NewFD)) {
9564       if (!CurContext->isRecord()) {
9565         // 'explicit' was specified outside of the class.
9566         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9567              diag::err_explicit_out_of_class)
9568             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9569       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9570                  !isa<CXXConversionDecl>(NewFD)) {
9571         // 'explicit' was specified on a function that wasn't a constructor
9572         // or conversion function.
9573         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9574              diag::err_explicit_non_ctor_or_conv_function)
9575             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9576       }
9577     }
9578 
9579     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9580     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9581       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9582       // are implicitly inline.
9583       NewFD->setImplicitlyInline();
9584 
9585       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9586       // be either constructors or to return a literal type. Therefore,
9587       // destructors cannot be declared constexpr.
9588       if (isa<CXXDestructorDecl>(NewFD) &&
9589           (!getLangOpts().CPlusPlus20 ||
9590            ConstexprKind == ConstexprSpecKind::Consteval)) {
9591         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9592             << static_cast<int>(ConstexprKind);
9593         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9594                                     ? ConstexprSpecKind::Unspecified
9595                                     : ConstexprSpecKind::Constexpr);
9596       }
9597       // C++20 [dcl.constexpr]p2: An allocation function, or a
9598       // deallocation function shall not be declared with the consteval
9599       // specifier.
9600       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9601           (NewFD->getOverloadedOperator() == OO_New ||
9602            NewFD->getOverloadedOperator() == OO_Array_New ||
9603            NewFD->getOverloadedOperator() == OO_Delete ||
9604            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9605         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9606              diag::err_invalid_consteval_decl_kind)
9607             << NewFD;
9608         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9609       }
9610     }
9611 
9612     // If __module_private__ was specified, mark the function accordingly.
9613     if (D.getDeclSpec().isModulePrivateSpecified()) {
9614       if (isFunctionTemplateSpecialization) {
9615         SourceLocation ModulePrivateLoc
9616           = D.getDeclSpec().getModulePrivateSpecLoc();
9617         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9618           << 0
9619           << FixItHint::CreateRemoval(ModulePrivateLoc);
9620       } else {
9621         NewFD->setModulePrivate();
9622         if (FunctionTemplate)
9623           FunctionTemplate->setModulePrivate();
9624       }
9625     }
9626 
9627     if (isFriend) {
9628       if (FunctionTemplate) {
9629         FunctionTemplate->setObjectOfFriendDecl();
9630         FunctionTemplate->setAccess(AS_public);
9631       }
9632       NewFD->setObjectOfFriendDecl();
9633       NewFD->setAccess(AS_public);
9634     }
9635 
9636     // If a function is defined as defaulted or deleted, mark it as such now.
9637     // We'll do the relevant checks on defaulted / deleted functions later.
9638     switch (D.getFunctionDefinitionKind()) {
9639     case FunctionDefinitionKind::Declaration:
9640     case FunctionDefinitionKind::Definition:
9641       break;
9642 
9643     case FunctionDefinitionKind::Defaulted:
9644       NewFD->setDefaulted();
9645       break;
9646 
9647     case FunctionDefinitionKind::Deleted:
9648       NewFD->setDeletedAsWritten();
9649       break;
9650     }
9651 
9652     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9653         D.isFunctionDefinition()) {
9654       // C++ [class.mfct]p2:
9655       //   A member function may be defined (8.4) in its class definition, in
9656       //   which case it is an inline member function (7.1.2)
9657       NewFD->setImplicitlyInline();
9658     }
9659 
9660     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9661         !CurContext->isRecord()) {
9662       // C++ [class.static]p1:
9663       //   A data or function member of a class may be declared static
9664       //   in a class definition, in which case it is a static member of
9665       //   the class.
9666 
9667       // Complain about the 'static' specifier if it's on an out-of-line
9668       // member function definition.
9669 
9670       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9671       // member function template declaration and class member template
9672       // declaration (MSVC versions before 2015), warn about this.
9673       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9674            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9675              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9676            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9677            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9678         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9679     }
9680 
9681     // C++11 [except.spec]p15:
9682     //   A deallocation function with no exception-specification is treated
9683     //   as if it were specified with noexcept(true).
9684     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9685     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9686          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9687         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9688       NewFD->setType(Context.getFunctionType(
9689           FPT->getReturnType(), FPT->getParamTypes(),
9690           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9691   }
9692 
9693   // Filter out previous declarations that don't match the scope.
9694   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9695                        D.getCXXScopeSpec().isNotEmpty() ||
9696                        isMemberSpecialization ||
9697                        isFunctionTemplateSpecialization);
9698 
9699   // Handle GNU asm-label extension (encoded as an attribute).
9700   if (Expr *E = (Expr*) D.getAsmLabel()) {
9701     // The parser guarantees this is a string.
9702     StringLiteral *SE = cast<StringLiteral>(E);
9703     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9704                                         /*IsLiteralLabel=*/true,
9705                                         SE->getStrTokenLoc(0)));
9706   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9707     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9708       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9709     if (I != ExtnameUndeclaredIdentifiers.end()) {
9710       if (isDeclExternC(NewFD)) {
9711         NewFD->addAttr(I->second);
9712         ExtnameUndeclaredIdentifiers.erase(I);
9713       } else
9714         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9715             << /*Variable*/0 << NewFD;
9716     }
9717   }
9718 
9719   // Copy the parameter declarations from the declarator D to the function
9720   // declaration NewFD, if they are available.  First scavenge them into Params.
9721   SmallVector<ParmVarDecl*, 16> Params;
9722   unsigned FTIIdx;
9723   if (D.isFunctionDeclarator(FTIIdx)) {
9724     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9725 
9726     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9727     // function that takes no arguments, not a function that takes a
9728     // single void argument.
9729     // We let through "const void" here because Sema::GetTypeForDeclarator
9730     // already checks for that case.
9731     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9732       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9733         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9734         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9735         Param->setDeclContext(NewFD);
9736         Params.push_back(Param);
9737 
9738         if (Param->isInvalidDecl())
9739           NewFD->setInvalidDecl();
9740       }
9741     }
9742 
9743     if (!getLangOpts().CPlusPlus) {
9744       // In C, find all the tag declarations from the prototype and move them
9745       // into the function DeclContext. Remove them from the surrounding tag
9746       // injection context of the function, which is typically but not always
9747       // the TU.
9748       DeclContext *PrototypeTagContext =
9749           getTagInjectionContext(NewFD->getLexicalDeclContext());
9750       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9751         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9752 
9753         // We don't want to reparent enumerators. Look at their parent enum
9754         // instead.
9755         if (!TD) {
9756           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9757             TD = cast<EnumDecl>(ECD->getDeclContext());
9758         }
9759         if (!TD)
9760           continue;
9761         DeclContext *TagDC = TD->getLexicalDeclContext();
9762         if (!TagDC->containsDecl(TD))
9763           continue;
9764         TagDC->removeDecl(TD);
9765         TD->setDeclContext(NewFD);
9766         NewFD->addDecl(TD);
9767 
9768         // Preserve the lexical DeclContext if it is not the surrounding tag
9769         // injection context of the FD. In this example, the semantic context of
9770         // E will be f and the lexical context will be S, while both the
9771         // semantic and lexical contexts of S will be f:
9772         //   void f(struct S { enum E { a } f; } s);
9773         if (TagDC != PrototypeTagContext)
9774           TD->setLexicalDeclContext(TagDC);
9775       }
9776     }
9777   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9778     // When we're declaring a function with a typedef, typeof, etc as in the
9779     // following example, we'll need to synthesize (unnamed)
9780     // parameters for use in the declaration.
9781     //
9782     // @code
9783     // typedef void fn(int);
9784     // fn f;
9785     // @endcode
9786 
9787     // Synthesize a parameter for each argument type.
9788     for (const auto &AI : FT->param_types()) {
9789       ParmVarDecl *Param =
9790           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9791       Param->setScopeInfo(0, Params.size());
9792       Params.push_back(Param);
9793     }
9794   } else {
9795     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9796            "Should not need args for typedef of non-prototype fn");
9797   }
9798 
9799   // Finally, we know we have the right number of parameters, install them.
9800   NewFD->setParams(Params);
9801 
9802   if (D.getDeclSpec().isNoreturnSpecified())
9803     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9804                                            D.getDeclSpec().getNoreturnSpecLoc(),
9805                                            AttributeCommonInfo::AS_Keyword));
9806 
9807   // Functions returning a variably modified type violate C99 6.7.5.2p2
9808   // because all functions have linkage.
9809   if (!NewFD->isInvalidDecl() &&
9810       NewFD->getReturnType()->isVariablyModifiedType()) {
9811     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9812     NewFD->setInvalidDecl();
9813   }
9814 
9815   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9816   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9817       !NewFD->hasAttr<SectionAttr>())
9818     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9819         Context, PragmaClangTextSection.SectionName,
9820         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9821 
9822   // Apply an implicit SectionAttr if #pragma code_seg is active.
9823   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9824       !NewFD->hasAttr<SectionAttr>()) {
9825     NewFD->addAttr(SectionAttr::CreateImplicit(
9826         Context, CodeSegStack.CurrentValue->getString(),
9827         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9828         SectionAttr::Declspec_allocate));
9829     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9830                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9831                          ASTContext::PSF_Read,
9832                      NewFD))
9833       NewFD->dropAttr<SectionAttr>();
9834   }
9835 
9836   // Apply an implicit CodeSegAttr from class declspec or
9837   // apply an implicit SectionAttr from #pragma code_seg if active.
9838   if (!NewFD->hasAttr<CodeSegAttr>()) {
9839     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9840                                                                  D.isFunctionDefinition())) {
9841       NewFD->addAttr(SAttr);
9842     }
9843   }
9844 
9845   // Handle attributes.
9846   ProcessDeclAttributes(S, NewFD, D);
9847 
9848   if (getLangOpts().OpenCL) {
9849     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9850     // type declaration will generate a compilation error.
9851     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9852     if (AddressSpace != LangAS::Default) {
9853       Diag(NewFD->getLocation(),
9854            diag::err_opencl_return_value_with_address_space);
9855       NewFD->setInvalidDecl();
9856     }
9857   }
9858 
9859   if (!getLangOpts().CPlusPlus) {
9860     // Perform semantic checking on the function declaration.
9861     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9862       CheckMain(NewFD, D.getDeclSpec());
9863 
9864     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9865       CheckMSVCRTEntryPoint(NewFD);
9866 
9867     if (!NewFD->isInvalidDecl())
9868       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9869                                                   isMemberSpecialization,
9870                                                   D.isFunctionDefinition()));
9871     else if (!Previous.empty())
9872       // Recover gracefully from an invalid redeclaration.
9873       D.setRedeclaration(true);
9874     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9875             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9876            "previous declaration set still overloaded");
9877 
9878     // Diagnose no-prototype function declarations with calling conventions that
9879     // don't support variadic calls. Only do this in C and do it after merging
9880     // possibly prototyped redeclarations.
9881     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9882     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9883       CallingConv CC = FT->getExtInfo().getCC();
9884       if (!supportsVariadicCall(CC)) {
9885         // Windows system headers sometimes accidentally use stdcall without
9886         // (void) parameters, so we relax this to a warning.
9887         int DiagID =
9888             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9889         Diag(NewFD->getLocation(), DiagID)
9890             << FunctionType::getNameForCallConv(CC);
9891       }
9892     }
9893 
9894    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9895        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9896      checkNonTrivialCUnion(NewFD->getReturnType(),
9897                            NewFD->getReturnTypeSourceRange().getBegin(),
9898                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9899   } else {
9900     // C++11 [replacement.functions]p3:
9901     //  The program's definitions shall not be specified as inline.
9902     //
9903     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9904     //
9905     // Suppress the diagnostic if the function is __attribute__((used)), since
9906     // that forces an external definition to be emitted.
9907     if (D.getDeclSpec().isInlineSpecified() &&
9908         NewFD->isReplaceableGlobalAllocationFunction() &&
9909         !NewFD->hasAttr<UsedAttr>())
9910       Diag(D.getDeclSpec().getInlineSpecLoc(),
9911            diag::ext_operator_new_delete_declared_inline)
9912         << NewFD->getDeclName();
9913 
9914     // If the declarator is a template-id, translate the parser's template
9915     // argument list into our AST format.
9916     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9917       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9918       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9919       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9920       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9921                                          TemplateId->NumArgs);
9922       translateTemplateArguments(TemplateArgsPtr,
9923                                  TemplateArgs);
9924 
9925       HasExplicitTemplateArgs = true;
9926 
9927       if (NewFD->isInvalidDecl()) {
9928         HasExplicitTemplateArgs = false;
9929       } else if (FunctionTemplate) {
9930         // Function template with explicit template arguments.
9931         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9932           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9933 
9934         HasExplicitTemplateArgs = false;
9935       } else {
9936         assert((isFunctionTemplateSpecialization ||
9937                 D.getDeclSpec().isFriendSpecified()) &&
9938                "should have a 'template<>' for this decl");
9939         // "friend void foo<>(int);" is an implicit specialization decl.
9940         isFunctionTemplateSpecialization = true;
9941       }
9942     } else if (isFriend && isFunctionTemplateSpecialization) {
9943       // This combination is only possible in a recovery case;  the user
9944       // wrote something like:
9945       //   template <> friend void foo(int);
9946       // which we're recovering from as if the user had written:
9947       //   friend void foo<>(int);
9948       // Go ahead and fake up a template id.
9949       HasExplicitTemplateArgs = true;
9950       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9951       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9952     }
9953 
9954     // We do not add HD attributes to specializations here because
9955     // they may have different constexpr-ness compared to their
9956     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9957     // may end up with different effective targets. Instead, a
9958     // specialization inherits its target attributes from its template
9959     // in the CheckFunctionTemplateSpecialization() call below.
9960     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9961       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9962 
9963     // If it's a friend (and only if it's a friend), it's possible
9964     // that either the specialized function type or the specialized
9965     // template is dependent, and therefore matching will fail.  In
9966     // this case, don't check the specialization yet.
9967     if (isFunctionTemplateSpecialization && isFriend &&
9968         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9969          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9970              TemplateArgs.arguments()))) {
9971       assert(HasExplicitTemplateArgs &&
9972              "friend function specialization without template args");
9973       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9974                                                        Previous))
9975         NewFD->setInvalidDecl();
9976     } else if (isFunctionTemplateSpecialization) {
9977       if (CurContext->isDependentContext() && CurContext->isRecord()
9978           && !isFriend) {
9979         isDependentClassScopeExplicitSpecialization = true;
9980       } else if (!NewFD->isInvalidDecl() &&
9981                  CheckFunctionTemplateSpecialization(
9982                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9983                      Previous))
9984         NewFD->setInvalidDecl();
9985 
9986       // C++ [dcl.stc]p1:
9987       //   A storage-class-specifier shall not be specified in an explicit
9988       //   specialization (14.7.3)
9989       FunctionTemplateSpecializationInfo *Info =
9990           NewFD->getTemplateSpecializationInfo();
9991       if (Info && SC != SC_None) {
9992         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9993           Diag(NewFD->getLocation(),
9994                diag::err_explicit_specialization_inconsistent_storage_class)
9995             << SC
9996             << FixItHint::CreateRemoval(
9997                                       D.getDeclSpec().getStorageClassSpecLoc());
9998 
9999         else
10000           Diag(NewFD->getLocation(),
10001                diag::ext_explicit_specialization_storage_class)
10002             << FixItHint::CreateRemoval(
10003                                       D.getDeclSpec().getStorageClassSpecLoc());
10004       }
10005     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10006       if (CheckMemberSpecialization(NewFD, Previous))
10007           NewFD->setInvalidDecl();
10008     }
10009 
10010     // Perform semantic checking on the function declaration.
10011     if (!isDependentClassScopeExplicitSpecialization) {
10012       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10013         CheckMain(NewFD, D.getDeclSpec());
10014 
10015       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10016         CheckMSVCRTEntryPoint(NewFD);
10017 
10018       if (!NewFD->isInvalidDecl())
10019         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10020                                                     isMemberSpecialization,
10021                                                     D.isFunctionDefinition()));
10022       else if (!Previous.empty())
10023         // Recover gracefully from an invalid redeclaration.
10024         D.setRedeclaration(true);
10025     }
10026 
10027     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10028             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10029            "previous declaration set still overloaded");
10030 
10031     NamedDecl *PrincipalDecl = (FunctionTemplate
10032                                 ? cast<NamedDecl>(FunctionTemplate)
10033                                 : NewFD);
10034 
10035     if (isFriend && NewFD->getPreviousDecl()) {
10036       AccessSpecifier Access = AS_public;
10037       if (!NewFD->isInvalidDecl())
10038         Access = NewFD->getPreviousDecl()->getAccess();
10039 
10040       NewFD->setAccess(Access);
10041       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10042     }
10043 
10044     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10045         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10046       PrincipalDecl->setNonMemberOperator();
10047 
10048     // If we have a function template, check the template parameter
10049     // list. This will check and merge default template arguments.
10050     if (FunctionTemplate) {
10051       FunctionTemplateDecl *PrevTemplate =
10052                                      FunctionTemplate->getPreviousDecl();
10053       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10054                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10055                                     : nullptr,
10056                             D.getDeclSpec().isFriendSpecified()
10057                               ? (D.isFunctionDefinition()
10058                                    ? TPC_FriendFunctionTemplateDefinition
10059                                    : TPC_FriendFunctionTemplate)
10060                               : (D.getCXXScopeSpec().isSet() &&
10061                                  DC && DC->isRecord() &&
10062                                  DC->isDependentContext())
10063                                   ? TPC_ClassTemplateMember
10064                                   : TPC_FunctionTemplate);
10065     }
10066 
10067     if (NewFD->isInvalidDecl()) {
10068       // Ignore all the rest of this.
10069     } else if (!D.isRedeclaration()) {
10070       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10071                                        AddToScope };
10072       // Fake up an access specifier if it's supposed to be a class member.
10073       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10074         NewFD->setAccess(AS_public);
10075 
10076       // Qualified decls generally require a previous declaration.
10077       if (D.getCXXScopeSpec().isSet()) {
10078         // ...with the major exception of templated-scope or
10079         // dependent-scope friend declarations.
10080 
10081         // TODO: we currently also suppress this check in dependent
10082         // contexts because (1) the parameter depth will be off when
10083         // matching friend templates and (2) we might actually be
10084         // selecting a friend based on a dependent factor.  But there
10085         // are situations where these conditions don't apply and we
10086         // can actually do this check immediately.
10087         //
10088         // Unless the scope is dependent, it's always an error if qualified
10089         // redeclaration lookup found nothing at all. Diagnose that now;
10090         // nothing will diagnose that error later.
10091         if (isFriend &&
10092             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10093              (!Previous.empty() && CurContext->isDependentContext()))) {
10094           // ignore these
10095         } else if (NewFD->isCPUDispatchMultiVersion() ||
10096                    NewFD->isCPUSpecificMultiVersion()) {
10097           // ignore this, we allow the redeclaration behavior here to create new
10098           // versions of the function.
10099         } else {
10100           // The user tried to provide an out-of-line definition for a
10101           // function that is a member of a class or namespace, but there
10102           // was no such member function declared (C++ [class.mfct]p2,
10103           // C++ [namespace.memdef]p2). For example:
10104           //
10105           // class X {
10106           //   void f() const;
10107           // };
10108           //
10109           // void X::f() { } // ill-formed
10110           //
10111           // Complain about this problem, and attempt to suggest close
10112           // matches (e.g., those that differ only in cv-qualifiers and
10113           // whether the parameter types are references).
10114 
10115           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10116                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10117             AddToScope = ExtraArgs.AddToScope;
10118             return Result;
10119           }
10120         }
10121 
10122         // Unqualified local friend declarations are required to resolve
10123         // to something.
10124       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10125         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10126                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10127           AddToScope = ExtraArgs.AddToScope;
10128           return Result;
10129         }
10130       }
10131     } else if (!D.isFunctionDefinition() &&
10132                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10133                !isFriend && !isFunctionTemplateSpecialization &&
10134                !isMemberSpecialization) {
10135       // An out-of-line member function declaration must also be a
10136       // definition (C++ [class.mfct]p2).
10137       // Note that this is not the case for explicit specializations of
10138       // function templates or member functions of class templates, per
10139       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10140       // extension for compatibility with old SWIG code which likes to
10141       // generate them.
10142       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10143         << D.getCXXScopeSpec().getRange();
10144     }
10145   }
10146 
10147   // If this is the first declaration of a library builtin function, add
10148   // attributes as appropriate.
10149   if (!D.isRedeclaration()) {
10150     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10151       if (unsigned BuiltinID = II->getBuiltinID()) {
10152         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10153         if (!InStdNamespace &&
10154             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10155           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10156             // Validate the type matches unless this builtin is specified as
10157             // matching regardless of its declared type.
10158             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10159               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10160             } else {
10161               ASTContext::GetBuiltinTypeError Error;
10162               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10163               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10164 
10165               if (!Error && !BuiltinType.isNull() &&
10166                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10167                       NewFD->getType(), BuiltinType))
10168                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10169             }
10170           }
10171         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10172                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10173           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10174         }
10175       }
10176     }
10177   }
10178 
10179   ProcessPragmaWeak(S, NewFD);
10180   checkAttributesAfterMerging(*this, *NewFD);
10181 
10182   AddKnownFunctionAttributes(NewFD);
10183 
10184   if (NewFD->hasAttr<OverloadableAttr>() &&
10185       !NewFD->getType()->getAs<FunctionProtoType>()) {
10186     Diag(NewFD->getLocation(),
10187          diag::err_attribute_overloadable_no_prototype)
10188       << NewFD;
10189 
10190     // Turn this into a variadic function with no parameters.
10191     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10192     FunctionProtoType::ExtProtoInfo EPI(
10193         Context.getDefaultCallingConvention(true, false));
10194     EPI.Variadic = true;
10195     EPI.ExtInfo = FT->getExtInfo();
10196 
10197     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10198     NewFD->setType(R);
10199   }
10200 
10201   // If there's a #pragma GCC visibility in scope, and this isn't a class
10202   // member, set the visibility of this function.
10203   if (!DC->isRecord() && NewFD->isExternallyVisible())
10204     AddPushedVisibilityAttribute(NewFD);
10205 
10206   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10207   // marking the function.
10208   AddCFAuditedAttribute(NewFD);
10209 
10210   // If this is a function definition, check if we have to apply any
10211   // attributes (i.e. optnone and no_builtin) due to a pragma.
10212   if (D.isFunctionDefinition()) {
10213     AddRangeBasedOptnone(NewFD);
10214     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10215     AddSectionMSAllocText(NewFD);
10216     ModifyFnAttributesMSPragmaOptimize(NewFD);
10217   }
10218 
10219   // If this is the first declaration of an extern C variable, update
10220   // the map of such variables.
10221   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10222       isIncompleteDeclExternC(*this, NewFD))
10223     RegisterLocallyScopedExternCDecl(NewFD, S);
10224 
10225   // Set this FunctionDecl's range up to the right paren.
10226   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10227 
10228   if (D.isRedeclaration() && !Previous.empty()) {
10229     NamedDecl *Prev = Previous.getRepresentativeDecl();
10230     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10231                                    isMemberSpecialization ||
10232                                        isFunctionTemplateSpecialization,
10233                                    D.isFunctionDefinition());
10234   }
10235 
10236   if (getLangOpts().CUDA) {
10237     IdentifierInfo *II = NewFD->getIdentifier();
10238     if (II && II->isStr(getCudaConfigureFuncName()) &&
10239         !NewFD->isInvalidDecl() &&
10240         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10241       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10242         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10243             << getCudaConfigureFuncName();
10244       Context.setcudaConfigureCallDecl(NewFD);
10245     }
10246 
10247     // Variadic functions, other than a *declaration* of printf, are not allowed
10248     // in device-side CUDA code, unless someone passed
10249     // -fcuda-allow-variadic-functions.
10250     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10251         (NewFD->hasAttr<CUDADeviceAttr>() ||
10252          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10253         !(II && II->isStr("printf") && NewFD->isExternC() &&
10254           !D.isFunctionDefinition())) {
10255       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10256     }
10257   }
10258 
10259   MarkUnusedFileScopedDecl(NewFD);
10260 
10261 
10262 
10263   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10264     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10265     if (SC == SC_Static) {
10266       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10267       D.setInvalidType();
10268     }
10269 
10270     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10271     if (!NewFD->getReturnType()->isVoidType()) {
10272       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10273       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10274           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10275                                 : FixItHint());
10276       D.setInvalidType();
10277     }
10278 
10279     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10280     for (auto Param : NewFD->parameters())
10281       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10282 
10283     if (getLangOpts().OpenCLCPlusPlus) {
10284       if (DC->isRecord()) {
10285         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10286         D.setInvalidType();
10287       }
10288       if (FunctionTemplate) {
10289         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10290         D.setInvalidType();
10291       }
10292     }
10293   }
10294 
10295   if (getLangOpts().CPlusPlus) {
10296     if (FunctionTemplate) {
10297       if (NewFD->isInvalidDecl())
10298         FunctionTemplate->setInvalidDecl();
10299       return FunctionTemplate;
10300     }
10301 
10302     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10303       CompleteMemberSpecialization(NewFD, Previous);
10304   }
10305 
10306   for (const ParmVarDecl *Param : NewFD->parameters()) {
10307     QualType PT = Param->getType();
10308 
10309     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10310     // types.
10311     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10312       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10313         QualType ElemTy = PipeTy->getElementType();
10314           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10315             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10316             D.setInvalidType();
10317           }
10318       }
10319     }
10320   }
10321 
10322   // Here we have an function template explicit specialization at class scope.
10323   // The actual specialization will be postponed to template instatiation
10324   // time via the ClassScopeFunctionSpecializationDecl node.
10325   if (isDependentClassScopeExplicitSpecialization) {
10326     ClassScopeFunctionSpecializationDecl *NewSpec =
10327                          ClassScopeFunctionSpecializationDecl::Create(
10328                                 Context, CurContext, NewFD->getLocation(),
10329                                 cast<CXXMethodDecl>(NewFD),
10330                                 HasExplicitTemplateArgs, TemplateArgs);
10331     CurContext->addDecl(NewSpec);
10332     AddToScope = false;
10333   }
10334 
10335   // Diagnose availability attributes. Availability cannot be used on functions
10336   // that are run during load/unload.
10337   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10338     if (NewFD->hasAttr<ConstructorAttr>()) {
10339       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10340           << 1;
10341       NewFD->dropAttr<AvailabilityAttr>();
10342     }
10343     if (NewFD->hasAttr<DestructorAttr>()) {
10344       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10345           << 2;
10346       NewFD->dropAttr<AvailabilityAttr>();
10347     }
10348   }
10349 
10350   // Diagnose no_builtin attribute on function declaration that are not a
10351   // definition.
10352   // FIXME: We should really be doing this in
10353   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10354   // the FunctionDecl and at this point of the code
10355   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10356   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10357   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10358     switch (D.getFunctionDefinitionKind()) {
10359     case FunctionDefinitionKind::Defaulted:
10360     case FunctionDefinitionKind::Deleted:
10361       Diag(NBA->getLocation(),
10362            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10363           << NBA->getSpelling();
10364       break;
10365     case FunctionDefinitionKind::Declaration:
10366       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10367           << NBA->getSpelling();
10368       break;
10369     case FunctionDefinitionKind::Definition:
10370       break;
10371     }
10372 
10373   return NewFD;
10374 }
10375 
10376 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10377 /// when __declspec(code_seg) "is applied to a class, all member functions of
10378 /// the class and nested classes -- this includes compiler-generated special
10379 /// member functions -- are put in the specified segment."
10380 /// The actual behavior is a little more complicated. The Microsoft compiler
10381 /// won't check outer classes if there is an active value from #pragma code_seg.
10382 /// The CodeSeg is always applied from the direct parent but only from outer
10383 /// classes when the #pragma code_seg stack is empty. See:
10384 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10385 /// available since MS has removed the page.
10386 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10387   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10388   if (!Method)
10389     return nullptr;
10390   const CXXRecordDecl *Parent = Method->getParent();
10391   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10392     Attr *NewAttr = SAttr->clone(S.getASTContext());
10393     NewAttr->setImplicit(true);
10394     return NewAttr;
10395   }
10396 
10397   // The Microsoft compiler won't check outer classes for the CodeSeg
10398   // when the #pragma code_seg stack is active.
10399   if (S.CodeSegStack.CurrentValue)
10400    return nullptr;
10401 
10402   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10403     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10404       Attr *NewAttr = SAttr->clone(S.getASTContext());
10405       NewAttr->setImplicit(true);
10406       return NewAttr;
10407     }
10408   }
10409   return nullptr;
10410 }
10411 
10412 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10413 /// containing class. Otherwise it will return implicit SectionAttr if the
10414 /// function is a definition and there is an active value on CodeSegStack
10415 /// (from the current #pragma code-seg value).
10416 ///
10417 /// \param FD Function being declared.
10418 /// \param IsDefinition Whether it is a definition or just a declarartion.
10419 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10420 ///          nullptr if no attribute should be added.
10421 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10422                                                        bool IsDefinition) {
10423   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10424     return A;
10425   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10426       CodeSegStack.CurrentValue)
10427     return SectionAttr::CreateImplicit(
10428         getASTContext(), CodeSegStack.CurrentValue->getString(),
10429         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10430         SectionAttr::Declspec_allocate);
10431   return nullptr;
10432 }
10433 
10434 /// Determines if we can perform a correct type check for \p D as a
10435 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10436 /// best-effort check.
10437 ///
10438 /// \param NewD The new declaration.
10439 /// \param OldD The old declaration.
10440 /// \param NewT The portion of the type of the new declaration to check.
10441 /// \param OldT The portion of the type of the old declaration to check.
10442 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10443                                           QualType NewT, QualType OldT) {
10444   if (!NewD->getLexicalDeclContext()->isDependentContext())
10445     return true;
10446 
10447   // For dependently-typed local extern declarations and friends, we can't
10448   // perform a correct type check in general until instantiation:
10449   //
10450   //   int f();
10451   //   template<typename T> void g() { T f(); }
10452   //
10453   // (valid if g() is only instantiated with T = int).
10454   if (NewT->isDependentType() &&
10455       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10456     return false;
10457 
10458   // Similarly, if the previous declaration was a dependent local extern
10459   // declaration, we don't really know its type yet.
10460   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10461     return false;
10462 
10463   return true;
10464 }
10465 
10466 /// Checks if the new declaration declared in dependent context must be
10467 /// put in the same redeclaration chain as the specified declaration.
10468 ///
10469 /// \param D Declaration that is checked.
10470 /// \param PrevDecl Previous declaration found with proper lookup method for the
10471 ///                 same declaration name.
10472 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10473 ///          belongs to.
10474 ///
10475 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10476   if (!D->getLexicalDeclContext()->isDependentContext())
10477     return true;
10478 
10479   // Don't chain dependent friend function definitions until instantiation, to
10480   // permit cases like
10481   //
10482   //   void func();
10483   //   template<typename T> class C1 { friend void func() {} };
10484   //   template<typename T> class C2 { friend void func() {} };
10485   //
10486   // ... which is valid if only one of C1 and C2 is ever instantiated.
10487   //
10488   // FIXME: This need only apply to function definitions. For now, we proxy
10489   // this by checking for a file-scope function. We do not want this to apply
10490   // to friend declarations nominating member functions, because that gets in
10491   // the way of access checks.
10492   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10493     return false;
10494 
10495   auto *VD = dyn_cast<ValueDecl>(D);
10496   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10497   return !VD || !PrevVD ||
10498          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10499                                         PrevVD->getType());
10500 }
10501 
10502 /// Check the target attribute of the function for MultiVersion
10503 /// validity.
10504 ///
10505 /// Returns true if there was an error, false otherwise.
10506 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10507   const auto *TA = FD->getAttr<TargetAttr>();
10508   assert(TA && "MultiVersion Candidate requires a target attribute");
10509   ParsedTargetAttr ParseInfo = TA->parse();
10510   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10511   enum ErrType { Feature = 0, Architecture = 1 };
10512 
10513   if (!ParseInfo.Architecture.empty() &&
10514       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10515     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10516         << Architecture << ParseInfo.Architecture;
10517     return true;
10518   }
10519 
10520   for (const auto &Feat : ParseInfo.Features) {
10521     auto BareFeat = StringRef{Feat}.substr(1);
10522     if (Feat[0] == '-') {
10523       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10524           << Feature << ("no-" + BareFeat).str();
10525       return true;
10526     }
10527 
10528     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10529         !TargetInfo.isValidFeatureName(BareFeat)) {
10530       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10531           << Feature << BareFeat;
10532       return true;
10533     }
10534   }
10535   return false;
10536 }
10537 
10538 // Provide a white-list of attributes that are allowed to be combined with
10539 // multiversion functions.
10540 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10541                                            MultiVersionKind MVKind) {
10542   // Note: this list/diagnosis must match the list in
10543   // checkMultiversionAttributesAllSame.
10544   switch (Kind) {
10545   default:
10546     return false;
10547   case attr::Used:
10548     return MVKind == MultiVersionKind::Target;
10549   case attr::NonNull:
10550   case attr::NoThrow:
10551     return true;
10552   }
10553 }
10554 
10555 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10556                                                  const FunctionDecl *FD,
10557                                                  const FunctionDecl *CausedFD,
10558                                                  MultiVersionKind MVKind) {
10559   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10560     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10561         << static_cast<unsigned>(MVKind) << A;
10562     if (CausedFD)
10563       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10564     return true;
10565   };
10566 
10567   for (const Attr *A : FD->attrs()) {
10568     switch (A->getKind()) {
10569     case attr::CPUDispatch:
10570     case attr::CPUSpecific:
10571       if (MVKind != MultiVersionKind::CPUDispatch &&
10572           MVKind != MultiVersionKind::CPUSpecific)
10573         return Diagnose(S, A);
10574       break;
10575     case attr::Target:
10576       if (MVKind != MultiVersionKind::Target)
10577         return Diagnose(S, A);
10578       break;
10579     case attr::TargetClones:
10580       if (MVKind != MultiVersionKind::TargetClones)
10581         return Diagnose(S, A);
10582       break;
10583     default:
10584       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10585         return Diagnose(S, A);
10586       break;
10587     }
10588   }
10589   return false;
10590 }
10591 
10592 bool Sema::areMultiversionVariantFunctionsCompatible(
10593     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10594     const PartialDiagnostic &NoProtoDiagID,
10595     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10596     const PartialDiagnosticAt &NoSupportDiagIDAt,
10597     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10598     bool ConstexprSupported, bool CLinkageMayDiffer) {
10599   enum DoesntSupport {
10600     FuncTemplates = 0,
10601     VirtFuncs = 1,
10602     DeducedReturn = 2,
10603     Constructors = 3,
10604     Destructors = 4,
10605     DeletedFuncs = 5,
10606     DefaultedFuncs = 6,
10607     ConstexprFuncs = 7,
10608     ConstevalFuncs = 8,
10609     Lambda = 9,
10610   };
10611   enum Different {
10612     CallingConv = 0,
10613     ReturnType = 1,
10614     ConstexprSpec = 2,
10615     InlineSpec = 3,
10616     Linkage = 4,
10617     LanguageLinkage = 5,
10618   };
10619 
10620   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10621       !OldFD->getType()->getAs<FunctionProtoType>()) {
10622     Diag(OldFD->getLocation(), NoProtoDiagID);
10623     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10624     return true;
10625   }
10626 
10627   if (NoProtoDiagID.getDiagID() != 0 &&
10628       !NewFD->getType()->getAs<FunctionProtoType>())
10629     return Diag(NewFD->getLocation(), NoProtoDiagID);
10630 
10631   if (!TemplatesSupported &&
10632       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10633     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10634            << FuncTemplates;
10635 
10636   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10637     if (NewCXXFD->isVirtual())
10638       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10639              << VirtFuncs;
10640 
10641     if (isa<CXXConstructorDecl>(NewCXXFD))
10642       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10643              << Constructors;
10644 
10645     if (isa<CXXDestructorDecl>(NewCXXFD))
10646       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10647              << Destructors;
10648   }
10649 
10650   if (NewFD->isDeleted())
10651     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10652            << DeletedFuncs;
10653 
10654   if (NewFD->isDefaulted())
10655     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10656            << DefaultedFuncs;
10657 
10658   if (!ConstexprSupported && NewFD->isConstexpr())
10659     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10660            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10661 
10662   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10663   const auto *NewType = cast<FunctionType>(NewQType);
10664   QualType NewReturnType = NewType->getReturnType();
10665 
10666   if (NewReturnType->isUndeducedType())
10667     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10668            << DeducedReturn;
10669 
10670   // Ensure the return type is identical.
10671   if (OldFD) {
10672     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10673     const auto *OldType = cast<FunctionType>(OldQType);
10674     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10675     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10676 
10677     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10678       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10679 
10680     QualType OldReturnType = OldType->getReturnType();
10681 
10682     if (OldReturnType != NewReturnType)
10683       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10684 
10685     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10686       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10687 
10688     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10689       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10690 
10691     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10692       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10693 
10694     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10695       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10696 
10697     if (CheckEquivalentExceptionSpec(
10698             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10699             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10700       return true;
10701   }
10702   return false;
10703 }
10704 
10705 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10706                                              const FunctionDecl *NewFD,
10707                                              bool CausesMV,
10708                                              MultiVersionKind MVKind) {
10709   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10710     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10711     if (OldFD)
10712       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10713     return true;
10714   }
10715 
10716   bool IsCPUSpecificCPUDispatchMVKind =
10717       MVKind == MultiVersionKind::CPUDispatch ||
10718       MVKind == MultiVersionKind::CPUSpecific;
10719 
10720   if (CausesMV && OldFD &&
10721       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10722     return true;
10723 
10724   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10725     return true;
10726 
10727   // Only allow transition to MultiVersion if it hasn't been used.
10728   if (OldFD && CausesMV && OldFD->isUsed(false))
10729     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10730 
10731   return S.areMultiversionVariantFunctionsCompatible(
10732       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10733       PartialDiagnosticAt(NewFD->getLocation(),
10734                           S.PDiag(diag::note_multiversioning_caused_here)),
10735       PartialDiagnosticAt(NewFD->getLocation(),
10736                           S.PDiag(diag::err_multiversion_doesnt_support)
10737                               << static_cast<unsigned>(MVKind)),
10738       PartialDiagnosticAt(NewFD->getLocation(),
10739                           S.PDiag(diag::err_multiversion_diff)),
10740       /*TemplatesSupported=*/false,
10741       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10742       /*CLinkageMayDiffer=*/false);
10743 }
10744 
10745 /// Check the validity of a multiversion function declaration that is the
10746 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10747 ///
10748 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10749 ///
10750 /// Returns true if there was an error, false otherwise.
10751 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10752                                            MultiVersionKind MVKind,
10753                                            const TargetAttr *TA) {
10754   assert(MVKind != MultiVersionKind::None &&
10755          "Function lacks multiversion attribute");
10756 
10757   // Target only causes MV if it is default, otherwise this is a normal
10758   // function.
10759   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10760     return false;
10761 
10762   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10763     FD->setInvalidDecl();
10764     return true;
10765   }
10766 
10767   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10768     FD->setInvalidDecl();
10769     return true;
10770   }
10771 
10772   FD->setIsMultiVersion();
10773   return false;
10774 }
10775 
10776 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10777   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10778     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10779       return true;
10780   }
10781 
10782   return false;
10783 }
10784 
10785 static bool CheckTargetCausesMultiVersioning(
10786     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10787     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10788   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10789   ParsedTargetAttr NewParsed = NewTA->parse();
10790   // Sort order doesn't matter, it just needs to be consistent.
10791   llvm::sort(NewParsed.Features);
10792 
10793   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10794   // to change, this is a simple redeclaration.
10795   if (!NewTA->isDefaultVersion() &&
10796       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10797     return false;
10798 
10799   // Otherwise, this decl causes MultiVersioning.
10800   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10801                                        MultiVersionKind::Target)) {
10802     NewFD->setInvalidDecl();
10803     return true;
10804   }
10805 
10806   if (CheckMultiVersionValue(S, NewFD)) {
10807     NewFD->setInvalidDecl();
10808     return true;
10809   }
10810 
10811   // If this is 'default', permit the forward declaration.
10812   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10813     Redeclaration = true;
10814     OldDecl = OldFD;
10815     OldFD->setIsMultiVersion();
10816     NewFD->setIsMultiVersion();
10817     return false;
10818   }
10819 
10820   if (CheckMultiVersionValue(S, OldFD)) {
10821     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10822     NewFD->setInvalidDecl();
10823     return true;
10824   }
10825 
10826   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10827 
10828   if (OldParsed == NewParsed) {
10829     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10830     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10831     NewFD->setInvalidDecl();
10832     return true;
10833   }
10834 
10835   for (const auto *FD : OldFD->redecls()) {
10836     const auto *CurTA = FD->getAttr<TargetAttr>();
10837     // We allow forward declarations before ANY multiversioning attributes, but
10838     // nothing after the fact.
10839     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10840         (!CurTA || CurTA->isInherited())) {
10841       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10842           << 0;
10843       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10844       NewFD->setInvalidDecl();
10845       return true;
10846     }
10847   }
10848 
10849   OldFD->setIsMultiVersion();
10850   NewFD->setIsMultiVersion();
10851   Redeclaration = false;
10852   OldDecl = nullptr;
10853   Previous.clear();
10854   return false;
10855 }
10856 
10857 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10858                                         MultiVersionKind New) {
10859   if (Old == New || Old == MultiVersionKind::None ||
10860       New == MultiVersionKind::None)
10861     return true;
10862 
10863   return (Old == MultiVersionKind::CPUDispatch &&
10864           New == MultiVersionKind::CPUSpecific) ||
10865          (Old == MultiVersionKind::CPUSpecific &&
10866           New == MultiVersionKind::CPUDispatch);
10867 }
10868 
10869 /// Check the validity of a new function declaration being added to an existing
10870 /// multiversioned declaration collection.
10871 static bool CheckMultiVersionAdditionalDecl(
10872     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10873     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10874     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10875     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10876     LookupResult &Previous) {
10877 
10878   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10879   // Disallow mixing of multiversioning types.
10880   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10881     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10882     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10883     NewFD->setInvalidDecl();
10884     return true;
10885   }
10886 
10887   ParsedTargetAttr NewParsed;
10888   if (NewTA) {
10889     NewParsed = NewTA->parse();
10890     llvm::sort(NewParsed.Features);
10891   }
10892 
10893   bool UseMemberUsingDeclRules =
10894       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10895 
10896   bool MayNeedOverloadableChecks =
10897       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10898 
10899   // Next, check ALL non-overloads to see if this is a redeclaration of a
10900   // previous member of the MultiVersion set.
10901   for (NamedDecl *ND : Previous) {
10902     FunctionDecl *CurFD = ND->getAsFunction();
10903     if (!CurFD)
10904       continue;
10905     if (MayNeedOverloadableChecks &&
10906         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10907       continue;
10908 
10909     switch (NewMVKind) {
10910     case MultiVersionKind::None:
10911       assert(OldMVKind == MultiVersionKind::TargetClones &&
10912              "Only target_clones can be omitted in subsequent declarations");
10913       break;
10914     case MultiVersionKind::Target: {
10915       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10916       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10917         NewFD->setIsMultiVersion();
10918         Redeclaration = true;
10919         OldDecl = ND;
10920         return false;
10921       }
10922 
10923       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10924       if (CurParsed == NewParsed) {
10925         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10926         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10927         NewFD->setInvalidDecl();
10928         return true;
10929       }
10930       break;
10931     }
10932     case MultiVersionKind::TargetClones: {
10933       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10934       Redeclaration = true;
10935       OldDecl = CurFD;
10936       NewFD->setIsMultiVersion();
10937 
10938       if (CurClones && NewClones &&
10939           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10940            !std::equal(CurClones->featuresStrs_begin(),
10941                        CurClones->featuresStrs_end(),
10942                        NewClones->featuresStrs_begin()))) {
10943         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10944         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10945         NewFD->setInvalidDecl();
10946         return true;
10947       }
10948 
10949       return false;
10950     }
10951     case MultiVersionKind::CPUSpecific:
10952     case MultiVersionKind::CPUDispatch: {
10953       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10954       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10955       // Handle CPUDispatch/CPUSpecific versions.
10956       // Only 1 CPUDispatch function is allowed, this will make it go through
10957       // the redeclaration errors.
10958       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10959           CurFD->hasAttr<CPUDispatchAttr>()) {
10960         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10961             std::equal(
10962                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10963                 NewCPUDisp->cpus_begin(),
10964                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10965                   return Cur->getName() == New->getName();
10966                 })) {
10967           NewFD->setIsMultiVersion();
10968           Redeclaration = true;
10969           OldDecl = ND;
10970           return false;
10971         }
10972 
10973         // If the declarations don't match, this is an error condition.
10974         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10975         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10976         NewFD->setInvalidDecl();
10977         return true;
10978       }
10979       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10980         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10981             std::equal(
10982                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10983                 NewCPUSpec->cpus_begin(),
10984                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10985                   return Cur->getName() == New->getName();
10986                 })) {
10987           NewFD->setIsMultiVersion();
10988           Redeclaration = true;
10989           OldDecl = ND;
10990           return false;
10991         }
10992 
10993         // Only 1 version of CPUSpecific is allowed for each CPU.
10994         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10995           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10996             if (CurII == NewII) {
10997               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10998                   << NewII;
10999               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11000               NewFD->setInvalidDecl();
11001               return true;
11002             }
11003           }
11004         }
11005       }
11006       break;
11007     }
11008     }
11009   }
11010 
11011   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11012   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11013   // handled in the attribute adding step.
11014   if (NewMVKind == MultiVersionKind::Target &&
11015       CheckMultiVersionValue(S, NewFD)) {
11016     NewFD->setInvalidDecl();
11017     return true;
11018   }
11019 
11020   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11021                                        !OldFD->isMultiVersion(), NewMVKind)) {
11022     NewFD->setInvalidDecl();
11023     return true;
11024   }
11025 
11026   // Permit forward declarations in the case where these two are compatible.
11027   if (!OldFD->isMultiVersion()) {
11028     OldFD->setIsMultiVersion();
11029     NewFD->setIsMultiVersion();
11030     Redeclaration = true;
11031     OldDecl = OldFD;
11032     return false;
11033   }
11034 
11035   NewFD->setIsMultiVersion();
11036   Redeclaration = false;
11037   OldDecl = nullptr;
11038   Previous.clear();
11039   return false;
11040 }
11041 
11042 /// Check the validity of a mulitversion function declaration.
11043 /// Also sets the multiversion'ness' of the function itself.
11044 ///
11045 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11046 ///
11047 /// Returns true if there was an error, false otherwise.
11048 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11049                                       bool &Redeclaration, NamedDecl *&OldDecl,
11050                                       LookupResult &Previous) {
11051   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11052   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11053   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11054   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11055   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11056 
11057   // Main isn't allowed to become a multiversion function, however it IS
11058   // permitted to have 'main' be marked with the 'target' optimization hint.
11059   if (NewFD->isMain()) {
11060     if (MVKind != MultiVersionKind::None &&
11061         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11062       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11063       NewFD->setInvalidDecl();
11064       return true;
11065     }
11066     return false;
11067   }
11068 
11069   if (!OldDecl || !OldDecl->getAsFunction() ||
11070       OldDecl->getDeclContext()->getRedeclContext() !=
11071           NewFD->getDeclContext()->getRedeclContext()) {
11072     // If there's no previous declaration, AND this isn't attempting to cause
11073     // multiversioning, this isn't an error condition.
11074     if (MVKind == MultiVersionKind::None)
11075       return false;
11076     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11077   }
11078 
11079   FunctionDecl *OldFD = OldDecl->getAsFunction();
11080 
11081   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11082     return false;
11083 
11084   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11085   // for target_clones.
11086   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11087       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11088     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11089         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11090     NewFD->setInvalidDecl();
11091     return true;
11092   }
11093 
11094   if (!OldFD->isMultiVersion()) {
11095     switch (MVKind) {
11096     case MultiVersionKind::Target:
11097       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11098                                               Redeclaration, OldDecl, Previous);
11099     case MultiVersionKind::TargetClones:
11100       if (OldFD->isUsed(false)) {
11101         NewFD->setInvalidDecl();
11102         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11103       }
11104       OldFD->setIsMultiVersion();
11105       break;
11106     case MultiVersionKind::CPUDispatch:
11107     case MultiVersionKind::CPUSpecific:
11108     case MultiVersionKind::None:
11109       break;
11110     }
11111   }
11112 
11113   // At this point, we have a multiversion function decl (in OldFD) AND an
11114   // appropriate attribute in the current function decl.  Resolve that these are
11115   // still compatible with previous declarations.
11116   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11117                                          NewCPUDisp, NewCPUSpec, NewClones,
11118                                          Redeclaration, OldDecl, Previous);
11119 }
11120 
11121 /// Perform semantic checking of a new function declaration.
11122 ///
11123 /// Performs semantic analysis of the new function declaration
11124 /// NewFD. This routine performs all semantic checking that does not
11125 /// require the actual declarator involved in the declaration, and is
11126 /// used both for the declaration of functions as they are parsed
11127 /// (called via ActOnDeclarator) and for the declaration of functions
11128 /// that have been instantiated via C++ template instantiation (called
11129 /// via InstantiateDecl).
11130 ///
11131 /// \param IsMemberSpecialization whether this new function declaration is
11132 /// a member specialization (that replaces any definition provided by the
11133 /// previous declaration).
11134 ///
11135 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11136 ///
11137 /// \returns true if the function declaration is a redeclaration.
11138 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11139                                     LookupResult &Previous,
11140                                     bool IsMemberSpecialization,
11141                                     bool DeclIsDefn) {
11142   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11143          "Variably modified return types are not handled here");
11144 
11145   // Determine whether the type of this function should be merged with
11146   // a previous visible declaration. This never happens for functions in C++,
11147   // and always happens in C if the previous declaration was visible.
11148   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11149                                !Previous.isShadowed();
11150 
11151   bool Redeclaration = false;
11152   NamedDecl *OldDecl = nullptr;
11153   bool MayNeedOverloadableChecks = false;
11154 
11155   // Merge or overload the declaration with an existing declaration of
11156   // the same name, if appropriate.
11157   if (!Previous.empty()) {
11158     // Determine whether NewFD is an overload of PrevDecl or
11159     // a declaration that requires merging. If it's an overload,
11160     // there's no more work to do here; we'll just add the new
11161     // function to the scope.
11162     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11163       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11164       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11165         Redeclaration = true;
11166         OldDecl = Candidate;
11167       }
11168     } else {
11169       MayNeedOverloadableChecks = true;
11170       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11171                             /*NewIsUsingDecl*/ false)) {
11172       case Ovl_Match:
11173         Redeclaration = true;
11174         break;
11175 
11176       case Ovl_NonFunction:
11177         Redeclaration = true;
11178         break;
11179 
11180       case Ovl_Overload:
11181         Redeclaration = false;
11182         break;
11183       }
11184     }
11185   }
11186 
11187   // Check for a previous extern "C" declaration with this name.
11188   if (!Redeclaration &&
11189       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11190     if (!Previous.empty()) {
11191       // This is an extern "C" declaration with the same name as a previous
11192       // declaration, and thus redeclares that entity...
11193       Redeclaration = true;
11194       OldDecl = Previous.getFoundDecl();
11195       MergeTypeWithPrevious = false;
11196 
11197       // ... except in the presence of __attribute__((overloadable)).
11198       if (OldDecl->hasAttr<OverloadableAttr>() ||
11199           NewFD->hasAttr<OverloadableAttr>()) {
11200         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11201           MayNeedOverloadableChecks = true;
11202           Redeclaration = false;
11203           OldDecl = nullptr;
11204         }
11205       }
11206     }
11207   }
11208 
11209   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11210     return Redeclaration;
11211 
11212   // PPC MMA non-pointer types are not allowed as function return types.
11213   if (Context.getTargetInfo().getTriple().isPPC64() &&
11214       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11215     NewFD->setInvalidDecl();
11216   }
11217 
11218   // C++11 [dcl.constexpr]p8:
11219   //   A constexpr specifier for a non-static member function that is not
11220   //   a constructor declares that member function to be const.
11221   //
11222   // This needs to be delayed until we know whether this is an out-of-line
11223   // definition of a static member function.
11224   //
11225   // This rule is not present in C++1y, so we produce a backwards
11226   // compatibility warning whenever it happens in C++11.
11227   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11228   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11229       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11230       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11231     CXXMethodDecl *OldMD = nullptr;
11232     if (OldDecl)
11233       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11234     if (!OldMD || !OldMD->isStatic()) {
11235       const FunctionProtoType *FPT =
11236         MD->getType()->castAs<FunctionProtoType>();
11237       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11238       EPI.TypeQuals.addConst();
11239       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11240                                           FPT->getParamTypes(), EPI));
11241 
11242       // Warn that we did this, if we're not performing template instantiation.
11243       // In that case, we'll have warned already when the template was defined.
11244       if (!inTemplateInstantiation()) {
11245         SourceLocation AddConstLoc;
11246         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11247                 .IgnoreParens().getAs<FunctionTypeLoc>())
11248           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11249 
11250         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11251           << FixItHint::CreateInsertion(AddConstLoc, " const");
11252       }
11253     }
11254   }
11255 
11256   if (Redeclaration) {
11257     // NewFD and OldDecl represent declarations that need to be
11258     // merged.
11259     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11260                           DeclIsDefn)) {
11261       NewFD->setInvalidDecl();
11262       return Redeclaration;
11263     }
11264 
11265     Previous.clear();
11266     Previous.addDecl(OldDecl);
11267 
11268     if (FunctionTemplateDecl *OldTemplateDecl =
11269             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11270       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11271       FunctionTemplateDecl *NewTemplateDecl
11272         = NewFD->getDescribedFunctionTemplate();
11273       assert(NewTemplateDecl && "Template/non-template mismatch");
11274 
11275       // The call to MergeFunctionDecl above may have created some state in
11276       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11277       // can add it as a redeclaration.
11278       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11279 
11280       NewFD->setPreviousDeclaration(OldFD);
11281       if (NewFD->isCXXClassMember()) {
11282         NewFD->setAccess(OldTemplateDecl->getAccess());
11283         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11284       }
11285 
11286       // If this is an explicit specialization of a member that is a function
11287       // template, mark it as a member specialization.
11288       if (IsMemberSpecialization &&
11289           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11290         NewTemplateDecl->setMemberSpecialization();
11291         assert(OldTemplateDecl->isMemberSpecialization());
11292         // Explicit specializations of a member template do not inherit deleted
11293         // status from the parent member template that they are specializing.
11294         if (OldFD->isDeleted()) {
11295           // FIXME: This assert will not hold in the presence of modules.
11296           assert(OldFD->getCanonicalDecl() == OldFD);
11297           // FIXME: We need an update record for this AST mutation.
11298           OldFD->setDeletedAsWritten(false);
11299         }
11300       }
11301 
11302     } else {
11303       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11304         auto *OldFD = cast<FunctionDecl>(OldDecl);
11305         // This needs to happen first so that 'inline' propagates.
11306         NewFD->setPreviousDeclaration(OldFD);
11307         if (NewFD->isCXXClassMember())
11308           NewFD->setAccess(OldFD->getAccess());
11309       }
11310     }
11311   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11312              !NewFD->getAttr<OverloadableAttr>()) {
11313     assert((Previous.empty() ||
11314             llvm::any_of(Previous,
11315                          [](const NamedDecl *ND) {
11316                            return ND->hasAttr<OverloadableAttr>();
11317                          })) &&
11318            "Non-redecls shouldn't happen without overloadable present");
11319 
11320     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11321       const auto *FD = dyn_cast<FunctionDecl>(ND);
11322       return FD && !FD->hasAttr<OverloadableAttr>();
11323     });
11324 
11325     if (OtherUnmarkedIter != Previous.end()) {
11326       Diag(NewFD->getLocation(),
11327            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11328       Diag((*OtherUnmarkedIter)->getLocation(),
11329            diag::note_attribute_overloadable_prev_overload)
11330           << false;
11331 
11332       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11333     }
11334   }
11335 
11336   if (LangOpts.OpenMP)
11337     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11338 
11339   // Semantic checking for this function declaration (in isolation).
11340 
11341   if (getLangOpts().CPlusPlus) {
11342     // C++-specific checks.
11343     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11344       CheckConstructor(Constructor);
11345     } else if (CXXDestructorDecl *Destructor =
11346                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11347       CXXRecordDecl *Record = Destructor->getParent();
11348       QualType ClassType = Context.getTypeDeclType(Record);
11349 
11350       // FIXME: Shouldn't we be able to perform this check even when the class
11351       // type is dependent? Both gcc and edg can handle that.
11352       if (!ClassType->isDependentType()) {
11353         DeclarationName Name
11354           = Context.DeclarationNames.getCXXDestructorName(
11355                                         Context.getCanonicalType(ClassType));
11356         if (NewFD->getDeclName() != Name) {
11357           Diag(NewFD->getLocation(), diag::err_destructor_name);
11358           NewFD->setInvalidDecl();
11359           return Redeclaration;
11360         }
11361       }
11362     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11363       if (auto *TD = Guide->getDescribedFunctionTemplate())
11364         CheckDeductionGuideTemplate(TD);
11365 
11366       // A deduction guide is not on the list of entities that can be
11367       // explicitly specialized.
11368       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11369         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11370             << /*explicit specialization*/ 1;
11371     }
11372 
11373     // Find any virtual functions that this function overrides.
11374     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11375       if (!Method->isFunctionTemplateSpecialization() &&
11376           !Method->getDescribedFunctionTemplate() &&
11377           Method->isCanonicalDecl()) {
11378         AddOverriddenMethods(Method->getParent(), Method);
11379       }
11380       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11381         // C++2a [class.virtual]p6
11382         // A virtual method shall not have a requires-clause.
11383         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11384              diag::err_constrained_virtual_method);
11385 
11386       if (Method->isStatic())
11387         checkThisInStaticMemberFunctionType(Method);
11388     }
11389 
11390     // C++20: dcl.decl.general p4:
11391     // The optional requires-clause ([temp.pre]) in an init-declarator or
11392     // member-declarator shall be present only if the declarator declares a
11393     // templated function ([dcl.fct]).
11394     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11395       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11396         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11397     }
11398 
11399     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11400       ActOnConversionDeclarator(Conversion);
11401 
11402     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11403     if (NewFD->isOverloadedOperator() &&
11404         CheckOverloadedOperatorDeclaration(NewFD)) {
11405       NewFD->setInvalidDecl();
11406       return Redeclaration;
11407     }
11408 
11409     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11410     if (NewFD->getLiteralIdentifier() &&
11411         CheckLiteralOperatorDeclaration(NewFD)) {
11412       NewFD->setInvalidDecl();
11413       return Redeclaration;
11414     }
11415 
11416     // In C++, check default arguments now that we have merged decls. Unless
11417     // the lexical context is the class, because in this case this is done
11418     // during delayed parsing anyway.
11419     if (!CurContext->isRecord())
11420       CheckCXXDefaultArguments(NewFD);
11421 
11422     // If this function is declared as being extern "C", then check to see if
11423     // the function returns a UDT (class, struct, or union type) that is not C
11424     // compatible, and if it does, warn the user.
11425     // But, issue any diagnostic on the first declaration only.
11426     if (Previous.empty() && NewFD->isExternC()) {
11427       QualType R = NewFD->getReturnType();
11428       if (R->isIncompleteType() && !R->isVoidType())
11429         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11430             << NewFD << R;
11431       else if (!R.isPODType(Context) && !R->isVoidType() &&
11432                !R->isObjCObjectPointerType())
11433         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11434     }
11435 
11436     // C++1z [dcl.fct]p6:
11437     //   [...] whether the function has a non-throwing exception-specification
11438     //   [is] part of the function type
11439     //
11440     // This results in an ABI break between C++14 and C++17 for functions whose
11441     // declared type includes an exception-specification in a parameter or
11442     // return type. (Exception specifications on the function itself are OK in
11443     // most cases, and exception specifications are not permitted in most other
11444     // contexts where they could make it into a mangling.)
11445     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11446       auto HasNoexcept = [&](QualType T) -> bool {
11447         // Strip off declarator chunks that could be between us and a function
11448         // type. We don't need to look far, exception specifications are very
11449         // restricted prior to C++17.
11450         if (auto *RT = T->getAs<ReferenceType>())
11451           T = RT->getPointeeType();
11452         else if (T->isAnyPointerType())
11453           T = T->getPointeeType();
11454         else if (auto *MPT = T->getAs<MemberPointerType>())
11455           T = MPT->getPointeeType();
11456         if (auto *FPT = T->getAs<FunctionProtoType>())
11457           if (FPT->isNothrow())
11458             return true;
11459         return false;
11460       };
11461 
11462       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11463       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11464       for (QualType T : FPT->param_types())
11465         AnyNoexcept |= HasNoexcept(T);
11466       if (AnyNoexcept)
11467         Diag(NewFD->getLocation(),
11468              diag::warn_cxx17_compat_exception_spec_in_signature)
11469             << NewFD;
11470     }
11471 
11472     if (!Redeclaration && LangOpts.CUDA)
11473       checkCUDATargetOverload(NewFD, Previous);
11474   }
11475   return Redeclaration;
11476 }
11477 
11478 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11479   // C++11 [basic.start.main]p3:
11480   //   A program that [...] declares main to be inline, static or
11481   //   constexpr is ill-formed.
11482   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11483   //   appear in a declaration of main.
11484   // static main is not an error under C99, but we should warn about it.
11485   // We accept _Noreturn main as an extension.
11486   if (FD->getStorageClass() == SC_Static)
11487     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11488          ? diag::err_static_main : diag::warn_static_main)
11489       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11490   if (FD->isInlineSpecified())
11491     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11492       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11493   if (DS.isNoreturnSpecified()) {
11494     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11495     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11496     Diag(NoreturnLoc, diag::ext_noreturn_main);
11497     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11498       << FixItHint::CreateRemoval(NoreturnRange);
11499   }
11500   if (FD->isConstexpr()) {
11501     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11502         << FD->isConsteval()
11503         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11504     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11505   }
11506 
11507   if (getLangOpts().OpenCL) {
11508     Diag(FD->getLocation(), diag::err_opencl_no_main)
11509         << FD->hasAttr<OpenCLKernelAttr>();
11510     FD->setInvalidDecl();
11511     return;
11512   }
11513 
11514   // Functions named main in hlsl are default entries, but don't have specific
11515   // signatures they are required to conform to.
11516   if (getLangOpts().HLSL)
11517     return;
11518 
11519   QualType T = FD->getType();
11520   assert(T->isFunctionType() && "function decl is not of function type");
11521   const FunctionType* FT = T->castAs<FunctionType>();
11522 
11523   // Set default calling convention for main()
11524   if (FT->getCallConv() != CC_C) {
11525     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11526     FD->setType(QualType(FT, 0));
11527     T = Context.getCanonicalType(FD->getType());
11528   }
11529 
11530   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11531     // In C with GNU extensions we allow main() to have non-integer return
11532     // type, but we should warn about the extension, and we disable the
11533     // implicit-return-zero rule.
11534 
11535     // GCC in C mode accepts qualified 'int'.
11536     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11537       FD->setHasImplicitReturnZero(true);
11538     else {
11539       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11540       SourceRange RTRange = FD->getReturnTypeSourceRange();
11541       if (RTRange.isValid())
11542         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11543             << FixItHint::CreateReplacement(RTRange, "int");
11544     }
11545   } else {
11546     // In C and C++, main magically returns 0 if you fall off the end;
11547     // set the flag which tells us that.
11548     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11549 
11550     // All the standards say that main() should return 'int'.
11551     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11552       FD->setHasImplicitReturnZero(true);
11553     else {
11554       // Otherwise, this is just a flat-out error.
11555       SourceRange RTRange = FD->getReturnTypeSourceRange();
11556       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11557           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11558                                 : FixItHint());
11559       FD->setInvalidDecl(true);
11560     }
11561   }
11562 
11563   // Treat protoless main() as nullary.
11564   if (isa<FunctionNoProtoType>(FT)) return;
11565 
11566   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11567   unsigned nparams = FTP->getNumParams();
11568   assert(FD->getNumParams() == nparams);
11569 
11570   bool HasExtraParameters = (nparams > 3);
11571 
11572   if (FTP->isVariadic()) {
11573     Diag(FD->getLocation(), diag::ext_variadic_main);
11574     // FIXME: if we had information about the location of the ellipsis, we
11575     // could add a FixIt hint to remove it as a parameter.
11576   }
11577 
11578   // Darwin passes an undocumented fourth argument of type char**.  If
11579   // other platforms start sprouting these, the logic below will start
11580   // getting shifty.
11581   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11582     HasExtraParameters = false;
11583 
11584   if (HasExtraParameters) {
11585     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11586     FD->setInvalidDecl(true);
11587     nparams = 3;
11588   }
11589 
11590   // FIXME: a lot of the following diagnostics would be improved
11591   // if we had some location information about types.
11592 
11593   QualType CharPP =
11594     Context.getPointerType(Context.getPointerType(Context.CharTy));
11595   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11596 
11597   for (unsigned i = 0; i < nparams; ++i) {
11598     QualType AT = FTP->getParamType(i);
11599 
11600     bool mismatch = true;
11601 
11602     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11603       mismatch = false;
11604     else if (Expected[i] == CharPP) {
11605       // As an extension, the following forms are okay:
11606       //   char const **
11607       //   char const * const *
11608       //   char * const *
11609 
11610       QualifierCollector qs;
11611       const PointerType* PT;
11612       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11613           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11614           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11615                               Context.CharTy)) {
11616         qs.removeConst();
11617         mismatch = !qs.empty();
11618       }
11619     }
11620 
11621     if (mismatch) {
11622       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11623       // TODO: suggest replacing given type with expected type
11624       FD->setInvalidDecl(true);
11625     }
11626   }
11627 
11628   if (nparams == 1 && !FD->isInvalidDecl()) {
11629     Diag(FD->getLocation(), diag::warn_main_one_arg);
11630   }
11631 
11632   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11633     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11634     FD->setInvalidDecl();
11635   }
11636 }
11637 
11638 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11639 
11640   // Default calling convention for main and wmain is __cdecl
11641   if (FD->getName() == "main" || FD->getName() == "wmain")
11642     return false;
11643 
11644   // Default calling convention for MinGW is __cdecl
11645   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11646   if (T.isWindowsGNUEnvironment())
11647     return false;
11648 
11649   // Default calling convention for WinMain, wWinMain and DllMain
11650   // is __stdcall on 32 bit Windows
11651   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11652     return true;
11653 
11654   return false;
11655 }
11656 
11657 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11658   QualType T = FD->getType();
11659   assert(T->isFunctionType() && "function decl is not of function type");
11660   const FunctionType *FT = T->castAs<FunctionType>();
11661 
11662   // Set an implicit return of 'zero' if the function can return some integral,
11663   // enumeration, pointer or nullptr type.
11664   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11665       FT->getReturnType()->isAnyPointerType() ||
11666       FT->getReturnType()->isNullPtrType())
11667     // DllMain is exempt because a return value of zero means it failed.
11668     if (FD->getName() != "DllMain")
11669       FD->setHasImplicitReturnZero(true);
11670 
11671   // Explicity specified calling conventions are applied to MSVC entry points
11672   if (!hasExplicitCallingConv(T)) {
11673     if (isDefaultStdCall(FD, *this)) {
11674       if (FT->getCallConv() != CC_X86StdCall) {
11675         FT = Context.adjustFunctionType(
11676             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11677         FD->setType(QualType(FT, 0));
11678       }
11679     } else if (FT->getCallConv() != CC_C) {
11680       FT = Context.adjustFunctionType(FT,
11681                                       FT->getExtInfo().withCallingConv(CC_C));
11682       FD->setType(QualType(FT, 0));
11683     }
11684   }
11685 
11686   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11687     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11688     FD->setInvalidDecl();
11689   }
11690 }
11691 
11692 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11693   // FIXME: Need strict checking.  In C89, we need to check for
11694   // any assignment, increment, decrement, function-calls, or
11695   // commas outside of a sizeof.  In C99, it's the same list,
11696   // except that the aforementioned are allowed in unevaluated
11697   // expressions.  Everything else falls under the
11698   // "may accept other forms of constant expressions" exception.
11699   //
11700   // Regular C++ code will not end up here (exceptions: language extensions,
11701   // OpenCL C++ etc), so the constant expression rules there don't matter.
11702   if (Init->isValueDependent()) {
11703     assert(Init->containsErrors() &&
11704            "Dependent code should only occur in error-recovery path.");
11705     return true;
11706   }
11707   const Expr *Culprit;
11708   if (Init->isConstantInitializer(Context, false, &Culprit))
11709     return false;
11710   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11711     << Culprit->getSourceRange();
11712   return true;
11713 }
11714 
11715 namespace {
11716   // Visits an initialization expression to see if OrigDecl is evaluated in
11717   // its own initialization and throws a warning if it does.
11718   class SelfReferenceChecker
11719       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11720     Sema &S;
11721     Decl *OrigDecl;
11722     bool isRecordType;
11723     bool isPODType;
11724     bool isReferenceType;
11725 
11726     bool isInitList;
11727     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11728 
11729   public:
11730     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11731 
11732     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11733                                                     S(S), OrigDecl(OrigDecl) {
11734       isPODType = false;
11735       isRecordType = false;
11736       isReferenceType = false;
11737       isInitList = false;
11738       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11739         isPODType = VD->getType().isPODType(S.Context);
11740         isRecordType = VD->getType()->isRecordType();
11741         isReferenceType = VD->getType()->isReferenceType();
11742       }
11743     }
11744 
11745     // For most expressions, just call the visitor.  For initializer lists,
11746     // track the index of the field being initialized since fields are
11747     // initialized in order allowing use of previously initialized fields.
11748     void CheckExpr(Expr *E) {
11749       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11750       if (!InitList) {
11751         Visit(E);
11752         return;
11753       }
11754 
11755       // Track and increment the index here.
11756       isInitList = true;
11757       InitFieldIndex.push_back(0);
11758       for (auto Child : InitList->children()) {
11759         CheckExpr(cast<Expr>(Child));
11760         ++InitFieldIndex.back();
11761       }
11762       InitFieldIndex.pop_back();
11763     }
11764 
11765     // Returns true if MemberExpr is checked and no further checking is needed.
11766     // Returns false if additional checking is required.
11767     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11768       llvm::SmallVector<FieldDecl*, 4> Fields;
11769       Expr *Base = E;
11770       bool ReferenceField = false;
11771 
11772       // Get the field members used.
11773       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11774         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11775         if (!FD)
11776           return false;
11777         Fields.push_back(FD);
11778         if (FD->getType()->isReferenceType())
11779           ReferenceField = true;
11780         Base = ME->getBase()->IgnoreParenImpCasts();
11781       }
11782 
11783       // Keep checking only if the base Decl is the same.
11784       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11785       if (!DRE || DRE->getDecl() != OrigDecl)
11786         return false;
11787 
11788       // A reference field can be bound to an unininitialized field.
11789       if (CheckReference && !ReferenceField)
11790         return true;
11791 
11792       // Convert FieldDecls to their index number.
11793       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11794       for (const FieldDecl *I : llvm::reverse(Fields))
11795         UsedFieldIndex.push_back(I->getFieldIndex());
11796 
11797       // See if a warning is needed by checking the first difference in index
11798       // numbers.  If field being used has index less than the field being
11799       // initialized, then the use is safe.
11800       for (auto UsedIter = UsedFieldIndex.begin(),
11801                 UsedEnd = UsedFieldIndex.end(),
11802                 OrigIter = InitFieldIndex.begin(),
11803                 OrigEnd = InitFieldIndex.end();
11804            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11805         if (*UsedIter < *OrigIter)
11806           return true;
11807         if (*UsedIter > *OrigIter)
11808           break;
11809       }
11810 
11811       // TODO: Add a different warning which will print the field names.
11812       HandleDeclRefExpr(DRE);
11813       return true;
11814     }
11815 
11816     // For most expressions, the cast is directly above the DeclRefExpr.
11817     // For conditional operators, the cast can be outside the conditional
11818     // operator if both expressions are DeclRefExpr's.
11819     void HandleValue(Expr *E) {
11820       E = E->IgnoreParens();
11821       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11822         HandleDeclRefExpr(DRE);
11823         return;
11824       }
11825 
11826       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11827         Visit(CO->getCond());
11828         HandleValue(CO->getTrueExpr());
11829         HandleValue(CO->getFalseExpr());
11830         return;
11831       }
11832 
11833       if (BinaryConditionalOperator *BCO =
11834               dyn_cast<BinaryConditionalOperator>(E)) {
11835         Visit(BCO->getCond());
11836         HandleValue(BCO->getFalseExpr());
11837         return;
11838       }
11839 
11840       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11841         HandleValue(OVE->getSourceExpr());
11842         return;
11843       }
11844 
11845       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11846         if (BO->getOpcode() == BO_Comma) {
11847           Visit(BO->getLHS());
11848           HandleValue(BO->getRHS());
11849           return;
11850         }
11851       }
11852 
11853       if (isa<MemberExpr>(E)) {
11854         if (isInitList) {
11855           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11856                                       false /*CheckReference*/))
11857             return;
11858         }
11859 
11860         Expr *Base = E->IgnoreParenImpCasts();
11861         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11862           // Check for static member variables and don't warn on them.
11863           if (!isa<FieldDecl>(ME->getMemberDecl()))
11864             return;
11865           Base = ME->getBase()->IgnoreParenImpCasts();
11866         }
11867         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11868           HandleDeclRefExpr(DRE);
11869         return;
11870       }
11871 
11872       Visit(E);
11873     }
11874 
11875     // Reference types not handled in HandleValue are handled here since all
11876     // uses of references are bad, not just r-value uses.
11877     void VisitDeclRefExpr(DeclRefExpr *E) {
11878       if (isReferenceType)
11879         HandleDeclRefExpr(E);
11880     }
11881 
11882     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11883       if (E->getCastKind() == CK_LValueToRValue) {
11884         HandleValue(E->getSubExpr());
11885         return;
11886       }
11887 
11888       Inherited::VisitImplicitCastExpr(E);
11889     }
11890 
11891     void VisitMemberExpr(MemberExpr *E) {
11892       if (isInitList) {
11893         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11894           return;
11895       }
11896 
11897       // Don't warn on arrays since they can be treated as pointers.
11898       if (E->getType()->canDecayToPointerType()) return;
11899 
11900       // Warn when a non-static method call is followed by non-static member
11901       // field accesses, which is followed by a DeclRefExpr.
11902       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11903       bool Warn = (MD && !MD->isStatic());
11904       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11905       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11906         if (!isa<FieldDecl>(ME->getMemberDecl()))
11907           Warn = false;
11908         Base = ME->getBase()->IgnoreParenImpCasts();
11909       }
11910 
11911       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11912         if (Warn)
11913           HandleDeclRefExpr(DRE);
11914         return;
11915       }
11916 
11917       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11918       // Visit that expression.
11919       Visit(Base);
11920     }
11921 
11922     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11923       Expr *Callee = E->getCallee();
11924 
11925       if (isa<UnresolvedLookupExpr>(Callee))
11926         return Inherited::VisitCXXOperatorCallExpr(E);
11927 
11928       Visit(Callee);
11929       for (auto Arg: E->arguments())
11930         HandleValue(Arg->IgnoreParenImpCasts());
11931     }
11932 
11933     void VisitUnaryOperator(UnaryOperator *E) {
11934       // For POD record types, addresses of its own members are well-defined.
11935       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11936           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11937         if (!isPODType)
11938           HandleValue(E->getSubExpr());
11939         return;
11940       }
11941 
11942       if (E->isIncrementDecrementOp()) {
11943         HandleValue(E->getSubExpr());
11944         return;
11945       }
11946 
11947       Inherited::VisitUnaryOperator(E);
11948     }
11949 
11950     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11951 
11952     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11953       if (E->getConstructor()->isCopyConstructor()) {
11954         Expr *ArgExpr = E->getArg(0);
11955         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11956           if (ILE->getNumInits() == 1)
11957             ArgExpr = ILE->getInit(0);
11958         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11959           if (ICE->getCastKind() == CK_NoOp)
11960             ArgExpr = ICE->getSubExpr();
11961         HandleValue(ArgExpr);
11962         return;
11963       }
11964       Inherited::VisitCXXConstructExpr(E);
11965     }
11966 
11967     void VisitCallExpr(CallExpr *E) {
11968       // Treat std::move as a use.
11969       if (E->isCallToStdMove()) {
11970         HandleValue(E->getArg(0));
11971         return;
11972       }
11973 
11974       Inherited::VisitCallExpr(E);
11975     }
11976 
11977     void VisitBinaryOperator(BinaryOperator *E) {
11978       if (E->isCompoundAssignmentOp()) {
11979         HandleValue(E->getLHS());
11980         Visit(E->getRHS());
11981         return;
11982       }
11983 
11984       Inherited::VisitBinaryOperator(E);
11985     }
11986 
11987     // A custom visitor for BinaryConditionalOperator is needed because the
11988     // regular visitor would check the condition and true expression separately
11989     // but both point to the same place giving duplicate diagnostics.
11990     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11991       Visit(E->getCond());
11992       Visit(E->getFalseExpr());
11993     }
11994 
11995     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11996       Decl* ReferenceDecl = DRE->getDecl();
11997       if (OrigDecl != ReferenceDecl) return;
11998       unsigned diag;
11999       if (isReferenceType) {
12000         diag = diag::warn_uninit_self_reference_in_reference_init;
12001       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12002         diag = diag::warn_static_self_reference_in_init;
12003       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12004                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12005                  DRE->getDecl()->getType()->isRecordType()) {
12006         diag = diag::warn_uninit_self_reference_in_init;
12007       } else {
12008         // Local variables will be handled by the CFG analysis.
12009         return;
12010       }
12011 
12012       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12013                             S.PDiag(diag)
12014                                 << DRE->getDecl() << OrigDecl->getLocation()
12015                                 << DRE->getSourceRange());
12016     }
12017   };
12018 
12019   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12020   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12021                                  bool DirectInit) {
12022     // Parameters arguments are occassionially constructed with itself,
12023     // for instance, in recursive functions.  Skip them.
12024     if (isa<ParmVarDecl>(OrigDecl))
12025       return;
12026 
12027     E = E->IgnoreParens();
12028 
12029     // Skip checking T a = a where T is not a record or reference type.
12030     // Doing so is a way to silence uninitialized warnings.
12031     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12032       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12033         if (ICE->getCastKind() == CK_LValueToRValue)
12034           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12035             if (DRE->getDecl() == OrigDecl)
12036               return;
12037 
12038     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12039   }
12040 } // end anonymous namespace
12041 
12042 namespace {
12043   // Simple wrapper to add the name of a variable or (if no variable is
12044   // available) a DeclarationName into a diagnostic.
12045   struct VarDeclOrName {
12046     VarDecl *VDecl;
12047     DeclarationName Name;
12048 
12049     friend const Sema::SemaDiagnosticBuilder &
12050     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12051       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12052     }
12053   };
12054 } // end anonymous namespace
12055 
12056 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12057                                             DeclarationName Name, QualType Type,
12058                                             TypeSourceInfo *TSI,
12059                                             SourceRange Range, bool DirectInit,
12060                                             Expr *Init) {
12061   bool IsInitCapture = !VDecl;
12062   assert((!VDecl || !VDecl->isInitCapture()) &&
12063          "init captures are expected to be deduced prior to initialization");
12064 
12065   VarDeclOrName VN{VDecl, Name};
12066 
12067   DeducedType *Deduced = Type->getContainedDeducedType();
12068   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12069 
12070   // C++11 [dcl.spec.auto]p3
12071   if (!Init) {
12072     assert(VDecl && "no init for init capture deduction?");
12073 
12074     // Except for class argument deduction, and then for an initializing
12075     // declaration only, i.e. no static at class scope or extern.
12076     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12077         VDecl->hasExternalStorage() ||
12078         VDecl->isStaticDataMember()) {
12079       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12080         << VDecl->getDeclName() << Type;
12081       return QualType();
12082     }
12083   }
12084 
12085   ArrayRef<Expr*> DeduceInits;
12086   if (Init)
12087     DeduceInits = Init;
12088 
12089   if (DirectInit) {
12090     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12091       DeduceInits = PL->exprs();
12092   }
12093 
12094   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12095     assert(VDecl && "non-auto type for init capture deduction?");
12096     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12097     InitializationKind Kind = InitializationKind::CreateForInit(
12098         VDecl->getLocation(), DirectInit, Init);
12099     // FIXME: Initialization should not be taking a mutable list of inits.
12100     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12101     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12102                                                        InitsCopy);
12103   }
12104 
12105   if (DirectInit) {
12106     if (auto *IL = dyn_cast<InitListExpr>(Init))
12107       DeduceInits = IL->inits();
12108   }
12109 
12110   // Deduction only works if we have exactly one source expression.
12111   if (DeduceInits.empty()) {
12112     // It isn't possible to write this directly, but it is possible to
12113     // end up in this situation with "auto x(some_pack...);"
12114     Diag(Init->getBeginLoc(), IsInitCapture
12115                                   ? diag::err_init_capture_no_expression
12116                                   : diag::err_auto_var_init_no_expression)
12117         << VN << Type << Range;
12118     return QualType();
12119   }
12120 
12121   if (DeduceInits.size() > 1) {
12122     Diag(DeduceInits[1]->getBeginLoc(),
12123          IsInitCapture ? diag::err_init_capture_multiple_expressions
12124                        : diag::err_auto_var_init_multiple_expressions)
12125         << VN << Type << Range;
12126     return QualType();
12127   }
12128 
12129   Expr *DeduceInit = DeduceInits[0];
12130   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12131     Diag(Init->getBeginLoc(), IsInitCapture
12132                                   ? diag::err_init_capture_paren_braces
12133                                   : diag::err_auto_var_init_paren_braces)
12134         << isa<InitListExpr>(Init) << VN << Type << Range;
12135     return QualType();
12136   }
12137 
12138   // Expressions default to 'id' when we're in a debugger.
12139   bool DefaultedAnyToId = false;
12140   if (getLangOpts().DebuggerCastResultToId &&
12141       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12142     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12143     if (Result.isInvalid()) {
12144       return QualType();
12145     }
12146     Init = Result.get();
12147     DefaultedAnyToId = true;
12148   }
12149 
12150   // C++ [dcl.decomp]p1:
12151   //   If the assignment-expression [...] has array type A and no ref-qualifier
12152   //   is present, e has type cv A
12153   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12154       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12155       DeduceInit->getType()->isConstantArrayType())
12156     return Context.getQualifiedType(DeduceInit->getType(),
12157                                     Type.getQualifiers());
12158 
12159   QualType DeducedType;
12160   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12161     if (!IsInitCapture)
12162       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12163     else if (isa<InitListExpr>(Init))
12164       Diag(Range.getBegin(),
12165            diag::err_init_capture_deduction_failure_from_init_list)
12166           << VN
12167           << (DeduceInit->getType().isNull() ? TSI->getType()
12168                                              : DeduceInit->getType())
12169           << DeduceInit->getSourceRange();
12170     else
12171       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12172           << VN << TSI->getType()
12173           << (DeduceInit->getType().isNull() ? TSI->getType()
12174                                              : DeduceInit->getType())
12175           << DeduceInit->getSourceRange();
12176   }
12177 
12178   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12179   // 'id' instead of a specific object type prevents most of our usual
12180   // checks.
12181   // We only want to warn outside of template instantiations, though:
12182   // inside a template, the 'id' could have come from a parameter.
12183   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12184       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12185     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12186     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12187   }
12188 
12189   return DeducedType;
12190 }
12191 
12192 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12193                                          Expr *Init) {
12194   assert(!Init || !Init->containsErrors());
12195   QualType DeducedType = deduceVarTypeFromInitializer(
12196       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12197       VDecl->getSourceRange(), DirectInit, Init);
12198   if (DeducedType.isNull()) {
12199     VDecl->setInvalidDecl();
12200     return true;
12201   }
12202 
12203   VDecl->setType(DeducedType);
12204   assert(VDecl->isLinkageValid());
12205 
12206   // In ARC, infer lifetime.
12207   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12208     VDecl->setInvalidDecl();
12209 
12210   if (getLangOpts().OpenCL)
12211     deduceOpenCLAddressSpace(VDecl);
12212 
12213   // If this is a redeclaration, check that the type we just deduced matches
12214   // the previously declared type.
12215   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12216     // We never need to merge the type, because we cannot form an incomplete
12217     // array of auto, nor deduce such a type.
12218     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12219   }
12220 
12221   // Check the deduced type is valid for a variable declaration.
12222   CheckVariableDeclarationType(VDecl);
12223   return VDecl->isInvalidDecl();
12224 }
12225 
12226 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12227                                               SourceLocation Loc) {
12228   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12229     Init = EWC->getSubExpr();
12230 
12231   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12232     Init = CE->getSubExpr();
12233 
12234   QualType InitType = Init->getType();
12235   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12236           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12237          "shouldn't be called if type doesn't have a non-trivial C struct");
12238   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12239     for (auto I : ILE->inits()) {
12240       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12241           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12242         continue;
12243       SourceLocation SL = I->getExprLoc();
12244       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12245     }
12246     return;
12247   }
12248 
12249   if (isa<ImplicitValueInitExpr>(Init)) {
12250     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12251       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12252                             NTCUK_Init);
12253   } else {
12254     // Assume all other explicit initializers involving copying some existing
12255     // object.
12256     // TODO: ignore any explicit initializers where we can guarantee
12257     // copy-elision.
12258     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12259       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12260   }
12261 }
12262 
12263 namespace {
12264 
12265 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12266   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12267   // in the source code or implicitly by the compiler if it is in a union
12268   // defined in a system header and has non-trivial ObjC ownership
12269   // qualifications. We don't want those fields to participate in determining
12270   // whether the containing union is non-trivial.
12271   return FD->hasAttr<UnavailableAttr>();
12272 }
12273 
12274 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12275     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12276                                     void> {
12277   using Super =
12278       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12279                                     void>;
12280 
12281   DiagNonTrivalCUnionDefaultInitializeVisitor(
12282       QualType OrigTy, SourceLocation OrigLoc,
12283       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12284       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12285 
12286   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12287                      const FieldDecl *FD, bool InNonTrivialUnion) {
12288     if (const auto *AT = S.Context.getAsArrayType(QT))
12289       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12290                                      InNonTrivialUnion);
12291     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12292   }
12293 
12294   void visitARCStrong(QualType QT, const FieldDecl *FD,
12295                       bool InNonTrivialUnion) {
12296     if (InNonTrivialUnion)
12297       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12298           << 1 << 0 << QT << FD->getName();
12299   }
12300 
12301   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12302     if (InNonTrivialUnion)
12303       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12304           << 1 << 0 << QT << FD->getName();
12305   }
12306 
12307   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12308     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12309     if (RD->isUnion()) {
12310       if (OrigLoc.isValid()) {
12311         bool IsUnion = false;
12312         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12313           IsUnion = OrigRD->isUnion();
12314         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12315             << 0 << OrigTy << IsUnion << UseContext;
12316         // Reset OrigLoc so that this diagnostic is emitted only once.
12317         OrigLoc = SourceLocation();
12318       }
12319       InNonTrivialUnion = true;
12320     }
12321 
12322     if (InNonTrivialUnion)
12323       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12324           << 0 << 0 << QT.getUnqualifiedType() << "";
12325 
12326     for (const FieldDecl *FD : RD->fields())
12327       if (!shouldIgnoreForRecordTriviality(FD))
12328         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12329   }
12330 
12331   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12332 
12333   // The non-trivial C union type or the struct/union type that contains a
12334   // non-trivial C union.
12335   QualType OrigTy;
12336   SourceLocation OrigLoc;
12337   Sema::NonTrivialCUnionContext UseContext;
12338   Sema &S;
12339 };
12340 
12341 struct DiagNonTrivalCUnionDestructedTypeVisitor
12342     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12343   using Super =
12344       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12345 
12346   DiagNonTrivalCUnionDestructedTypeVisitor(
12347       QualType OrigTy, SourceLocation OrigLoc,
12348       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12349       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12350 
12351   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12352                      const FieldDecl *FD, bool InNonTrivialUnion) {
12353     if (const auto *AT = S.Context.getAsArrayType(QT))
12354       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12355                                      InNonTrivialUnion);
12356     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12357   }
12358 
12359   void visitARCStrong(QualType QT, const FieldDecl *FD,
12360                       bool InNonTrivialUnion) {
12361     if (InNonTrivialUnion)
12362       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12363           << 1 << 1 << QT << FD->getName();
12364   }
12365 
12366   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12367     if (InNonTrivialUnion)
12368       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12369           << 1 << 1 << QT << FD->getName();
12370   }
12371 
12372   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12373     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12374     if (RD->isUnion()) {
12375       if (OrigLoc.isValid()) {
12376         bool IsUnion = false;
12377         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12378           IsUnion = OrigRD->isUnion();
12379         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12380             << 1 << OrigTy << IsUnion << UseContext;
12381         // Reset OrigLoc so that this diagnostic is emitted only once.
12382         OrigLoc = SourceLocation();
12383       }
12384       InNonTrivialUnion = true;
12385     }
12386 
12387     if (InNonTrivialUnion)
12388       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12389           << 0 << 1 << QT.getUnqualifiedType() << "";
12390 
12391     for (const FieldDecl *FD : RD->fields())
12392       if (!shouldIgnoreForRecordTriviality(FD))
12393         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12394   }
12395 
12396   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12397   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12398                           bool InNonTrivialUnion) {}
12399 
12400   // The non-trivial C union type or the struct/union type that contains a
12401   // non-trivial C union.
12402   QualType OrigTy;
12403   SourceLocation OrigLoc;
12404   Sema::NonTrivialCUnionContext UseContext;
12405   Sema &S;
12406 };
12407 
12408 struct DiagNonTrivalCUnionCopyVisitor
12409     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12410   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12411 
12412   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12413                                  Sema::NonTrivialCUnionContext UseContext,
12414                                  Sema &S)
12415       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12416 
12417   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12418                      const FieldDecl *FD, bool InNonTrivialUnion) {
12419     if (const auto *AT = S.Context.getAsArrayType(QT))
12420       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12421                                      InNonTrivialUnion);
12422     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12423   }
12424 
12425   void visitARCStrong(QualType QT, const FieldDecl *FD,
12426                       bool InNonTrivialUnion) {
12427     if (InNonTrivialUnion)
12428       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12429           << 1 << 2 << QT << FD->getName();
12430   }
12431 
12432   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12433     if (InNonTrivialUnion)
12434       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12435           << 1 << 2 << QT << FD->getName();
12436   }
12437 
12438   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12439     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12440     if (RD->isUnion()) {
12441       if (OrigLoc.isValid()) {
12442         bool IsUnion = false;
12443         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12444           IsUnion = OrigRD->isUnion();
12445         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12446             << 2 << OrigTy << IsUnion << UseContext;
12447         // Reset OrigLoc so that this diagnostic is emitted only once.
12448         OrigLoc = SourceLocation();
12449       }
12450       InNonTrivialUnion = true;
12451     }
12452 
12453     if (InNonTrivialUnion)
12454       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12455           << 0 << 2 << QT.getUnqualifiedType() << "";
12456 
12457     for (const FieldDecl *FD : RD->fields())
12458       if (!shouldIgnoreForRecordTriviality(FD))
12459         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12460   }
12461 
12462   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12463                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12464   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12465   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12466                             bool InNonTrivialUnion) {}
12467 
12468   // The non-trivial C union type or the struct/union type that contains a
12469   // non-trivial C union.
12470   QualType OrigTy;
12471   SourceLocation OrigLoc;
12472   Sema::NonTrivialCUnionContext UseContext;
12473   Sema &S;
12474 };
12475 
12476 } // namespace
12477 
12478 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12479                                  NonTrivialCUnionContext UseContext,
12480                                  unsigned NonTrivialKind) {
12481   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12482           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12483           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12484          "shouldn't be called if type doesn't have a non-trivial C union");
12485 
12486   if ((NonTrivialKind & NTCUK_Init) &&
12487       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12488     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12489         .visit(QT, nullptr, false);
12490   if ((NonTrivialKind & NTCUK_Destruct) &&
12491       QT.hasNonTrivialToPrimitiveDestructCUnion())
12492     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12493         .visit(QT, nullptr, false);
12494   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12495     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12496         .visit(QT, nullptr, false);
12497 }
12498 
12499 /// AddInitializerToDecl - Adds the initializer Init to the
12500 /// declaration dcl. If DirectInit is true, this is C++ direct
12501 /// initialization rather than copy initialization.
12502 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12503   // If there is no declaration, there was an error parsing it.  Just ignore
12504   // the initializer.
12505   if (!RealDecl || RealDecl->isInvalidDecl()) {
12506     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12507     return;
12508   }
12509 
12510   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12511     // Pure-specifiers are handled in ActOnPureSpecifier.
12512     Diag(Method->getLocation(), diag::err_member_function_initialization)
12513       << Method->getDeclName() << Init->getSourceRange();
12514     Method->setInvalidDecl();
12515     return;
12516   }
12517 
12518   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12519   if (!VDecl) {
12520     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12521     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12522     RealDecl->setInvalidDecl();
12523     return;
12524   }
12525 
12526   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12527   if (VDecl->getType()->isUndeducedType()) {
12528     // Attempt typo correction early so that the type of the init expression can
12529     // be deduced based on the chosen correction if the original init contains a
12530     // TypoExpr.
12531     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12532     if (!Res.isUsable()) {
12533       // There are unresolved typos in Init, just drop them.
12534       // FIXME: improve the recovery strategy to preserve the Init.
12535       RealDecl->setInvalidDecl();
12536       return;
12537     }
12538     if (Res.get()->containsErrors()) {
12539       // Invalidate the decl as we don't know the type for recovery-expr yet.
12540       RealDecl->setInvalidDecl();
12541       VDecl->setInit(Res.get());
12542       return;
12543     }
12544     Init = Res.get();
12545 
12546     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12547       return;
12548   }
12549 
12550   // dllimport cannot be used on variable definitions.
12551   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12552     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12553     VDecl->setInvalidDecl();
12554     return;
12555   }
12556 
12557   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12558     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12559     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12560     VDecl->setInvalidDecl();
12561     return;
12562   }
12563 
12564   if (!VDecl->getType()->isDependentType()) {
12565     // A definition must end up with a complete type, which means it must be
12566     // complete with the restriction that an array type might be completed by
12567     // the initializer; note that later code assumes this restriction.
12568     QualType BaseDeclType = VDecl->getType();
12569     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12570       BaseDeclType = Array->getElementType();
12571     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12572                             diag::err_typecheck_decl_incomplete_type)) {
12573       RealDecl->setInvalidDecl();
12574       return;
12575     }
12576 
12577     // The variable can not have an abstract class type.
12578     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12579                                diag::err_abstract_type_in_decl,
12580                                AbstractVariableType))
12581       VDecl->setInvalidDecl();
12582   }
12583 
12584   // If adding the initializer will turn this declaration into a definition,
12585   // and we already have a definition for this variable, diagnose or otherwise
12586   // handle the situation.
12587   if (VarDecl *Def = VDecl->getDefinition())
12588     if (Def != VDecl &&
12589         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12590         !VDecl->isThisDeclarationADemotedDefinition() &&
12591         checkVarDeclRedefinition(Def, VDecl))
12592       return;
12593 
12594   if (getLangOpts().CPlusPlus) {
12595     // C++ [class.static.data]p4
12596     //   If a static data member is of const integral or const
12597     //   enumeration type, its declaration in the class definition can
12598     //   specify a constant-initializer which shall be an integral
12599     //   constant expression (5.19). In that case, the member can appear
12600     //   in integral constant expressions. The member shall still be
12601     //   defined in a namespace scope if it is used in the program and the
12602     //   namespace scope definition shall not contain an initializer.
12603     //
12604     // We already performed a redefinition check above, but for static
12605     // data members we also need to check whether there was an in-class
12606     // declaration with an initializer.
12607     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12608       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12609           << VDecl->getDeclName();
12610       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12611            diag::note_previous_initializer)
12612           << 0;
12613       return;
12614     }
12615 
12616     if (VDecl->hasLocalStorage())
12617       setFunctionHasBranchProtectedScope();
12618 
12619     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12620       VDecl->setInvalidDecl();
12621       return;
12622     }
12623   }
12624 
12625   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12626   // a kernel function cannot be initialized."
12627   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12628     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12629     VDecl->setInvalidDecl();
12630     return;
12631   }
12632 
12633   // The LoaderUninitialized attribute acts as a definition (of undef).
12634   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12635     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12636     VDecl->setInvalidDecl();
12637     return;
12638   }
12639 
12640   // Get the decls type and save a reference for later, since
12641   // CheckInitializerTypes may change it.
12642   QualType DclT = VDecl->getType(), SavT = DclT;
12643 
12644   // Expressions default to 'id' when we're in a debugger
12645   // and we are assigning it to a variable of Objective-C pointer type.
12646   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12647       Init->getType() == Context.UnknownAnyTy) {
12648     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12649     if (Result.isInvalid()) {
12650       VDecl->setInvalidDecl();
12651       return;
12652     }
12653     Init = Result.get();
12654   }
12655 
12656   // Perform the initialization.
12657   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12658   if (!VDecl->isInvalidDecl()) {
12659     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12660     InitializationKind Kind = InitializationKind::CreateForInit(
12661         VDecl->getLocation(), DirectInit, Init);
12662 
12663     MultiExprArg Args = Init;
12664     if (CXXDirectInit)
12665       Args = MultiExprArg(CXXDirectInit->getExprs(),
12666                           CXXDirectInit->getNumExprs());
12667 
12668     // Try to correct any TypoExprs in the initialization arguments.
12669     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12670       ExprResult Res = CorrectDelayedTyposInExpr(
12671           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12672           [this, Entity, Kind](Expr *E) {
12673             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12674             return Init.Failed() ? ExprError() : E;
12675           });
12676       if (Res.isInvalid()) {
12677         VDecl->setInvalidDecl();
12678       } else if (Res.get() != Args[Idx]) {
12679         Args[Idx] = Res.get();
12680       }
12681     }
12682     if (VDecl->isInvalidDecl())
12683       return;
12684 
12685     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12686                                    /*TopLevelOfInitList=*/false,
12687                                    /*TreatUnavailableAsInvalid=*/false);
12688     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12689     if (Result.isInvalid()) {
12690       // If the provided initializer fails to initialize the var decl,
12691       // we attach a recovery expr for better recovery.
12692       auto RecoveryExpr =
12693           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12694       if (RecoveryExpr.get())
12695         VDecl->setInit(RecoveryExpr.get());
12696       return;
12697     }
12698 
12699     Init = Result.getAs<Expr>();
12700   }
12701 
12702   // Check for self-references within variable initializers.
12703   // Variables declared within a function/method body (except for references)
12704   // are handled by a dataflow analysis.
12705   // This is undefined behavior in C++, but valid in C.
12706   if (getLangOpts().CPlusPlus)
12707     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12708         VDecl->getType()->isReferenceType())
12709       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12710 
12711   // If the type changed, it means we had an incomplete type that was
12712   // completed by the initializer. For example:
12713   //   int ary[] = { 1, 3, 5 };
12714   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12715   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12716     VDecl->setType(DclT);
12717 
12718   if (!VDecl->isInvalidDecl()) {
12719     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12720 
12721     if (VDecl->hasAttr<BlocksAttr>())
12722       checkRetainCycles(VDecl, Init);
12723 
12724     // It is safe to assign a weak reference into a strong variable.
12725     // Although this code can still have problems:
12726     //   id x = self.weakProp;
12727     //   id y = self.weakProp;
12728     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12729     // paths through the function. This should be revisited if
12730     // -Wrepeated-use-of-weak is made flow-sensitive.
12731     if (FunctionScopeInfo *FSI = getCurFunction())
12732       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12733            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12734           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12735                            Init->getBeginLoc()))
12736         FSI->markSafeWeakUse(Init);
12737   }
12738 
12739   // The initialization is usually a full-expression.
12740   //
12741   // FIXME: If this is a braced initialization of an aggregate, it is not
12742   // an expression, and each individual field initializer is a separate
12743   // full-expression. For instance, in:
12744   //
12745   //   struct Temp { ~Temp(); };
12746   //   struct S { S(Temp); };
12747   //   struct T { S a, b; } t = { Temp(), Temp() }
12748   //
12749   // we should destroy the first Temp before constructing the second.
12750   ExprResult Result =
12751       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12752                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12753   if (Result.isInvalid()) {
12754     VDecl->setInvalidDecl();
12755     return;
12756   }
12757   Init = Result.get();
12758 
12759   // Attach the initializer to the decl.
12760   VDecl->setInit(Init);
12761 
12762   if (VDecl->isLocalVarDecl()) {
12763     // Don't check the initializer if the declaration is malformed.
12764     if (VDecl->isInvalidDecl()) {
12765       // do nothing
12766 
12767     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12768     // This is true even in C++ for OpenCL.
12769     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12770       CheckForConstantInitializer(Init, DclT);
12771 
12772     // Otherwise, C++ does not restrict the initializer.
12773     } else if (getLangOpts().CPlusPlus) {
12774       // do nothing
12775 
12776     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12777     // static storage duration shall be constant expressions or string literals.
12778     } else if (VDecl->getStorageClass() == SC_Static) {
12779       CheckForConstantInitializer(Init, DclT);
12780 
12781     // C89 is stricter than C99 for aggregate initializers.
12782     // C89 6.5.7p3: All the expressions [...] in an initializer list
12783     // for an object that has aggregate or union type shall be
12784     // constant expressions.
12785     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12786                isa<InitListExpr>(Init)) {
12787       const Expr *Culprit;
12788       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12789         Diag(Culprit->getExprLoc(),
12790              diag::ext_aggregate_init_not_constant)
12791           << Culprit->getSourceRange();
12792       }
12793     }
12794 
12795     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12796       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12797         if (VDecl->hasLocalStorage())
12798           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12799   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12800              VDecl->getLexicalDeclContext()->isRecord()) {
12801     // This is an in-class initialization for a static data member, e.g.,
12802     //
12803     // struct S {
12804     //   static const int value = 17;
12805     // };
12806 
12807     // C++ [class.mem]p4:
12808     //   A member-declarator can contain a constant-initializer only
12809     //   if it declares a static member (9.4) of const integral or
12810     //   const enumeration type, see 9.4.2.
12811     //
12812     // C++11 [class.static.data]p3:
12813     //   If a non-volatile non-inline const static data member is of integral
12814     //   or enumeration type, its declaration in the class definition can
12815     //   specify a brace-or-equal-initializer in which every initializer-clause
12816     //   that is an assignment-expression is a constant expression. A static
12817     //   data member of literal type can be declared in the class definition
12818     //   with the constexpr specifier; if so, its declaration shall specify a
12819     //   brace-or-equal-initializer in which every initializer-clause that is
12820     //   an assignment-expression is a constant expression.
12821 
12822     // Do nothing on dependent types.
12823     if (DclT->isDependentType()) {
12824 
12825     // Allow any 'static constexpr' members, whether or not they are of literal
12826     // type. We separately check that every constexpr variable is of literal
12827     // type.
12828     } else if (VDecl->isConstexpr()) {
12829 
12830     // Require constness.
12831     } else if (!DclT.isConstQualified()) {
12832       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12833         << Init->getSourceRange();
12834       VDecl->setInvalidDecl();
12835 
12836     // We allow integer constant expressions in all cases.
12837     } else if (DclT->isIntegralOrEnumerationType()) {
12838       // Check whether the expression is a constant expression.
12839       SourceLocation Loc;
12840       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12841         // In C++11, a non-constexpr const static data member with an
12842         // in-class initializer cannot be volatile.
12843         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12844       else if (Init->isValueDependent())
12845         ; // Nothing to check.
12846       else if (Init->isIntegerConstantExpr(Context, &Loc))
12847         ; // Ok, it's an ICE!
12848       else if (Init->getType()->isScopedEnumeralType() &&
12849                Init->isCXX11ConstantExpr(Context))
12850         ; // Ok, it is a scoped-enum constant expression.
12851       else if (Init->isEvaluatable(Context)) {
12852         // If we can constant fold the initializer through heroics, accept it,
12853         // but report this as a use of an extension for -pedantic.
12854         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12855           << Init->getSourceRange();
12856       } else {
12857         // Otherwise, this is some crazy unknown case.  Report the issue at the
12858         // location provided by the isIntegerConstantExpr failed check.
12859         Diag(Loc, diag::err_in_class_initializer_non_constant)
12860           << Init->getSourceRange();
12861         VDecl->setInvalidDecl();
12862       }
12863 
12864     // We allow foldable floating-point constants as an extension.
12865     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12866       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12867       // it anyway and provide a fixit to add the 'constexpr'.
12868       if (getLangOpts().CPlusPlus11) {
12869         Diag(VDecl->getLocation(),
12870              diag::ext_in_class_initializer_float_type_cxx11)
12871             << DclT << Init->getSourceRange();
12872         Diag(VDecl->getBeginLoc(),
12873              diag::note_in_class_initializer_float_type_cxx11)
12874             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12875       } else {
12876         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12877           << DclT << Init->getSourceRange();
12878 
12879         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12880           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12881             << Init->getSourceRange();
12882           VDecl->setInvalidDecl();
12883         }
12884       }
12885 
12886     // Suggest adding 'constexpr' in C++11 for literal types.
12887     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12888       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12889           << DclT << Init->getSourceRange()
12890           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12891       VDecl->setConstexpr(true);
12892 
12893     } else {
12894       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12895         << DclT << Init->getSourceRange();
12896       VDecl->setInvalidDecl();
12897     }
12898   } else if (VDecl->isFileVarDecl()) {
12899     // In C, extern is typically used to avoid tentative definitions when
12900     // declaring variables in headers, but adding an intializer makes it a
12901     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12902     // In C++, extern is often used to give implictly static const variables
12903     // external linkage, so don't warn in that case. If selectany is present,
12904     // this might be header code intended for C and C++ inclusion, so apply the
12905     // C++ rules.
12906     if (VDecl->getStorageClass() == SC_Extern &&
12907         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12908          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12909         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12910         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12911       Diag(VDecl->getLocation(), diag::warn_extern_init);
12912 
12913     // In Microsoft C++ mode, a const variable defined in namespace scope has
12914     // external linkage by default if the variable is declared with
12915     // __declspec(dllexport).
12916     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12917         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12918         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12919       VDecl->setStorageClass(SC_Extern);
12920 
12921     // C99 6.7.8p4. All file scoped initializers need to be constant.
12922     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12923       CheckForConstantInitializer(Init, DclT);
12924   }
12925 
12926   QualType InitType = Init->getType();
12927   if (!InitType.isNull() &&
12928       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12929        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12930     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12931 
12932   // We will represent direct-initialization similarly to copy-initialization:
12933   //    int x(1);  -as-> int x = 1;
12934   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12935   //
12936   // Clients that want to distinguish between the two forms, can check for
12937   // direct initializer using VarDecl::getInitStyle().
12938   // A major benefit is that clients that don't particularly care about which
12939   // exactly form was it (like the CodeGen) can handle both cases without
12940   // special case code.
12941 
12942   // C++ 8.5p11:
12943   // The form of initialization (using parentheses or '=') is generally
12944   // insignificant, but does matter when the entity being initialized has a
12945   // class type.
12946   if (CXXDirectInit) {
12947     assert(DirectInit && "Call-style initializer must be direct init.");
12948     VDecl->setInitStyle(VarDecl::CallInit);
12949   } else if (DirectInit) {
12950     // This must be list-initialization. No other way is direct-initialization.
12951     VDecl->setInitStyle(VarDecl::ListInit);
12952   }
12953 
12954   if (LangOpts.OpenMP &&
12955       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12956       VDecl->isFileVarDecl())
12957     DeclsToCheckForDeferredDiags.insert(VDecl);
12958   CheckCompleteVariableDeclaration(VDecl);
12959 }
12960 
12961 /// ActOnInitializerError - Given that there was an error parsing an
12962 /// initializer for the given declaration, try to at least re-establish
12963 /// invariants such as whether a variable's type is either dependent or
12964 /// complete.
12965 void Sema::ActOnInitializerError(Decl *D) {
12966   // Our main concern here is re-establishing invariants like "a
12967   // variable's type is either dependent or complete".
12968   if (!D || D->isInvalidDecl()) return;
12969 
12970   VarDecl *VD = dyn_cast<VarDecl>(D);
12971   if (!VD) return;
12972 
12973   // Bindings are not usable if we can't make sense of the initializer.
12974   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12975     for (auto *BD : DD->bindings())
12976       BD->setInvalidDecl();
12977 
12978   // Auto types are meaningless if we can't make sense of the initializer.
12979   if (VD->getType()->isUndeducedType()) {
12980     D->setInvalidDecl();
12981     return;
12982   }
12983 
12984   QualType Ty = VD->getType();
12985   if (Ty->isDependentType()) return;
12986 
12987   // Require a complete type.
12988   if (RequireCompleteType(VD->getLocation(),
12989                           Context.getBaseElementType(Ty),
12990                           diag::err_typecheck_decl_incomplete_type)) {
12991     VD->setInvalidDecl();
12992     return;
12993   }
12994 
12995   // Require a non-abstract type.
12996   if (RequireNonAbstractType(VD->getLocation(), Ty,
12997                              diag::err_abstract_type_in_decl,
12998                              AbstractVariableType)) {
12999     VD->setInvalidDecl();
13000     return;
13001   }
13002 
13003   // Don't bother complaining about constructors or destructors,
13004   // though.
13005 }
13006 
13007 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13008   // If there is no declaration, there was an error parsing it. Just ignore it.
13009   if (!RealDecl)
13010     return;
13011 
13012   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13013     QualType Type = Var->getType();
13014 
13015     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13016     if (isa<DecompositionDecl>(RealDecl)) {
13017       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13018       Var->setInvalidDecl();
13019       return;
13020     }
13021 
13022     if (Type->isUndeducedType() &&
13023         DeduceVariableDeclarationType(Var, false, nullptr))
13024       return;
13025 
13026     // C++11 [class.static.data]p3: A static data member can be declared with
13027     // the constexpr specifier; if so, its declaration shall specify
13028     // a brace-or-equal-initializer.
13029     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13030     // the definition of a variable [...] or the declaration of a static data
13031     // member.
13032     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13033         !Var->isThisDeclarationADemotedDefinition()) {
13034       if (Var->isStaticDataMember()) {
13035         // C++1z removes the relevant rule; the in-class declaration is always
13036         // a definition there.
13037         if (!getLangOpts().CPlusPlus17 &&
13038             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13039           Diag(Var->getLocation(),
13040                diag::err_constexpr_static_mem_var_requires_init)
13041               << Var;
13042           Var->setInvalidDecl();
13043           return;
13044         }
13045       } else {
13046         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13047         Var->setInvalidDecl();
13048         return;
13049       }
13050     }
13051 
13052     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13053     // be initialized.
13054     if (!Var->isInvalidDecl() &&
13055         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13056         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13057       bool HasConstExprDefaultConstructor = false;
13058       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13059         for (auto *Ctor : RD->ctors()) {
13060           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13061               Ctor->getMethodQualifiers().getAddressSpace() ==
13062                   LangAS::opencl_constant) {
13063             HasConstExprDefaultConstructor = true;
13064           }
13065         }
13066       }
13067       if (!HasConstExprDefaultConstructor) {
13068         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13069         Var->setInvalidDecl();
13070         return;
13071       }
13072     }
13073 
13074     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13075       if (Var->getStorageClass() == SC_Extern) {
13076         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13077             << Var;
13078         Var->setInvalidDecl();
13079         return;
13080       }
13081       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13082                               diag::err_typecheck_decl_incomplete_type)) {
13083         Var->setInvalidDecl();
13084         return;
13085       }
13086       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13087         if (!RD->hasTrivialDefaultConstructor()) {
13088           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13089           Var->setInvalidDecl();
13090           return;
13091         }
13092       }
13093       // The declaration is unitialized, no need for further checks.
13094       return;
13095     }
13096 
13097     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13098     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13099         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13100       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13101                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13102 
13103 
13104     switch (DefKind) {
13105     case VarDecl::Definition:
13106       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13107         break;
13108 
13109       // We have an out-of-line definition of a static data member
13110       // that has an in-class initializer, so we type-check this like
13111       // a declaration.
13112       //
13113       LLVM_FALLTHROUGH;
13114 
13115     case VarDecl::DeclarationOnly:
13116       // It's only a declaration.
13117 
13118       // Block scope. C99 6.7p7: If an identifier for an object is
13119       // declared with no linkage (C99 6.2.2p6), the type for the
13120       // object shall be complete.
13121       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13122           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13123           RequireCompleteType(Var->getLocation(), Type,
13124                               diag::err_typecheck_decl_incomplete_type))
13125         Var->setInvalidDecl();
13126 
13127       // Make sure that the type is not abstract.
13128       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13129           RequireNonAbstractType(Var->getLocation(), Type,
13130                                  diag::err_abstract_type_in_decl,
13131                                  AbstractVariableType))
13132         Var->setInvalidDecl();
13133       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13134           Var->getStorageClass() == SC_PrivateExtern) {
13135         Diag(Var->getLocation(), diag::warn_private_extern);
13136         Diag(Var->getLocation(), diag::note_private_extern);
13137       }
13138 
13139       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13140           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13141         ExternalDeclarations.push_back(Var);
13142 
13143       return;
13144 
13145     case VarDecl::TentativeDefinition:
13146       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13147       // object that has file scope without an initializer, and without a
13148       // storage-class specifier or with the storage-class specifier "static",
13149       // constitutes a tentative definition. Note: A tentative definition with
13150       // external linkage is valid (C99 6.2.2p5).
13151       if (!Var->isInvalidDecl()) {
13152         if (const IncompleteArrayType *ArrayT
13153                                     = Context.getAsIncompleteArrayType(Type)) {
13154           if (RequireCompleteSizedType(
13155                   Var->getLocation(), ArrayT->getElementType(),
13156                   diag::err_array_incomplete_or_sizeless_type))
13157             Var->setInvalidDecl();
13158         } else if (Var->getStorageClass() == SC_Static) {
13159           // C99 6.9.2p3: If the declaration of an identifier for an object is
13160           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13161           // declared type shall not be an incomplete type.
13162           // NOTE: code such as the following
13163           //     static struct s;
13164           //     struct s { int a; };
13165           // is accepted by gcc. Hence here we issue a warning instead of
13166           // an error and we do not invalidate the static declaration.
13167           // NOTE: to avoid multiple warnings, only check the first declaration.
13168           if (Var->isFirstDecl())
13169             RequireCompleteType(Var->getLocation(), Type,
13170                                 diag::ext_typecheck_decl_incomplete_type);
13171         }
13172       }
13173 
13174       // Record the tentative definition; we're done.
13175       if (!Var->isInvalidDecl())
13176         TentativeDefinitions.push_back(Var);
13177       return;
13178     }
13179 
13180     // Provide a specific diagnostic for uninitialized variable
13181     // definitions with incomplete array type.
13182     if (Type->isIncompleteArrayType()) {
13183       Diag(Var->getLocation(),
13184            diag::err_typecheck_incomplete_array_needs_initializer);
13185       Var->setInvalidDecl();
13186       return;
13187     }
13188 
13189     // Provide a specific diagnostic for uninitialized variable
13190     // definitions with reference type.
13191     if (Type->isReferenceType()) {
13192       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13193           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13194       return;
13195     }
13196 
13197     // Do not attempt to type-check the default initializer for a
13198     // variable with dependent type.
13199     if (Type->isDependentType())
13200       return;
13201 
13202     if (Var->isInvalidDecl())
13203       return;
13204 
13205     if (!Var->hasAttr<AliasAttr>()) {
13206       if (RequireCompleteType(Var->getLocation(),
13207                               Context.getBaseElementType(Type),
13208                               diag::err_typecheck_decl_incomplete_type)) {
13209         Var->setInvalidDecl();
13210         return;
13211       }
13212     } else {
13213       return;
13214     }
13215 
13216     // The variable can not have an abstract class type.
13217     if (RequireNonAbstractType(Var->getLocation(), Type,
13218                                diag::err_abstract_type_in_decl,
13219                                AbstractVariableType)) {
13220       Var->setInvalidDecl();
13221       return;
13222     }
13223 
13224     // Check for jumps past the implicit initializer.  C++0x
13225     // clarifies that this applies to a "variable with automatic
13226     // storage duration", not a "local variable".
13227     // C++11 [stmt.dcl]p3
13228     //   A program that jumps from a point where a variable with automatic
13229     //   storage duration is not in scope to a point where it is in scope is
13230     //   ill-formed unless the variable has scalar type, class type with a
13231     //   trivial default constructor and a trivial destructor, a cv-qualified
13232     //   version of one of these types, or an array of one of the preceding
13233     //   types and is declared without an initializer.
13234     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13235       if (const RecordType *Record
13236             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13237         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13238         // Mark the function (if we're in one) for further checking even if the
13239         // looser rules of C++11 do not require such checks, so that we can
13240         // diagnose incompatibilities with C++98.
13241         if (!CXXRecord->isPOD())
13242           setFunctionHasBranchProtectedScope();
13243       }
13244     }
13245     // In OpenCL, we can't initialize objects in the __local address space,
13246     // even implicitly, so don't synthesize an implicit initializer.
13247     if (getLangOpts().OpenCL &&
13248         Var->getType().getAddressSpace() == LangAS::opencl_local)
13249       return;
13250     // C++03 [dcl.init]p9:
13251     //   If no initializer is specified for an object, and the
13252     //   object is of (possibly cv-qualified) non-POD class type (or
13253     //   array thereof), the object shall be default-initialized; if
13254     //   the object is of const-qualified type, the underlying class
13255     //   type shall have a user-declared default
13256     //   constructor. Otherwise, if no initializer is specified for
13257     //   a non- static object, the object and its subobjects, if
13258     //   any, have an indeterminate initial value); if the object
13259     //   or any of its subobjects are of const-qualified type, the
13260     //   program is ill-formed.
13261     // C++0x [dcl.init]p11:
13262     //   If no initializer is specified for an object, the object is
13263     //   default-initialized; [...].
13264     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13265     InitializationKind Kind
13266       = InitializationKind::CreateDefault(Var->getLocation());
13267 
13268     InitializationSequence InitSeq(*this, Entity, Kind, None);
13269     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13270 
13271     if (Init.get()) {
13272       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13273       // This is important for template substitution.
13274       Var->setInitStyle(VarDecl::CallInit);
13275     } else if (Init.isInvalid()) {
13276       // If default-init fails, attach a recovery-expr initializer to track
13277       // that initialization was attempted and failed.
13278       auto RecoveryExpr =
13279           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13280       if (RecoveryExpr.get())
13281         Var->setInit(RecoveryExpr.get());
13282     }
13283 
13284     CheckCompleteVariableDeclaration(Var);
13285   }
13286 }
13287 
13288 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13289   // If there is no declaration, there was an error parsing it. Ignore it.
13290   if (!D)
13291     return;
13292 
13293   VarDecl *VD = dyn_cast<VarDecl>(D);
13294   if (!VD) {
13295     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13296     D->setInvalidDecl();
13297     return;
13298   }
13299 
13300   VD->setCXXForRangeDecl(true);
13301 
13302   // for-range-declaration cannot be given a storage class specifier.
13303   int Error = -1;
13304   switch (VD->getStorageClass()) {
13305   case SC_None:
13306     break;
13307   case SC_Extern:
13308     Error = 0;
13309     break;
13310   case SC_Static:
13311     Error = 1;
13312     break;
13313   case SC_PrivateExtern:
13314     Error = 2;
13315     break;
13316   case SC_Auto:
13317     Error = 3;
13318     break;
13319   case SC_Register:
13320     Error = 4;
13321     break;
13322   }
13323 
13324   // for-range-declaration cannot be given a storage class specifier con't.
13325   switch (VD->getTSCSpec()) {
13326   case TSCS_thread_local:
13327     Error = 6;
13328     break;
13329   case TSCS___thread:
13330   case TSCS__Thread_local:
13331   case TSCS_unspecified:
13332     break;
13333   }
13334 
13335   if (Error != -1) {
13336     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13337         << VD << Error;
13338     D->setInvalidDecl();
13339   }
13340 }
13341 
13342 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13343                                             IdentifierInfo *Ident,
13344                                             ParsedAttributes &Attrs) {
13345   // C++1y [stmt.iter]p1:
13346   //   A range-based for statement of the form
13347   //      for ( for-range-identifier : for-range-initializer ) statement
13348   //   is equivalent to
13349   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13350   DeclSpec DS(Attrs.getPool().getFactory());
13351 
13352   const char *PrevSpec;
13353   unsigned DiagID;
13354   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13355                      getPrintingPolicy());
13356 
13357   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13358   D.SetIdentifier(Ident, IdentLoc);
13359   D.takeAttributes(Attrs);
13360 
13361   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13362                 IdentLoc);
13363   Decl *Var = ActOnDeclarator(S, D);
13364   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13365   FinalizeDeclaration(Var);
13366   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13367                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13368                                                       : IdentLoc);
13369 }
13370 
13371 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13372   if (var->isInvalidDecl()) return;
13373 
13374   MaybeAddCUDAConstantAttr(var);
13375 
13376   if (getLangOpts().OpenCL) {
13377     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13378     // initialiser
13379     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13380         !var->hasInit()) {
13381       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13382           << 1 /*Init*/;
13383       var->setInvalidDecl();
13384       return;
13385     }
13386   }
13387 
13388   // In Objective-C, don't allow jumps past the implicit initialization of a
13389   // local retaining variable.
13390   if (getLangOpts().ObjC &&
13391       var->hasLocalStorage()) {
13392     switch (var->getType().getObjCLifetime()) {
13393     case Qualifiers::OCL_None:
13394     case Qualifiers::OCL_ExplicitNone:
13395     case Qualifiers::OCL_Autoreleasing:
13396       break;
13397 
13398     case Qualifiers::OCL_Weak:
13399     case Qualifiers::OCL_Strong:
13400       setFunctionHasBranchProtectedScope();
13401       break;
13402     }
13403   }
13404 
13405   if (var->hasLocalStorage() &&
13406       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13407     setFunctionHasBranchProtectedScope();
13408 
13409   // Warn about externally-visible variables being defined without a
13410   // prior declaration.  We only want to do this for global
13411   // declarations, but we also specifically need to avoid doing it for
13412   // class members because the linkage of an anonymous class can
13413   // change if it's later given a typedef name.
13414   if (var->isThisDeclarationADefinition() &&
13415       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13416       var->isExternallyVisible() && var->hasLinkage() &&
13417       !var->isInline() && !var->getDescribedVarTemplate() &&
13418       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13419       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13420       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13421                                   var->getLocation())) {
13422     // Find a previous declaration that's not a definition.
13423     VarDecl *prev = var->getPreviousDecl();
13424     while (prev && prev->isThisDeclarationADefinition())
13425       prev = prev->getPreviousDecl();
13426 
13427     if (!prev) {
13428       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13429       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13430           << /* variable */ 0;
13431     }
13432   }
13433 
13434   // Cache the result of checking for constant initialization.
13435   Optional<bool> CacheHasConstInit;
13436   const Expr *CacheCulprit = nullptr;
13437   auto checkConstInit = [&]() mutable {
13438     if (!CacheHasConstInit)
13439       CacheHasConstInit = var->getInit()->isConstantInitializer(
13440             Context, var->getType()->isReferenceType(), &CacheCulprit);
13441     return *CacheHasConstInit;
13442   };
13443 
13444   if (var->getTLSKind() == VarDecl::TLS_Static) {
13445     if (var->getType().isDestructedType()) {
13446       // GNU C++98 edits for __thread, [basic.start.term]p3:
13447       //   The type of an object with thread storage duration shall not
13448       //   have a non-trivial destructor.
13449       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13450       if (getLangOpts().CPlusPlus11)
13451         Diag(var->getLocation(), diag::note_use_thread_local);
13452     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13453       if (!checkConstInit()) {
13454         // GNU C++98 edits for __thread, [basic.start.init]p4:
13455         //   An object of thread storage duration shall not require dynamic
13456         //   initialization.
13457         // FIXME: Need strict checking here.
13458         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13459           << CacheCulprit->getSourceRange();
13460         if (getLangOpts().CPlusPlus11)
13461           Diag(var->getLocation(), diag::note_use_thread_local);
13462       }
13463     }
13464   }
13465 
13466 
13467   if (!var->getType()->isStructureType() && var->hasInit() &&
13468       isa<InitListExpr>(var->getInit())) {
13469     const auto *ILE = cast<InitListExpr>(var->getInit());
13470     unsigned NumInits = ILE->getNumInits();
13471     if (NumInits > 2)
13472       for (unsigned I = 0; I < NumInits; ++I) {
13473         const auto *Init = ILE->getInit(I);
13474         if (!Init)
13475           break;
13476         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13477         if (!SL)
13478           break;
13479 
13480         unsigned NumConcat = SL->getNumConcatenated();
13481         // Diagnose missing comma in string array initialization.
13482         // Do not warn when all the elements in the initializer are concatenated
13483         // together. Do not warn for macros too.
13484         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13485           bool OnlyOneMissingComma = true;
13486           for (unsigned J = I + 1; J < NumInits; ++J) {
13487             const auto *Init = ILE->getInit(J);
13488             if (!Init)
13489               break;
13490             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13491             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13492               OnlyOneMissingComma = false;
13493               break;
13494             }
13495           }
13496 
13497           if (OnlyOneMissingComma) {
13498             SmallVector<FixItHint, 1> Hints;
13499             for (unsigned i = 0; i < NumConcat - 1; ++i)
13500               Hints.push_back(FixItHint::CreateInsertion(
13501                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13502 
13503             Diag(SL->getStrTokenLoc(1),
13504                  diag::warn_concatenated_literal_array_init)
13505                 << Hints;
13506             Diag(SL->getBeginLoc(),
13507                  diag::note_concatenated_string_literal_silence);
13508           }
13509           // In any case, stop now.
13510           break;
13511         }
13512       }
13513   }
13514 
13515 
13516   QualType type = var->getType();
13517 
13518   if (var->hasAttr<BlocksAttr>())
13519     getCurFunction()->addByrefBlockVar(var);
13520 
13521   Expr *Init = var->getInit();
13522   bool GlobalStorage = var->hasGlobalStorage();
13523   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13524   QualType baseType = Context.getBaseElementType(type);
13525   bool HasConstInit = true;
13526 
13527   // Check whether the initializer is sufficiently constant.
13528   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13529       !Init->isValueDependent() &&
13530       (GlobalStorage || var->isConstexpr() ||
13531        var->mightBeUsableInConstantExpressions(Context))) {
13532     // If this variable might have a constant initializer or might be usable in
13533     // constant expressions, check whether or not it actually is now.  We can't
13534     // do this lazily, because the result might depend on things that change
13535     // later, such as which constexpr functions happen to be defined.
13536     SmallVector<PartialDiagnosticAt, 8> Notes;
13537     if (!getLangOpts().CPlusPlus11) {
13538       // Prior to C++11, in contexts where a constant initializer is required,
13539       // the set of valid constant initializers is described by syntactic rules
13540       // in [expr.const]p2-6.
13541       // FIXME: Stricter checking for these rules would be useful for constinit /
13542       // -Wglobal-constructors.
13543       HasConstInit = checkConstInit();
13544 
13545       // Compute and cache the constant value, and remember that we have a
13546       // constant initializer.
13547       if (HasConstInit) {
13548         (void)var->checkForConstantInitialization(Notes);
13549         Notes.clear();
13550       } else if (CacheCulprit) {
13551         Notes.emplace_back(CacheCulprit->getExprLoc(),
13552                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13553         Notes.back().second << CacheCulprit->getSourceRange();
13554       }
13555     } else {
13556       // Evaluate the initializer to see if it's a constant initializer.
13557       HasConstInit = var->checkForConstantInitialization(Notes);
13558     }
13559 
13560     if (HasConstInit) {
13561       // FIXME: Consider replacing the initializer with a ConstantExpr.
13562     } else if (var->isConstexpr()) {
13563       SourceLocation DiagLoc = var->getLocation();
13564       // If the note doesn't add any useful information other than a source
13565       // location, fold it into the primary diagnostic.
13566       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13567                                    diag::note_invalid_subexpr_in_const_expr) {
13568         DiagLoc = Notes[0].first;
13569         Notes.clear();
13570       }
13571       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13572           << var << Init->getSourceRange();
13573       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13574         Diag(Notes[I].first, Notes[I].second);
13575     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13576       auto *Attr = var->getAttr<ConstInitAttr>();
13577       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13578           << Init->getSourceRange();
13579       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13580           << Attr->getRange() << Attr->isConstinit();
13581       for (auto &it : Notes)
13582         Diag(it.first, it.second);
13583     } else if (IsGlobal &&
13584                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13585                                            var->getLocation())) {
13586       // Warn about globals which don't have a constant initializer.  Don't
13587       // warn about globals with a non-trivial destructor because we already
13588       // warned about them.
13589       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13590       if (!(RD && !RD->hasTrivialDestructor())) {
13591         // checkConstInit() here permits trivial default initialization even in
13592         // C++11 onwards, where such an initializer is not a constant initializer
13593         // but nonetheless doesn't require a global constructor.
13594         if (!checkConstInit())
13595           Diag(var->getLocation(), diag::warn_global_constructor)
13596               << Init->getSourceRange();
13597       }
13598     }
13599   }
13600 
13601   // Apply section attributes and pragmas to global variables.
13602   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13603       !inTemplateInstantiation()) {
13604     PragmaStack<StringLiteral *> *Stack = nullptr;
13605     int SectionFlags = ASTContext::PSF_Read;
13606     if (var->getType().isConstQualified()) {
13607       if (HasConstInit)
13608         Stack = &ConstSegStack;
13609       else {
13610         Stack = &BSSSegStack;
13611         SectionFlags |= ASTContext::PSF_Write;
13612       }
13613     } else if (var->hasInit() && HasConstInit) {
13614       Stack = &DataSegStack;
13615       SectionFlags |= ASTContext::PSF_Write;
13616     } else {
13617       Stack = &BSSSegStack;
13618       SectionFlags |= ASTContext::PSF_Write;
13619     }
13620     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13621       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13622         SectionFlags |= ASTContext::PSF_Implicit;
13623       UnifySection(SA->getName(), SectionFlags, var);
13624     } else if (Stack->CurrentValue) {
13625       SectionFlags |= ASTContext::PSF_Implicit;
13626       auto SectionName = Stack->CurrentValue->getString();
13627       var->addAttr(SectionAttr::CreateImplicit(
13628           Context, SectionName, Stack->CurrentPragmaLocation,
13629           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13630       if (UnifySection(SectionName, SectionFlags, var))
13631         var->dropAttr<SectionAttr>();
13632     }
13633 
13634     // Apply the init_seg attribute if this has an initializer.  If the
13635     // initializer turns out to not be dynamic, we'll end up ignoring this
13636     // attribute.
13637     if (CurInitSeg && var->getInit())
13638       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13639                                                CurInitSegLoc,
13640                                                AttributeCommonInfo::AS_Pragma));
13641   }
13642 
13643   // All the following checks are C++ only.
13644   if (!getLangOpts().CPlusPlus) {
13645     // If this variable must be emitted, add it as an initializer for the
13646     // current module.
13647     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13648       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13649     return;
13650   }
13651 
13652   // Require the destructor.
13653   if (!type->isDependentType())
13654     if (const RecordType *recordType = baseType->getAs<RecordType>())
13655       FinalizeVarWithDestructor(var, recordType);
13656 
13657   // If this variable must be emitted, add it as an initializer for the current
13658   // module.
13659   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13660     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13661 
13662   // Build the bindings if this is a structured binding declaration.
13663   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13664     CheckCompleteDecompositionDeclaration(DD);
13665 }
13666 
13667 /// Check if VD needs to be dllexport/dllimport due to being in a
13668 /// dllexport/import function.
13669 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13670   assert(VD->isStaticLocal());
13671 
13672   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13673 
13674   // Find outermost function when VD is in lambda function.
13675   while (FD && !getDLLAttr(FD) &&
13676          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13677          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13678     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13679   }
13680 
13681   if (!FD)
13682     return;
13683 
13684   // Static locals inherit dll attributes from their function.
13685   if (Attr *A = getDLLAttr(FD)) {
13686     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13687     NewAttr->setInherited(true);
13688     VD->addAttr(NewAttr);
13689   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13690     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13691     NewAttr->setInherited(true);
13692     VD->addAttr(NewAttr);
13693 
13694     // Export this function to enforce exporting this static variable even
13695     // if it is not used in this compilation unit.
13696     if (!FD->hasAttr<DLLExportAttr>())
13697       FD->addAttr(NewAttr);
13698 
13699   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13700     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13701     NewAttr->setInherited(true);
13702     VD->addAttr(NewAttr);
13703   }
13704 }
13705 
13706 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13707 /// any semantic actions necessary after any initializer has been attached.
13708 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13709   // Note that we are no longer parsing the initializer for this declaration.
13710   ParsingInitForAutoVars.erase(ThisDecl);
13711 
13712   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13713   if (!VD)
13714     return;
13715 
13716   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13717   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13718       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13719     if (PragmaClangBSSSection.Valid)
13720       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13721           Context, PragmaClangBSSSection.SectionName,
13722           PragmaClangBSSSection.PragmaLocation,
13723           AttributeCommonInfo::AS_Pragma));
13724     if (PragmaClangDataSection.Valid)
13725       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13726           Context, PragmaClangDataSection.SectionName,
13727           PragmaClangDataSection.PragmaLocation,
13728           AttributeCommonInfo::AS_Pragma));
13729     if (PragmaClangRodataSection.Valid)
13730       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13731           Context, PragmaClangRodataSection.SectionName,
13732           PragmaClangRodataSection.PragmaLocation,
13733           AttributeCommonInfo::AS_Pragma));
13734     if (PragmaClangRelroSection.Valid)
13735       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13736           Context, PragmaClangRelroSection.SectionName,
13737           PragmaClangRelroSection.PragmaLocation,
13738           AttributeCommonInfo::AS_Pragma));
13739   }
13740 
13741   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13742     for (auto *BD : DD->bindings()) {
13743       FinalizeDeclaration(BD);
13744     }
13745   }
13746 
13747   checkAttributesAfterMerging(*this, *VD);
13748 
13749   // Perform TLS alignment check here after attributes attached to the variable
13750   // which may affect the alignment have been processed. Only perform the check
13751   // if the target has a maximum TLS alignment (zero means no constraints).
13752   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13753     // Protect the check so that it's not performed on dependent types and
13754     // dependent alignments (we can't determine the alignment in that case).
13755     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13756       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13757       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13758         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13759           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13760           << (unsigned)MaxAlignChars.getQuantity();
13761       }
13762     }
13763   }
13764 
13765   if (VD->isStaticLocal())
13766     CheckStaticLocalForDllExport(VD);
13767 
13768   // Perform check for initializers of device-side global variables.
13769   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13770   // 7.5). We must also apply the same checks to all __shared__
13771   // variables whether they are local or not. CUDA also allows
13772   // constant initializers for __constant__ and __device__ variables.
13773   if (getLangOpts().CUDA)
13774     checkAllowedCUDAInitializer(VD);
13775 
13776   // Grab the dllimport or dllexport attribute off of the VarDecl.
13777   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13778 
13779   // Imported static data members cannot be defined out-of-line.
13780   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13781     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13782         VD->isThisDeclarationADefinition()) {
13783       // We allow definitions of dllimport class template static data members
13784       // with a warning.
13785       CXXRecordDecl *Context =
13786         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13787       bool IsClassTemplateMember =
13788           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13789           Context->getDescribedClassTemplate();
13790 
13791       Diag(VD->getLocation(),
13792            IsClassTemplateMember
13793                ? diag::warn_attribute_dllimport_static_field_definition
13794                : diag::err_attribute_dllimport_static_field_definition);
13795       Diag(IA->getLocation(), diag::note_attribute);
13796       if (!IsClassTemplateMember)
13797         VD->setInvalidDecl();
13798     }
13799   }
13800 
13801   // dllimport/dllexport variables cannot be thread local, their TLS index
13802   // isn't exported with the variable.
13803   if (DLLAttr && VD->getTLSKind()) {
13804     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13805     if (F && getDLLAttr(F)) {
13806       assert(VD->isStaticLocal());
13807       // But if this is a static local in a dlimport/dllexport function, the
13808       // function will never be inlined, which means the var would never be
13809       // imported, so having it marked import/export is safe.
13810     } else {
13811       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13812                                                                     << DLLAttr;
13813       VD->setInvalidDecl();
13814     }
13815   }
13816 
13817   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13818     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13819       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13820           << Attr;
13821       VD->dropAttr<UsedAttr>();
13822     }
13823   }
13824   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13825     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13826       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13827           << Attr;
13828       VD->dropAttr<RetainAttr>();
13829     }
13830   }
13831 
13832   const DeclContext *DC = VD->getDeclContext();
13833   // If there's a #pragma GCC visibility in scope, and this isn't a class
13834   // member, set the visibility of this variable.
13835   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13836     AddPushedVisibilityAttribute(VD);
13837 
13838   // FIXME: Warn on unused var template partial specializations.
13839   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13840     MarkUnusedFileScopedDecl(VD);
13841 
13842   // Now we have parsed the initializer and can update the table of magic
13843   // tag values.
13844   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13845       !VD->getType()->isIntegralOrEnumerationType())
13846     return;
13847 
13848   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13849     const Expr *MagicValueExpr = VD->getInit();
13850     if (!MagicValueExpr) {
13851       continue;
13852     }
13853     Optional<llvm::APSInt> MagicValueInt;
13854     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13855       Diag(I->getRange().getBegin(),
13856            diag::err_type_tag_for_datatype_not_ice)
13857         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13858       continue;
13859     }
13860     if (MagicValueInt->getActiveBits() > 64) {
13861       Diag(I->getRange().getBegin(),
13862            diag::err_type_tag_for_datatype_too_large)
13863         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13864       continue;
13865     }
13866     uint64_t MagicValue = MagicValueInt->getZExtValue();
13867     RegisterTypeTagForDatatype(I->getArgumentKind(),
13868                                MagicValue,
13869                                I->getMatchingCType(),
13870                                I->getLayoutCompatible(),
13871                                I->getMustBeNull());
13872   }
13873 }
13874 
13875 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13876   auto *VD = dyn_cast<VarDecl>(DD);
13877   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13878 }
13879 
13880 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13881                                                    ArrayRef<Decl *> Group) {
13882   SmallVector<Decl*, 8> Decls;
13883 
13884   if (DS.isTypeSpecOwned())
13885     Decls.push_back(DS.getRepAsDecl());
13886 
13887   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13888   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13889   bool DiagnosedMultipleDecomps = false;
13890   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13891   bool DiagnosedNonDeducedAuto = false;
13892 
13893   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13894     if (Decl *D = Group[i]) {
13895       // For declarators, there are some additional syntactic-ish checks we need
13896       // to perform.
13897       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13898         if (!FirstDeclaratorInGroup)
13899           FirstDeclaratorInGroup = DD;
13900         if (!FirstDecompDeclaratorInGroup)
13901           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13902         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13903             !hasDeducedAuto(DD))
13904           FirstNonDeducedAutoInGroup = DD;
13905 
13906         if (FirstDeclaratorInGroup != DD) {
13907           // A decomposition declaration cannot be combined with any other
13908           // declaration in the same group.
13909           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13910             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13911                  diag::err_decomp_decl_not_alone)
13912                 << FirstDeclaratorInGroup->getSourceRange()
13913                 << DD->getSourceRange();
13914             DiagnosedMultipleDecomps = true;
13915           }
13916 
13917           // A declarator that uses 'auto' in any way other than to declare a
13918           // variable with a deduced type cannot be combined with any other
13919           // declarator in the same group.
13920           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13921             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13922                  diag::err_auto_non_deduced_not_alone)
13923                 << FirstNonDeducedAutoInGroup->getType()
13924                        ->hasAutoForTrailingReturnType()
13925                 << FirstDeclaratorInGroup->getSourceRange()
13926                 << DD->getSourceRange();
13927             DiagnosedNonDeducedAuto = true;
13928           }
13929         }
13930       }
13931 
13932       Decls.push_back(D);
13933     }
13934   }
13935 
13936   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13937     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13938       handleTagNumbering(Tag, S);
13939       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13940           getLangOpts().CPlusPlus)
13941         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13942     }
13943   }
13944 
13945   return BuildDeclaratorGroup(Decls);
13946 }
13947 
13948 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13949 /// group, performing any necessary semantic checking.
13950 Sema::DeclGroupPtrTy
13951 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13952   // C++14 [dcl.spec.auto]p7: (DR1347)
13953   //   If the type that replaces the placeholder type is not the same in each
13954   //   deduction, the program is ill-formed.
13955   if (Group.size() > 1) {
13956     QualType Deduced;
13957     VarDecl *DeducedDecl = nullptr;
13958     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13959       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13960       if (!D || D->isInvalidDecl())
13961         break;
13962       DeducedType *DT = D->getType()->getContainedDeducedType();
13963       if (!DT || DT->getDeducedType().isNull())
13964         continue;
13965       if (Deduced.isNull()) {
13966         Deduced = DT->getDeducedType();
13967         DeducedDecl = D;
13968       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13969         auto *AT = dyn_cast<AutoType>(DT);
13970         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13971                         diag::err_auto_different_deductions)
13972                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13973                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13974                    << D->getDeclName();
13975         if (DeducedDecl->hasInit())
13976           Dia << DeducedDecl->getInit()->getSourceRange();
13977         if (D->getInit())
13978           Dia << D->getInit()->getSourceRange();
13979         D->setInvalidDecl();
13980         break;
13981       }
13982     }
13983   }
13984 
13985   ActOnDocumentableDecls(Group);
13986 
13987   return DeclGroupPtrTy::make(
13988       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13989 }
13990 
13991 void Sema::ActOnDocumentableDecl(Decl *D) {
13992   ActOnDocumentableDecls(D);
13993 }
13994 
13995 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13996   // Don't parse the comment if Doxygen diagnostics are ignored.
13997   if (Group.empty() || !Group[0])
13998     return;
13999 
14000   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14001                       Group[0]->getLocation()) &&
14002       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14003                       Group[0]->getLocation()))
14004     return;
14005 
14006   if (Group.size() >= 2) {
14007     // This is a decl group.  Normally it will contain only declarations
14008     // produced from declarator list.  But in case we have any definitions or
14009     // additional declaration references:
14010     //   'typedef struct S {} S;'
14011     //   'typedef struct S *S;'
14012     //   'struct S *pS;'
14013     // FinalizeDeclaratorGroup adds these as separate declarations.
14014     Decl *MaybeTagDecl = Group[0];
14015     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14016       Group = Group.slice(1);
14017     }
14018   }
14019 
14020   // FIMXE: We assume every Decl in the group is in the same file.
14021   // This is false when preprocessor constructs the group from decls in
14022   // different files (e. g. macros or #include).
14023   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14024 }
14025 
14026 /// Common checks for a parameter-declaration that should apply to both function
14027 /// parameters and non-type template parameters.
14028 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14029   // Check that there are no default arguments inside the type of this
14030   // parameter.
14031   if (getLangOpts().CPlusPlus)
14032     CheckExtraCXXDefaultArguments(D);
14033 
14034   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14035   if (D.getCXXScopeSpec().isSet()) {
14036     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14037       << D.getCXXScopeSpec().getRange();
14038   }
14039 
14040   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14041   // simple identifier except [...irrelevant cases...].
14042   switch (D.getName().getKind()) {
14043   case UnqualifiedIdKind::IK_Identifier:
14044     break;
14045 
14046   case UnqualifiedIdKind::IK_OperatorFunctionId:
14047   case UnqualifiedIdKind::IK_ConversionFunctionId:
14048   case UnqualifiedIdKind::IK_LiteralOperatorId:
14049   case UnqualifiedIdKind::IK_ConstructorName:
14050   case UnqualifiedIdKind::IK_DestructorName:
14051   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14052   case UnqualifiedIdKind::IK_DeductionGuideName:
14053     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14054       << GetNameForDeclarator(D).getName();
14055     break;
14056 
14057   case UnqualifiedIdKind::IK_TemplateId:
14058   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14059     // GetNameForDeclarator would not produce a useful name in this case.
14060     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14061     break;
14062   }
14063 }
14064 
14065 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14066 /// to introduce parameters into function prototype scope.
14067 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14068   const DeclSpec &DS = D.getDeclSpec();
14069 
14070   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14071 
14072   // C++03 [dcl.stc]p2 also permits 'auto'.
14073   StorageClass SC = SC_None;
14074   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14075     SC = SC_Register;
14076     // In C++11, the 'register' storage class specifier is deprecated.
14077     // In C++17, it is not allowed, but we tolerate it as an extension.
14078     if (getLangOpts().CPlusPlus11) {
14079       Diag(DS.getStorageClassSpecLoc(),
14080            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14081                                      : diag::warn_deprecated_register)
14082         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14083     }
14084   } else if (getLangOpts().CPlusPlus &&
14085              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14086     SC = SC_Auto;
14087   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14088     Diag(DS.getStorageClassSpecLoc(),
14089          diag::err_invalid_storage_class_in_func_decl);
14090     D.getMutableDeclSpec().ClearStorageClassSpecs();
14091   }
14092 
14093   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14094     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14095       << DeclSpec::getSpecifierName(TSCS);
14096   if (DS.isInlineSpecified())
14097     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14098         << getLangOpts().CPlusPlus17;
14099   if (DS.hasConstexprSpecifier())
14100     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14101         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14102 
14103   DiagnoseFunctionSpecifiers(DS);
14104 
14105   CheckFunctionOrTemplateParamDeclarator(S, D);
14106 
14107   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14108   QualType parmDeclType = TInfo->getType();
14109 
14110   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14111   IdentifierInfo *II = D.getIdentifier();
14112   if (II) {
14113     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14114                    ForVisibleRedeclaration);
14115     LookupName(R, S);
14116     if (R.isSingleResult()) {
14117       NamedDecl *PrevDecl = R.getFoundDecl();
14118       if (PrevDecl->isTemplateParameter()) {
14119         // Maybe we will complain about the shadowed template parameter.
14120         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14121         // Just pretend that we didn't see the previous declaration.
14122         PrevDecl = nullptr;
14123       } else if (S->isDeclScope(PrevDecl)) {
14124         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14125         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14126 
14127         // Recover by removing the name
14128         II = nullptr;
14129         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14130         D.setInvalidType(true);
14131       }
14132     }
14133   }
14134 
14135   // Temporarily put parameter variables in the translation unit, not
14136   // the enclosing context.  This prevents them from accidentally
14137   // looking like class members in C++.
14138   ParmVarDecl *New =
14139       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14140                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14141 
14142   if (D.isInvalidType())
14143     New->setInvalidDecl();
14144 
14145   assert(S->isFunctionPrototypeScope());
14146   assert(S->getFunctionPrototypeDepth() >= 1);
14147   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14148                     S->getNextFunctionPrototypeIndex());
14149 
14150   // Add the parameter declaration into this scope.
14151   S->AddDecl(New);
14152   if (II)
14153     IdResolver.AddDecl(New);
14154 
14155   ProcessDeclAttributes(S, New, D);
14156 
14157   if (D.getDeclSpec().isModulePrivateSpecified())
14158     Diag(New->getLocation(), diag::err_module_private_local)
14159         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14160         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14161 
14162   if (New->hasAttr<BlocksAttr>()) {
14163     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14164   }
14165 
14166   if (getLangOpts().OpenCL)
14167     deduceOpenCLAddressSpace(New);
14168 
14169   return New;
14170 }
14171 
14172 /// Synthesizes a variable for a parameter arising from a
14173 /// typedef.
14174 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14175                                               SourceLocation Loc,
14176                                               QualType T) {
14177   /* FIXME: setting StartLoc == Loc.
14178      Would it be worth to modify callers so as to provide proper source
14179      location for the unnamed parameters, embedding the parameter's type? */
14180   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14181                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14182                                            SC_None, nullptr);
14183   Param->setImplicit();
14184   return Param;
14185 }
14186 
14187 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14188   // Don't diagnose unused-parameter errors in template instantiations; we
14189   // will already have done so in the template itself.
14190   if (inTemplateInstantiation())
14191     return;
14192 
14193   for (const ParmVarDecl *Parameter : Parameters) {
14194     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14195         !Parameter->hasAttr<UnusedAttr>()) {
14196       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14197         << Parameter->getDeclName();
14198     }
14199   }
14200 }
14201 
14202 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14203     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14204   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14205     return;
14206 
14207   // Warn if the return value is pass-by-value and larger than the specified
14208   // threshold.
14209   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14210     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14211     if (Size > LangOpts.NumLargeByValueCopy)
14212       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14213   }
14214 
14215   // Warn if any parameter is pass-by-value and larger than the specified
14216   // threshold.
14217   for (const ParmVarDecl *Parameter : Parameters) {
14218     QualType T = Parameter->getType();
14219     if (T->isDependentType() || !T.isPODType(Context))
14220       continue;
14221     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14222     if (Size > LangOpts.NumLargeByValueCopy)
14223       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14224           << Parameter << Size;
14225   }
14226 }
14227 
14228 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14229                                   SourceLocation NameLoc, IdentifierInfo *Name,
14230                                   QualType T, TypeSourceInfo *TSInfo,
14231                                   StorageClass SC) {
14232   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14233   if (getLangOpts().ObjCAutoRefCount &&
14234       T.getObjCLifetime() == Qualifiers::OCL_None &&
14235       T->isObjCLifetimeType()) {
14236 
14237     Qualifiers::ObjCLifetime lifetime;
14238 
14239     // Special cases for arrays:
14240     //   - if it's const, use __unsafe_unretained
14241     //   - otherwise, it's an error
14242     if (T->isArrayType()) {
14243       if (!T.isConstQualified()) {
14244         if (DelayedDiagnostics.shouldDelayDiagnostics())
14245           DelayedDiagnostics.add(
14246               sema::DelayedDiagnostic::makeForbiddenType(
14247               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14248         else
14249           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14250               << TSInfo->getTypeLoc().getSourceRange();
14251       }
14252       lifetime = Qualifiers::OCL_ExplicitNone;
14253     } else {
14254       lifetime = T->getObjCARCImplicitLifetime();
14255     }
14256     T = Context.getLifetimeQualifiedType(T, lifetime);
14257   }
14258 
14259   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14260                                          Context.getAdjustedParameterType(T),
14261                                          TSInfo, SC, nullptr);
14262 
14263   // Make a note if we created a new pack in the scope of a lambda, so that
14264   // we know that references to that pack must also be expanded within the
14265   // lambda scope.
14266   if (New->isParameterPack())
14267     if (auto *LSI = getEnclosingLambda())
14268       LSI->LocalPacks.push_back(New);
14269 
14270   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14271       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14272     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14273                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14274 
14275   // Parameters can not be abstract class types.
14276   // For record types, this is done by the AbstractClassUsageDiagnoser once
14277   // the class has been completely parsed.
14278   if (!CurContext->isRecord() &&
14279       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14280                              AbstractParamType))
14281     New->setInvalidDecl();
14282 
14283   // Parameter declarators cannot be interface types. All ObjC objects are
14284   // passed by reference.
14285   if (T->isObjCObjectType()) {
14286     SourceLocation TypeEndLoc =
14287         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14288     Diag(NameLoc,
14289          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14290       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14291     T = Context.getObjCObjectPointerType(T);
14292     New->setType(T);
14293   }
14294 
14295   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14296   // duration shall not be qualified by an address-space qualifier."
14297   // Since all parameters have automatic store duration, they can not have
14298   // an address space.
14299   if (T.getAddressSpace() != LangAS::Default &&
14300       // OpenCL allows function arguments declared to be an array of a type
14301       // to be qualified with an address space.
14302       !(getLangOpts().OpenCL &&
14303         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14304     Diag(NameLoc, diag::err_arg_with_address_space);
14305     New->setInvalidDecl();
14306   }
14307 
14308   // PPC MMA non-pointer types are not allowed as function argument types.
14309   if (Context.getTargetInfo().getTriple().isPPC64() &&
14310       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14311     New->setInvalidDecl();
14312   }
14313 
14314   return New;
14315 }
14316 
14317 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14318                                            SourceLocation LocAfterDecls) {
14319   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14320 
14321   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14322   // in the declaration list shall have at least one declarator, those
14323   // declarators shall only declare identifiers from the identifier list, and
14324   // every identifier in the identifier list shall be declared.
14325   //
14326   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14327   // identifiers it names shall be declared in the declaration list."
14328   //
14329   // This is why we only diagnose in C99 and later. Note, the other conditions
14330   // listed are checked elsewhere.
14331   if (!FTI.hasPrototype) {
14332     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14333       --i;
14334       if (FTI.Params[i].Param == nullptr) {
14335         if (getLangOpts().C99) {
14336           SmallString<256> Code;
14337           llvm::raw_svector_ostream(Code)
14338               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14339           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14340               << FTI.Params[i].Ident
14341               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14342         }
14343 
14344         // Implicitly declare the argument as type 'int' for lack of a better
14345         // type.
14346         AttributeFactory attrs;
14347         DeclSpec DS(attrs);
14348         const char* PrevSpec; // unused
14349         unsigned DiagID; // unused
14350         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14351                            DiagID, Context.getPrintingPolicy());
14352         // Use the identifier location for the type source range.
14353         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14354         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14355         Declarator ParamD(DS, ParsedAttributesView::none(),
14356                           DeclaratorContext::KNRTypeList);
14357         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14358         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14359       }
14360     }
14361   }
14362 }
14363 
14364 Decl *
14365 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14366                               MultiTemplateParamsArg TemplateParameterLists,
14367                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14368   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14369   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14370   Scope *ParentScope = FnBodyScope->getParent();
14371 
14372   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14373   // we define a non-templated function definition, we will create a declaration
14374   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14375   // The base function declaration will have the equivalent of an `omp declare
14376   // variant` annotation which specifies the mangled definition as a
14377   // specialization function under the OpenMP context defined as part of the
14378   // `omp begin declare variant`.
14379   SmallVector<FunctionDecl *, 4> Bases;
14380   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14381     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14382         ParentScope, D, TemplateParameterLists, Bases);
14383 
14384   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14385   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14386   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14387 
14388   if (!Bases.empty())
14389     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14390 
14391   return Dcl;
14392 }
14393 
14394 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14395   Consumer.HandleInlineFunctionDefinition(D);
14396 }
14397 
14398 static bool
14399 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14400                                 const FunctionDecl *&PossiblePrototype) {
14401   // Don't warn about invalid declarations.
14402   if (FD->isInvalidDecl())
14403     return false;
14404 
14405   // Or declarations that aren't global.
14406   if (!FD->isGlobal())
14407     return false;
14408 
14409   // Don't warn about C++ member functions.
14410   if (isa<CXXMethodDecl>(FD))
14411     return false;
14412 
14413   // Don't warn about 'main'.
14414   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14415     if (IdentifierInfo *II = FD->getIdentifier())
14416       if (II->isStr("main") || II->isStr("efi_main"))
14417         return false;
14418 
14419   // Don't warn about inline functions.
14420   if (FD->isInlined())
14421     return false;
14422 
14423   // Don't warn about function templates.
14424   if (FD->getDescribedFunctionTemplate())
14425     return false;
14426 
14427   // Don't warn about function template specializations.
14428   if (FD->isFunctionTemplateSpecialization())
14429     return false;
14430 
14431   // Don't warn for OpenCL kernels.
14432   if (FD->hasAttr<OpenCLKernelAttr>())
14433     return false;
14434 
14435   // Don't warn on explicitly deleted functions.
14436   if (FD->isDeleted())
14437     return false;
14438 
14439   // Don't warn on implicitly local functions (such as having local-typed
14440   // parameters).
14441   if (!FD->isExternallyVisible())
14442     return false;
14443 
14444   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14445        Prev; Prev = Prev->getPreviousDecl()) {
14446     // Ignore any declarations that occur in function or method
14447     // scope, because they aren't visible from the header.
14448     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14449       continue;
14450 
14451     PossiblePrototype = Prev;
14452     return Prev->getType()->isFunctionNoProtoType();
14453   }
14454 
14455   return true;
14456 }
14457 
14458 void
14459 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14460                                    const FunctionDecl *EffectiveDefinition,
14461                                    SkipBodyInfo *SkipBody) {
14462   const FunctionDecl *Definition = EffectiveDefinition;
14463   if (!Definition &&
14464       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14465     return;
14466 
14467   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14468     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14469       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14470         // A merged copy of the same function, instantiated as a member of
14471         // the same class, is OK.
14472         if (declaresSameEntity(OrigFD, OrigDef) &&
14473             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14474                                cast<Decl>(FD->getLexicalDeclContext())))
14475           return;
14476       }
14477     }
14478   }
14479 
14480   if (canRedefineFunction(Definition, getLangOpts()))
14481     return;
14482 
14483   // Don't emit an error when this is redefinition of a typo-corrected
14484   // definition.
14485   if (TypoCorrectedFunctionDefinitions.count(Definition))
14486     return;
14487 
14488   // If we don't have a visible definition of the function, and it's inline or
14489   // a template, skip the new definition.
14490   if (SkipBody && !hasVisibleDefinition(Definition) &&
14491       (Definition->getFormalLinkage() == InternalLinkage ||
14492        Definition->isInlined() ||
14493        Definition->getDescribedFunctionTemplate() ||
14494        Definition->getNumTemplateParameterLists())) {
14495     SkipBody->ShouldSkip = true;
14496     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14497     if (auto *TD = Definition->getDescribedFunctionTemplate())
14498       makeMergedDefinitionVisible(TD);
14499     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14500     return;
14501   }
14502 
14503   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14504       Definition->getStorageClass() == SC_Extern)
14505     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14506         << FD << getLangOpts().CPlusPlus;
14507   else
14508     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14509 
14510   Diag(Definition->getLocation(), diag::note_previous_definition);
14511   FD->setInvalidDecl();
14512 }
14513 
14514 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14515                                    Sema &S) {
14516   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14517 
14518   LambdaScopeInfo *LSI = S.PushLambdaScope();
14519   LSI->CallOperator = CallOperator;
14520   LSI->Lambda = LambdaClass;
14521   LSI->ReturnType = CallOperator->getReturnType();
14522   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14523 
14524   if (LCD == LCD_None)
14525     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14526   else if (LCD == LCD_ByCopy)
14527     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14528   else if (LCD == LCD_ByRef)
14529     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14530   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14531 
14532   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14533   LSI->Mutable = !CallOperator->isConst();
14534 
14535   // Add the captures to the LSI so they can be noted as already
14536   // captured within tryCaptureVar.
14537   auto I = LambdaClass->field_begin();
14538   for (const auto &C : LambdaClass->captures()) {
14539     if (C.capturesVariable()) {
14540       VarDecl *VD = C.getCapturedVar();
14541       if (VD->isInitCapture())
14542         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14543       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14544       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14545           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14546           /*EllipsisLoc*/C.isPackExpansion()
14547                          ? C.getEllipsisLoc() : SourceLocation(),
14548           I->getType(), /*Invalid*/false);
14549 
14550     } else if (C.capturesThis()) {
14551       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14552                           C.getCaptureKind() == LCK_StarThis);
14553     } else {
14554       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14555                              I->getType());
14556     }
14557     ++I;
14558   }
14559 }
14560 
14561 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14562                                     SkipBodyInfo *SkipBody,
14563                                     FnBodyKind BodyKind) {
14564   if (!D) {
14565     // Parsing the function declaration failed in some way. Push on a fake scope
14566     // anyway so we can try to parse the function body.
14567     PushFunctionScope();
14568     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14569     return D;
14570   }
14571 
14572   FunctionDecl *FD = nullptr;
14573 
14574   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14575     FD = FunTmpl->getTemplatedDecl();
14576   else
14577     FD = cast<FunctionDecl>(D);
14578 
14579   // Do not push if it is a lambda because one is already pushed when building
14580   // the lambda in ActOnStartOfLambdaDefinition().
14581   if (!isLambdaCallOperator(FD))
14582     PushExpressionEvaluationContext(
14583         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14584                           : ExprEvalContexts.back().Context);
14585 
14586   // Check for defining attributes before the check for redefinition.
14587   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14588     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14589     FD->dropAttr<AliasAttr>();
14590     FD->setInvalidDecl();
14591   }
14592   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14593     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14594     FD->dropAttr<IFuncAttr>();
14595     FD->setInvalidDecl();
14596   }
14597 
14598   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14599     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14600         Ctor->isDefaultConstructor() &&
14601         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14602       // If this is an MS ABI dllexport default constructor, instantiate any
14603       // default arguments.
14604       InstantiateDefaultCtorDefaultArgs(Ctor);
14605     }
14606   }
14607 
14608   // See if this is a redefinition. If 'will have body' (or similar) is already
14609   // set, then these checks were already performed when it was set.
14610   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14611       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14612     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14613 
14614     // If we're skipping the body, we're done. Don't enter the scope.
14615     if (SkipBody && SkipBody->ShouldSkip)
14616       return D;
14617   }
14618 
14619   // Mark this function as "will have a body eventually".  This lets users to
14620   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14621   // this function.
14622   FD->setWillHaveBody();
14623 
14624   // If we are instantiating a generic lambda call operator, push
14625   // a LambdaScopeInfo onto the function stack.  But use the information
14626   // that's already been calculated (ActOnLambdaExpr) to prime the current
14627   // LambdaScopeInfo.
14628   // When the template operator is being specialized, the LambdaScopeInfo,
14629   // has to be properly restored so that tryCaptureVariable doesn't try
14630   // and capture any new variables. In addition when calculating potential
14631   // captures during transformation of nested lambdas, it is necessary to
14632   // have the LSI properly restored.
14633   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14634     assert(inTemplateInstantiation() &&
14635            "There should be an active template instantiation on the stack "
14636            "when instantiating a generic lambda!");
14637     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14638   } else {
14639     // Enter a new function scope
14640     PushFunctionScope();
14641   }
14642 
14643   // Builtin functions cannot be defined.
14644   if (unsigned BuiltinID = FD->getBuiltinID()) {
14645     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14646         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14647       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14648       FD->setInvalidDecl();
14649     }
14650   }
14651 
14652   // The return type of a function definition must be complete (C99 6.9.1p3),
14653   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14654   QualType ResultType = FD->getReturnType();
14655   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14656       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14657       RequireCompleteType(FD->getLocation(), ResultType,
14658                           diag::err_func_def_incomplete_result))
14659     FD->setInvalidDecl();
14660 
14661   if (FnBodyScope)
14662     PushDeclContext(FnBodyScope, FD);
14663 
14664   // Check the validity of our function parameters
14665   if (BodyKind != FnBodyKind::Delete)
14666     CheckParmsForFunctionDef(FD->parameters(),
14667                              /*CheckParameterNames=*/true);
14668 
14669   // Add non-parameter declarations already in the function to the current
14670   // scope.
14671   if (FnBodyScope) {
14672     for (Decl *NPD : FD->decls()) {
14673       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14674       if (!NonParmDecl)
14675         continue;
14676       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14677              "parameters should not be in newly created FD yet");
14678 
14679       // If the decl has a name, make it accessible in the current scope.
14680       if (NonParmDecl->getDeclName())
14681         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14682 
14683       // Similarly, dive into enums and fish their constants out, making them
14684       // accessible in this scope.
14685       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14686         for (auto *EI : ED->enumerators())
14687           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14688       }
14689     }
14690   }
14691 
14692   // Introduce our parameters into the function scope
14693   for (auto Param : FD->parameters()) {
14694     Param->setOwningFunction(FD);
14695 
14696     // If this has an identifier, add it to the scope stack.
14697     if (Param->getIdentifier() && FnBodyScope) {
14698       CheckShadow(FnBodyScope, Param);
14699 
14700       PushOnScopeChains(Param, FnBodyScope);
14701     }
14702   }
14703 
14704   // Ensure that the function's exception specification is instantiated.
14705   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14706     ResolveExceptionSpec(D->getLocation(), FPT);
14707 
14708   // dllimport cannot be applied to non-inline function definitions.
14709   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14710       !FD->isTemplateInstantiation()) {
14711     assert(!FD->hasAttr<DLLExportAttr>());
14712     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14713     FD->setInvalidDecl();
14714     return D;
14715   }
14716   // We want to attach documentation to original Decl (which might be
14717   // a function template).
14718   ActOnDocumentableDecl(D);
14719   if (getCurLexicalContext()->isObjCContainer() &&
14720       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14721       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14722     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14723 
14724   return D;
14725 }
14726 
14727 /// Given the set of return statements within a function body,
14728 /// compute the variables that are subject to the named return value
14729 /// optimization.
14730 ///
14731 /// Each of the variables that is subject to the named return value
14732 /// optimization will be marked as NRVO variables in the AST, and any
14733 /// return statement that has a marked NRVO variable as its NRVO candidate can
14734 /// use the named return value optimization.
14735 ///
14736 /// This function applies a very simplistic algorithm for NRVO: if every return
14737 /// statement in the scope of a variable has the same NRVO candidate, that
14738 /// candidate is an NRVO variable.
14739 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14740   ReturnStmt **Returns = Scope->Returns.data();
14741 
14742   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14743     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14744       if (!NRVOCandidate->isNRVOVariable())
14745         Returns[I]->setNRVOCandidate(nullptr);
14746     }
14747   }
14748 }
14749 
14750 bool Sema::canDelayFunctionBody(const Declarator &D) {
14751   // We can't delay parsing the body of a constexpr function template (yet).
14752   if (D.getDeclSpec().hasConstexprSpecifier())
14753     return false;
14754 
14755   // We can't delay parsing the body of a function template with a deduced
14756   // return type (yet).
14757   if (D.getDeclSpec().hasAutoTypeSpec()) {
14758     // If the placeholder introduces a non-deduced trailing return type,
14759     // we can still delay parsing it.
14760     if (D.getNumTypeObjects()) {
14761       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14762       if (Outer.Kind == DeclaratorChunk::Function &&
14763           Outer.Fun.hasTrailingReturnType()) {
14764         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14765         return Ty.isNull() || !Ty->isUndeducedType();
14766       }
14767     }
14768     return false;
14769   }
14770 
14771   return true;
14772 }
14773 
14774 bool Sema::canSkipFunctionBody(Decl *D) {
14775   // We cannot skip the body of a function (or function template) which is
14776   // constexpr, since we may need to evaluate its body in order to parse the
14777   // rest of the file.
14778   // We cannot skip the body of a function with an undeduced return type,
14779   // because any callers of that function need to know the type.
14780   if (const FunctionDecl *FD = D->getAsFunction()) {
14781     if (FD->isConstexpr())
14782       return false;
14783     // We can't simply call Type::isUndeducedType here, because inside template
14784     // auto can be deduced to a dependent type, which is not considered
14785     // "undeduced".
14786     if (FD->getReturnType()->getContainedDeducedType())
14787       return false;
14788   }
14789   return Consumer.shouldSkipFunctionBody(D);
14790 }
14791 
14792 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14793   if (!Decl)
14794     return nullptr;
14795   if (FunctionDecl *FD = Decl->getAsFunction())
14796     FD->setHasSkippedBody();
14797   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14798     MD->setHasSkippedBody();
14799   return Decl;
14800 }
14801 
14802 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14803   return ActOnFinishFunctionBody(D, BodyArg, false);
14804 }
14805 
14806 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14807 /// body.
14808 class ExitFunctionBodyRAII {
14809 public:
14810   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14811   ~ExitFunctionBodyRAII() {
14812     if (!IsLambda)
14813       S.PopExpressionEvaluationContext();
14814   }
14815 
14816 private:
14817   Sema &S;
14818   bool IsLambda = false;
14819 };
14820 
14821 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14822   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14823 
14824   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14825     if (EscapeInfo.count(BD))
14826       return EscapeInfo[BD];
14827 
14828     bool R = false;
14829     const BlockDecl *CurBD = BD;
14830 
14831     do {
14832       R = !CurBD->doesNotEscape();
14833       if (R)
14834         break;
14835       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14836     } while (CurBD);
14837 
14838     return EscapeInfo[BD] = R;
14839   };
14840 
14841   // If the location where 'self' is implicitly retained is inside a escaping
14842   // block, emit a diagnostic.
14843   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14844        S.ImplicitlyRetainedSelfLocs)
14845     if (IsOrNestedInEscapingBlock(P.second))
14846       S.Diag(P.first, diag::warn_implicitly_retains_self)
14847           << FixItHint::CreateInsertion(P.first, "self->");
14848 }
14849 
14850 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14851                                     bool IsInstantiation) {
14852   FunctionScopeInfo *FSI = getCurFunction();
14853   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14854 
14855   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14856     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14857 
14858   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14859   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14860 
14861   if (getLangOpts().Coroutines && FSI->isCoroutine())
14862     CheckCompletedCoroutineBody(FD, Body);
14863 
14864   {
14865     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14866     // one is already popped when finishing the lambda in BuildLambdaExpr().
14867     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14868     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14869 
14870     if (FD) {
14871       FD->setBody(Body);
14872       FD->setWillHaveBody(false);
14873 
14874       if (getLangOpts().CPlusPlus14) {
14875         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14876             FD->getReturnType()->isUndeducedType()) {
14877           // For a function with a deduced result type to return void,
14878           // the result type as written must be 'auto' or 'decltype(auto)',
14879           // possibly cv-qualified or constrained, but not ref-qualified.
14880           if (!FD->getReturnType()->getAs<AutoType>()) {
14881             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14882                 << FD->getReturnType();
14883             FD->setInvalidDecl();
14884           } else {
14885             // Falling off the end of the function is the same as 'return;'.
14886             Expr *Dummy = nullptr;
14887             if (DeduceFunctionTypeFromReturnExpr(
14888                     FD, dcl->getLocation(), Dummy,
14889                     FD->getReturnType()->getAs<AutoType>()))
14890               FD->setInvalidDecl();
14891           }
14892         }
14893       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14894         // In C++11, we don't use 'auto' deduction rules for lambda call
14895         // operators because we don't support return type deduction.
14896         auto *LSI = getCurLambda();
14897         if (LSI->HasImplicitReturnType) {
14898           deduceClosureReturnType(*LSI);
14899 
14900           // C++11 [expr.prim.lambda]p4:
14901           //   [...] if there are no return statements in the compound-statement
14902           //   [the deduced type is] the type void
14903           QualType RetType =
14904               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14905 
14906           // Update the return type to the deduced type.
14907           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14908           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14909                                               Proto->getExtProtoInfo()));
14910         }
14911       }
14912 
14913       // If the function implicitly returns zero (like 'main') or is naked,
14914       // don't complain about missing return statements.
14915       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14916         WP.disableCheckFallThrough();
14917 
14918       // MSVC permits the use of pure specifier (=0) on function definition,
14919       // defined at class scope, warn about this non-standard construct.
14920       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14921         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14922 
14923       if (!FD->isInvalidDecl()) {
14924         // Don't diagnose unused parameters of defaulted, deleted or naked
14925         // functions.
14926         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14927             !FD->hasAttr<NakedAttr>())
14928           DiagnoseUnusedParameters(FD->parameters());
14929         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14930                                                FD->getReturnType(), FD);
14931 
14932         // If this is a structor, we need a vtable.
14933         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14934           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14935         else if (CXXDestructorDecl *Destructor =
14936                      dyn_cast<CXXDestructorDecl>(FD))
14937           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14938 
14939         // Try to apply the named return value optimization. We have to check
14940         // if we can do this here because lambdas keep return statements around
14941         // to deduce an implicit return type.
14942         if (FD->getReturnType()->isRecordType() &&
14943             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14944           computeNRVO(Body, FSI);
14945       }
14946 
14947       // GNU warning -Wmissing-prototypes:
14948       //   Warn if a global function is defined without a previous
14949       //   prototype declaration. This warning is issued even if the
14950       //   definition itself provides a prototype. The aim is to detect
14951       //   global functions that fail to be declared in header files.
14952       const FunctionDecl *PossiblePrototype = nullptr;
14953       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14954         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14955 
14956         if (PossiblePrototype) {
14957           // We found a declaration that is not a prototype,
14958           // but that could be a zero-parameter prototype
14959           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14960             TypeLoc TL = TI->getTypeLoc();
14961             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14962               Diag(PossiblePrototype->getLocation(),
14963                    diag::note_declaration_not_a_prototype)
14964                   << (FD->getNumParams() != 0)
14965                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14966                                                     FTL.getRParenLoc(), "void")
14967                                               : FixItHint{});
14968           }
14969         } else {
14970           // Returns true if the token beginning at this Loc is `const`.
14971           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14972                                   const LangOptions &LangOpts) {
14973             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14974             if (LocInfo.first.isInvalid())
14975               return false;
14976 
14977             bool Invalid = false;
14978             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14979             if (Invalid)
14980               return false;
14981 
14982             if (LocInfo.second > Buffer.size())
14983               return false;
14984 
14985             const char *LexStart = Buffer.data() + LocInfo.second;
14986             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14987 
14988             return StartTok.consume_front("const") &&
14989                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14990                     StartTok.startswith("/*") || StartTok.startswith("//"));
14991           };
14992 
14993           auto findBeginLoc = [&]() {
14994             // If the return type has `const` qualifier, we want to insert
14995             // `static` before `const` (and not before the typename).
14996             if ((FD->getReturnType()->isAnyPointerType() &&
14997                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14998                 FD->getReturnType().isConstQualified()) {
14999               // But only do this if we can determine where the `const` is.
15000 
15001               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15002                                getLangOpts()))
15003 
15004                 return FD->getBeginLoc();
15005             }
15006             return FD->getTypeSpecStartLoc();
15007           };
15008           Diag(FD->getTypeSpecStartLoc(),
15009                diag::note_static_for_internal_linkage)
15010               << /* function */ 1
15011               << (FD->getStorageClass() == SC_None
15012                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15013                       : FixItHint{});
15014         }
15015       }
15016 
15017       // If the function being defined does not have a prototype, then we may
15018       // need to diagnose it as changing behavior in C2x because we now know
15019       // whether the function accepts arguments or not. This only handles the
15020       // case where the definition has no prototype but does have parameters
15021       // and either there is no previous potential prototype, or the previous
15022       // potential prototype also has no actual prototype. This handles cases
15023       // like:
15024       //   void f(); void f(a) int a; {}
15025       //   void g(a) int a; {}
15026       // See MergeFunctionDecl() for other cases of the behavior change
15027       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15028       // type without a prototype.
15029       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15030           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15031                                   !PossiblePrototype->isImplicit()))) {
15032         // The function definition has parameters, so this will change behavior
15033         // in C2x. If there is a possible prototype, it comes before the
15034         // function definition.
15035         // FIXME: The declaration may have already been diagnosed as being
15036         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15037         // there's no way to test for the "changes behavior" condition in
15038         // SemaType.cpp when forming the declaration's function type. So, we do
15039         // this awkward dance instead.
15040         //
15041         // If we have a possible prototype and it declares a function with a
15042         // prototype, we don't want to diagnose it; if we have a possible
15043         // prototype and it has no prototype, it may have already been
15044         // diagnosed in SemaType.cpp as deprecated depending on whether
15045         // -Wstrict-prototypes is enabled. If we already warned about it being
15046         // deprecated, add a note that it also changes behavior. If we didn't
15047         // warn about it being deprecated (because the diagnostic is not
15048         // enabled), warn now that it is deprecated and changes behavior.
15049 
15050         // This K&R C function definition definitely changes behavior in C2x,
15051         // so diagnose it.
15052         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15053             << /*definition*/ 1 << /* not supported in C2x */ 0;
15054 
15055         // If we have a possible prototype for the function which is a user-
15056         // visible declaration, we already tested that it has no prototype.
15057         // This will change behavior in C2x. This gets a warning rather than a
15058         // note because it's the same behavior-changing problem as with the
15059         // definition.
15060         if (PossiblePrototype)
15061           Diag(PossiblePrototype->getLocation(),
15062                diag::warn_non_prototype_changes_behavior)
15063               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15064               << /*definition*/ 1;
15065       }
15066 
15067       // Warn on CPUDispatch with an actual body.
15068       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15069         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15070           if (!CmpndBody->body_empty())
15071             Diag(CmpndBody->body_front()->getBeginLoc(),
15072                  diag::warn_dispatch_body_ignored);
15073 
15074       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15075         const CXXMethodDecl *KeyFunction;
15076         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15077             MD->isVirtual() &&
15078             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15079             MD == KeyFunction->getCanonicalDecl()) {
15080           // Update the key-function state if necessary for this ABI.
15081           if (FD->isInlined() &&
15082               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15083             Context.setNonKeyFunction(MD);
15084 
15085             // If the newly-chosen key function is already defined, then we
15086             // need to mark the vtable as used retroactively.
15087             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15088             const FunctionDecl *Definition;
15089             if (KeyFunction && KeyFunction->isDefined(Definition))
15090               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15091           } else {
15092             // We just defined they key function; mark the vtable as used.
15093             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15094           }
15095         }
15096       }
15097 
15098       assert(
15099           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15100           "Function parsing confused");
15101     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15102       assert(MD == getCurMethodDecl() && "Method parsing confused");
15103       MD->setBody(Body);
15104       if (!MD->isInvalidDecl()) {
15105         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15106                                                MD->getReturnType(), MD);
15107 
15108         if (Body)
15109           computeNRVO(Body, FSI);
15110       }
15111       if (FSI->ObjCShouldCallSuper) {
15112         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15113             << MD->getSelector().getAsString();
15114         FSI->ObjCShouldCallSuper = false;
15115       }
15116       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15117         const ObjCMethodDecl *InitMethod = nullptr;
15118         bool isDesignated =
15119             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15120         assert(isDesignated && InitMethod);
15121         (void)isDesignated;
15122 
15123         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15124           auto IFace = MD->getClassInterface();
15125           if (!IFace)
15126             return false;
15127           auto SuperD = IFace->getSuperClass();
15128           if (!SuperD)
15129             return false;
15130           return SuperD->getIdentifier() ==
15131                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15132         };
15133         // Don't issue this warning for unavailable inits or direct subclasses
15134         // of NSObject.
15135         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15136           Diag(MD->getLocation(),
15137                diag::warn_objc_designated_init_missing_super_call);
15138           Diag(InitMethod->getLocation(),
15139                diag::note_objc_designated_init_marked_here);
15140         }
15141         FSI->ObjCWarnForNoDesignatedInitChain = false;
15142       }
15143       if (FSI->ObjCWarnForNoInitDelegation) {
15144         // Don't issue this warning for unavaialable inits.
15145         if (!MD->isUnavailable())
15146           Diag(MD->getLocation(),
15147                diag::warn_objc_secondary_init_missing_init_call);
15148         FSI->ObjCWarnForNoInitDelegation = false;
15149       }
15150 
15151       diagnoseImplicitlyRetainedSelf(*this);
15152     } else {
15153       // Parsing the function declaration failed in some way. Pop the fake scope
15154       // we pushed on.
15155       PopFunctionScopeInfo(ActivePolicy, dcl);
15156       return nullptr;
15157     }
15158 
15159     if (Body && FSI->HasPotentialAvailabilityViolations)
15160       DiagnoseUnguardedAvailabilityViolations(dcl);
15161 
15162     assert(!FSI->ObjCShouldCallSuper &&
15163            "This should only be set for ObjC methods, which should have been "
15164            "handled in the block above.");
15165 
15166     // Verify and clean out per-function state.
15167     if (Body && (!FD || !FD->isDefaulted())) {
15168       // C++ constructors that have function-try-blocks can't have return
15169       // statements in the handlers of that block. (C++ [except.handle]p14)
15170       // Verify this.
15171       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15172         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15173 
15174       // Verify that gotos and switch cases don't jump into scopes illegally.
15175       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15176         DiagnoseInvalidJumps(Body);
15177 
15178       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15179         if (!Destructor->getParent()->isDependentType())
15180           CheckDestructor(Destructor);
15181 
15182         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15183                                                Destructor->getParent());
15184       }
15185 
15186       // If any errors have occurred, clear out any temporaries that may have
15187       // been leftover. This ensures that these temporaries won't be picked up
15188       // for deletion in some later function.
15189       if (hasUncompilableErrorOccurred() ||
15190           getDiagnostics().getSuppressAllDiagnostics()) {
15191         DiscardCleanupsInEvaluationContext();
15192       }
15193       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15194         // Since the body is valid, issue any analysis-based warnings that are
15195         // enabled.
15196         ActivePolicy = &WP;
15197       }
15198 
15199       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15200           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15201         FD->setInvalidDecl();
15202 
15203       if (FD && FD->hasAttr<NakedAttr>()) {
15204         for (const Stmt *S : Body->children()) {
15205           // Allow local register variables without initializer as they don't
15206           // require prologue.
15207           bool RegisterVariables = false;
15208           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15209             for (const auto *Decl : DS->decls()) {
15210               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15211                 RegisterVariables =
15212                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15213                 if (!RegisterVariables)
15214                   break;
15215               }
15216             }
15217           }
15218           if (RegisterVariables)
15219             continue;
15220           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15221             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15222             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15223             FD->setInvalidDecl();
15224             break;
15225           }
15226         }
15227       }
15228 
15229       assert(ExprCleanupObjects.size() ==
15230                  ExprEvalContexts.back().NumCleanupObjects &&
15231              "Leftover temporaries in function");
15232       assert(!Cleanup.exprNeedsCleanups() &&
15233              "Unaccounted cleanups in function");
15234       assert(MaybeODRUseExprs.empty() &&
15235              "Leftover expressions for odr-use checking");
15236     }
15237   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15238     // the declaration context below. Otherwise, we're unable to transform
15239     // 'this' expressions when transforming immediate context functions.
15240 
15241   if (!IsInstantiation)
15242     PopDeclContext();
15243 
15244   PopFunctionScopeInfo(ActivePolicy, dcl);
15245   // If any errors have occurred, clear out any temporaries that may have
15246   // been leftover. This ensures that these temporaries won't be picked up for
15247   // deletion in some later function.
15248   if (hasUncompilableErrorOccurred()) {
15249     DiscardCleanupsInEvaluationContext();
15250   }
15251 
15252   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15253                                   !LangOpts.OMPTargetTriples.empty())) ||
15254              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15255     auto ES = getEmissionStatus(FD);
15256     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15257         ES == Sema::FunctionEmissionStatus::Unknown)
15258       DeclsToCheckForDeferredDiags.insert(FD);
15259   }
15260 
15261   if (FD && !FD->isDeleted())
15262     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15263 
15264   return dcl;
15265 }
15266 
15267 /// When we finish delayed parsing of an attribute, we must attach it to the
15268 /// relevant Decl.
15269 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15270                                        ParsedAttributes &Attrs) {
15271   // Always attach attributes to the underlying decl.
15272   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15273     D = TD->getTemplatedDecl();
15274   ProcessDeclAttributeList(S, D, Attrs);
15275 
15276   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15277     if (Method->isStatic())
15278       checkThisInStaticMemberFunctionAttributes(Method);
15279 }
15280 
15281 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15282 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15283 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15284                                           IdentifierInfo &II, Scope *S) {
15285   // It is not valid to implicitly define a function in C2x.
15286   assert(LangOpts.implicitFunctionsAllowed() &&
15287          "Implicit function declarations aren't allowed in this language mode");
15288 
15289   // Find the scope in which the identifier is injected and the corresponding
15290   // DeclContext.
15291   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15292   // In that case, we inject the declaration into the translation unit scope
15293   // instead.
15294   Scope *BlockScope = S;
15295   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15296     BlockScope = BlockScope->getParent();
15297 
15298   Scope *ContextScope = BlockScope;
15299   while (!ContextScope->getEntity())
15300     ContextScope = ContextScope->getParent();
15301   ContextRAII SavedContext(*this, ContextScope->getEntity());
15302 
15303   // Before we produce a declaration for an implicitly defined
15304   // function, see whether there was a locally-scoped declaration of
15305   // this name as a function or variable. If so, use that
15306   // (non-visible) declaration, and complain about it.
15307   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15308   if (ExternCPrev) {
15309     // We still need to inject the function into the enclosing block scope so
15310     // that later (non-call) uses can see it.
15311     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15312 
15313     // C89 footnote 38:
15314     //   If in fact it is not defined as having type "function returning int",
15315     //   the behavior is undefined.
15316     if (!isa<FunctionDecl>(ExternCPrev) ||
15317         !Context.typesAreCompatible(
15318             cast<FunctionDecl>(ExternCPrev)->getType(),
15319             Context.getFunctionNoProtoType(Context.IntTy))) {
15320       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15321           << ExternCPrev << !getLangOpts().C99;
15322       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15323       return ExternCPrev;
15324     }
15325   }
15326 
15327   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15328   unsigned diag_id;
15329   if (II.getName().startswith("__builtin_"))
15330     diag_id = diag::warn_builtin_unknown;
15331   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15332   else if (getLangOpts().C99)
15333     diag_id = diag::ext_implicit_function_decl_c99;
15334   else
15335     diag_id = diag::warn_implicit_function_decl;
15336 
15337   TypoCorrection Corrected;
15338   // Because typo correction is expensive, only do it if the implicit
15339   // function declaration is going to be treated as an error.
15340   //
15341   // Perform the corection before issuing the main diagnostic, as some consumers
15342   // use typo-correction callbacks to enhance the main diagnostic.
15343   if (S && !ExternCPrev &&
15344       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15345     DeclFilterCCC<FunctionDecl> CCC{};
15346     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15347                             S, nullptr, CCC, CTK_NonError);
15348   }
15349 
15350   Diag(Loc, diag_id) << &II;
15351   if (Corrected) {
15352     // If the correction is going to suggest an implicitly defined function,
15353     // skip the correction as not being a particularly good idea.
15354     bool Diagnose = true;
15355     if (const auto *D = Corrected.getCorrectionDecl())
15356       Diagnose = !D->isImplicit();
15357     if (Diagnose)
15358       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15359                    /*ErrorRecovery*/ false);
15360   }
15361 
15362   // If we found a prior declaration of this function, don't bother building
15363   // another one. We've already pushed that one into scope, so there's nothing
15364   // more to do.
15365   if (ExternCPrev)
15366     return ExternCPrev;
15367 
15368   // Set a Declarator for the implicit definition: int foo();
15369   const char *Dummy;
15370   AttributeFactory attrFactory;
15371   DeclSpec DS(attrFactory);
15372   unsigned DiagID;
15373   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15374                                   Context.getPrintingPolicy());
15375   (void)Error; // Silence warning.
15376   assert(!Error && "Error setting up implicit decl!");
15377   SourceLocation NoLoc;
15378   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15379   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15380                                              /*IsAmbiguous=*/false,
15381                                              /*LParenLoc=*/NoLoc,
15382                                              /*Params=*/nullptr,
15383                                              /*NumParams=*/0,
15384                                              /*EllipsisLoc=*/NoLoc,
15385                                              /*RParenLoc=*/NoLoc,
15386                                              /*RefQualifierIsLvalueRef=*/true,
15387                                              /*RefQualifierLoc=*/NoLoc,
15388                                              /*MutableLoc=*/NoLoc, EST_None,
15389                                              /*ESpecRange=*/SourceRange(),
15390                                              /*Exceptions=*/nullptr,
15391                                              /*ExceptionRanges=*/nullptr,
15392                                              /*NumExceptions=*/0,
15393                                              /*NoexceptExpr=*/nullptr,
15394                                              /*ExceptionSpecTokens=*/nullptr,
15395                                              /*DeclsInPrototype=*/None, Loc,
15396                                              Loc, D),
15397                 std::move(DS.getAttributes()), SourceLocation());
15398   D.SetIdentifier(&II, Loc);
15399 
15400   // Insert this function into the enclosing block scope.
15401   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15402   FD->setImplicit();
15403 
15404   AddKnownFunctionAttributes(FD);
15405 
15406   return FD;
15407 }
15408 
15409 /// If this function is a C++ replaceable global allocation function
15410 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15411 /// adds any function attributes that we know a priori based on the standard.
15412 ///
15413 /// We need to check for duplicate attributes both here and where user-written
15414 /// attributes are applied to declarations.
15415 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15416     FunctionDecl *FD) {
15417   if (FD->isInvalidDecl())
15418     return;
15419 
15420   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15421       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15422     return;
15423 
15424   Optional<unsigned> AlignmentParam;
15425   bool IsNothrow = false;
15426   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15427     return;
15428 
15429   // C++2a [basic.stc.dynamic.allocation]p4:
15430   //   An allocation function that has a non-throwing exception specification
15431   //   indicates failure by returning a null pointer value. Any other allocation
15432   //   function never returns a null pointer value and indicates failure only by
15433   //   throwing an exception [...]
15434   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15435     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15436 
15437   // C++2a [basic.stc.dynamic.allocation]p2:
15438   //   An allocation function attempts to allocate the requested amount of
15439   //   storage. [...] If the request succeeds, the value returned by a
15440   //   replaceable allocation function is a [...] pointer value p0 different
15441   //   from any previously returned value p1 [...]
15442   //
15443   // However, this particular information is being added in codegen,
15444   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15445 
15446   // C++2a [basic.stc.dynamic.allocation]p2:
15447   //   An allocation function attempts to allocate the requested amount of
15448   //   storage. If it is successful, it returns the address of the start of a
15449   //   block of storage whose length in bytes is at least as large as the
15450   //   requested size.
15451   if (!FD->hasAttr<AllocSizeAttr>()) {
15452     FD->addAttr(AllocSizeAttr::CreateImplicit(
15453         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15454         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15455   }
15456 
15457   // C++2a [basic.stc.dynamic.allocation]p3:
15458   //   For an allocation function [...], the pointer returned on a successful
15459   //   call shall represent the address of storage that is aligned as follows:
15460   //   (3.1) If the allocation function takes an argument of type
15461   //         std​::​align_­val_­t, the storage will have the alignment
15462   //         specified by the value of this argument.
15463   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15464     FD->addAttr(AllocAlignAttr::CreateImplicit(
15465         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15466   }
15467 
15468   // FIXME:
15469   // C++2a [basic.stc.dynamic.allocation]p3:
15470   //   For an allocation function [...], the pointer returned on a successful
15471   //   call shall represent the address of storage that is aligned as follows:
15472   //   (3.2) Otherwise, if the allocation function is named operator new[],
15473   //         the storage is aligned for any object that does not have
15474   //         new-extended alignment ([basic.align]) and is no larger than the
15475   //         requested size.
15476   //   (3.3) Otherwise, the storage is aligned for any object that does not
15477   //         have new-extended alignment and is of the requested size.
15478 }
15479 
15480 /// Adds any function attributes that we know a priori based on
15481 /// the declaration of this function.
15482 ///
15483 /// These attributes can apply both to implicitly-declared builtins
15484 /// (like __builtin___printf_chk) or to library-declared functions
15485 /// like NSLog or printf.
15486 ///
15487 /// We need to check for duplicate attributes both here and where user-written
15488 /// attributes are applied to declarations.
15489 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15490   if (FD->isInvalidDecl())
15491     return;
15492 
15493   // If this is a built-in function, map its builtin attributes to
15494   // actual attributes.
15495   if (unsigned BuiltinID = FD->getBuiltinID()) {
15496     // Handle printf-formatting attributes.
15497     unsigned FormatIdx;
15498     bool HasVAListArg;
15499     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15500       if (!FD->hasAttr<FormatAttr>()) {
15501         const char *fmt = "printf";
15502         unsigned int NumParams = FD->getNumParams();
15503         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15504             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15505           fmt = "NSString";
15506         FD->addAttr(FormatAttr::CreateImplicit(Context,
15507                                                &Context.Idents.get(fmt),
15508                                                FormatIdx+1,
15509                                                HasVAListArg ? 0 : FormatIdx+2,
15510                                                FD->getLocation()));
15511       }
15512     }
15513     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15514                                              HasVAListArg)) {
15515      if (!FD->hasAttr<FormatAttr>())
15516        FD->addAttr(FormatAttr::CreateImplicit(Context,
15517                                               &Context.Idents.get("scanf"),
15518                                               FormatIdx+1,
15519                                               HasVAListArg ? 0 : FormatIdx+2,
15520                                               FD->getLocation()));
15521     }
15522 
15523     // Handle automatically recognized callbacks.
15524     SmallVector<int, 4> Encoding;
15525     if (!FD->hasAttr<CallbackAttr>() &&
15526         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15527       FD->addAttr(CallbackAttr::CreateImplicit(
15528           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15529 
15530     // Mark const if we don't care about errno and that is the only thing
15531     // preventing the function from being const. This allows IRgen to use LLVM
15532     // intrinsics for such functions.
15533     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15534         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15535       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15536 
15537     // We make "fma" on GNU or Windows const because we know it does not set
15538     // errno in those environments even though it could set errno based on the
15539     // C standard.
15540     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15541     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15542         !FD->hasAttr<ConstAttr>()) {
15543       switch (BuiltinID) {
15544       case Builtin::BI__builtin_fma:
15545       case Builtin::BI__builtin_fmaf:
15546       case Builtin::BI__builtin_fmal:
15547       case Builtin::BIfma:
15548       case Builtin::BIfmaf:
15549       case Builtin::BIfmal:
15550         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15551         break;
15552       default:
15553         break;
15554       }
15555     }
15556 
15557     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15558         !FD->hasAttr<ReturnsTwiceAttr>())
15559       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15560                                          FD->getLocation()));
15561     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15562       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15563     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15564       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15565     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15566       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15567     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15568         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15569       // Add the appropriate attribute, depending on the CUDA compilation mode
15570       // and which target the builtin belongs to. For example, during host
15571       // compilation, aux builtins are __device__, while the rest are __host__.
15572       if (getLangOpts().CUDAIsDevice !=
15573           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15574         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15575       else
15576         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15577     }
15578 
15579     // Add known guaranteed alignment for allocation functions.
15580     switch (BuiltinID) {
15581     case Builtin::BImemalign:
15582     case Builtin::BIaligned_alloc:
15583       if (!FD->hasAttr<AllocAlignAttr>())
15584         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15585                                                    FD->getLocation()));
15586       break;
15587     default:
15588       break;
15589     }
15590 
15591     // Add allocsize attribute for allocation functions.
15592     switch (BuiltinID) {
15593     case Builtin::BIcalloc:
15594       FD->addAttr(AllocSizeAttr::CreateImplicit(
15595           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15596       break;
15597     case Builtin::BImemalign:
15598     case Builtin::BIaligned_alloc:
15599     case Builtin::BIrealloc:
15600       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15601                                                 ParamIdx(), FD->getLocation()));
15602       break;
15603     case Builtin::BImalloc:
15604       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15605                                                 ParamIdx(), FD->getLocation()));
15606       break;
15607     default:
15608       break;
15609     }
15610   }
15611 
15612   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15613 
15614   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15615   // throw, add an implicit nothrow attribute to any extern "C" function we come
15616   // across.
15617   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15618       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15619     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15620     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15621       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15622   }
15623 
15624   IdentifierInfo *Name = FD->getIdentifier();
15625   if (!Name)
15626     return;
15627   if ((!getLangOpts().CPlusPlus &&
15628        FD->getDeclContext()->isTranslationUnit()) ||
15629       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15630        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15631        LinkageSpecDecl::lang_c)) {
15632     // Okay: this could be a libc/libm/Objective-C function we know
15633     // about.
15634   } else
15635     return;
15636 
15637   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15638     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15639     // target-specific builtins, perhaps?
15640     if (!FD->hasAttr<FormatAttr>())
15641       FD->addAttr(FormatAttr::CreateImplicit(Context,
15642                                              &Context.Idents.get("printf"), 2,
15643                                              Name->isStr("vasprintf") ? 0 : 3,
15644                                              FD->getLocation()));
15645   }
15646 
15647   if (Name->isStr("__CFStringMakeConstantString")) {
15648     // We already have a __builtin___CFStringMakeConstantString,
15649     // but builds that use -fno-constant-cfstrings don't go through that.
15650     if (!FD->hasAttr<FormatArgAttr>())
15651       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15652                                                 FD->getLocation()));
15653   }
15654 }
15655 
15656 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15657                                     TypeSourceInfo *TInfo) {
15658   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15659   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15660 
15661   if (!TInfo) {
15662     assert(D.isInvalidType() && "no declarator info for valid type");
15663     TInfo = Context.getTrivialTypeSourceInfo(T);
15664   }
15665 
15666   // Scope manipulation handled by caller.
15667   TypedefDecl *NewTD =
15668       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15669                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15670 
15671   // Bail out immediately if we have an invalid declaration.
15672   if (D.isInvalidType()) {
15673     NewTD->setInvalidDecl();
15674     return NewTD;
15675   }
15676 
15677   if (D.getDeclSpec().isModulePrivateSpecified()) {
15678     if (CurContext->isFunctionOrMethod())
15679       Diag(NewTD->getLocation(), diag::err_module_private_local)
15680           << 2 << NewTD
15681           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15682           << FixItHint::CreateRemoval(
15683                  D.getDeclSpec().getModulePrivateSpecLoc());
15684     else
15685       NewTD->setModulePrivate();
15686   }
15687 
15688   // C++ [dcl.typedef]p8:
15689   //   If the typedef declaration defines an unnamed class (or
15690   //   enum), the first typedef-name declared by the declaration
15691   //   to be that class type (or enum type) is used to denote the
15692   //   class type (or enum type) for linkage purposes only.
15693   // We need to check whether the type was declared in the declaration.
15694   switch (D.getDeclSpec().getTypeSpecType()) {
15695   case TST_enum:
15696   case TST_struct:
15697   case TST_interface:
15698   case TST_union:
15699   case TST_class: {
15700     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15701     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15702     break;
15703   }
15704 
15705   default:
15706     break;
15707   }
15708 
15709   return NewTD;
15710 }
15711 
15712 /// Check that this is a valid underlying type for an enum declaration.
15713 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15714   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15715   QualType T = TI->getType();
15716 
15717   if (T->isDependentType())
15718     return false;
15719 
15720   // This doesn't use 'isIntegralType' despite the error message mentioning
15721   // integral type because isIntegralType would also allow enum types in C.
15722   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15723     if (BT->isInteger())
15724       return false;
15725 
15726   if (T->isBitIntType())
15727     return false;
15728 
15729   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15730 }
15731 
15732 /// Check whether this is a valid redeclaration of a previous enumeration.
15733 /// \return true if the redeclaration was invalid.
15734 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15735                                   QualType EnumUnderlyingTy, bool IsFixed,
15736                                   const EnumDecl *Prev) {
15737   if (IsScoped != Prev->isScoped()) {
15738     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15739       << Prev->isScoped();
15740     Diag(Prev->getLocation(), diag::note_previous_declaration);
15741     return true;
15742   }
15743 
15744   if (IsFixed && Prev->isFixed()) {
15745     if (!EnumUnderlyingTy->isDependentType() &&
15746         !Prev->getIntegerType()->isDependentType() &&
15747         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15748                                         Prev->getIntegerType())) {
15749       // TODO: Highlight the underlying type of the redeclaration.
15750       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15751         << EnumUnderlyingTy << Prev->getIntegerType();
15752       Diag(Prev->getLocation(), diag::note_previous_declaration)
15753           << Prev->getIntegerTypeRange();
15754       return true;
15755     }
15756   } else if (IsFixed != Prev->isFixed()) {
15757     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15758       << Prev->isFixed();
15759     Diag(Prev->getLocation(), diag::note_previous_declaration);
15760     return true;
15761   }
15762 
15763   return false;
15764 }
15765 
15766 /// Get diagnostic %select index for tag kind for
15767 /// redeclaration diagnostic message.
15768 /// WARNING: Indexes apply to particular diagnostics only!
15769 ///
15770 /// \returns diagnostic %select index.
15771 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15772   switch (Tag) {
15773   case TTK_Struct: return 0;
15774   case TTK_Interface: return 1;
15775   case TTK_Class:  return 2;
15776   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15777   }
15778 }
15779 
15780 /// Determine if tag kind is a class-key compatible with
15781 /// class for redeclaration (class, struct, or __interface).
15782 ///
15783 /// \returns true iff the tag kind is compatible.
15784 static bool isClassCompatTagKind(TagTypeKind Tag)
15785 {
15786   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15787 }
15788 
15789 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15790                                              TagTypeKind TTK) {
15791   if (isa<TypedefDecl>(PrevDecl))
15792     return NTK_Typedef;
15793   else if (isa<TypeAliasDecl>(PrevDecl))
15794     return NTK_TypeAlias;
15795   else if (isa<ClassTemplateDecl>(PrevDecl))
15796     return NTK_Template;
15797   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15798     return NTK_TypeAliasTemplate;
15799   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15800     return NTK_TemplateTemplateArgument;
15801   switch (TTK) {
15802   case TTK_Struct:
15803   case TTK_Interface:
15804   case TTK_Class:
15805     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15806   case TTK_Union:
15807     return NTK_NonUnion;
15808   case TTK_Enum:
15809     return NTK_NonEnum;
15810   }
15811   llvm_unreachable("invalid TTK");
15812 }
15813 
15814 /// Determine whether a tag with a given kind is acceptable
15815 /// as a redeclaration of the given tag declaration.
15816 ///
15817 /// \returns true if the new tag kind is acceptable, false otherwise.
15818 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15819                                         TagTypeKind NewTag, bool isDefinition,
15820                                         SourceLocation NewTagLoc,
15821                                         const IdentifierInfo *Name) {
15822   // C++ [dcl.type.elab]p3:
15823   //   The class-key or enum keyword present in the
15824   //   elaborated-type-specifier shall agree in kind with the
15825   //   declaration to which the name in the elaborated-type-specifier
15826   //   refers. This rule also applies to the form of
15827   //   elaborated-type-specifier that declares a class-name or
15828   //   friend class since it can be construed as referring to the
15829   //   definition of the class. Thus, in any
15830   //   elaborated-type-specifier, the enum keyword shall be used to
15831   //   refer to an enumeration (7.2), the union class-key shall be
15832   //   used to refer to a union (clause 9), and either the class or
15833   //   struct class-key shall be used to refer to a class (clause 9)
15834   //   declared using the class or struct class-key.
15835   TagTypeKind OldTag = Previous->getTagKind();
15836   if (OldTag != NewTag &&
15837       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15838     return false;
15839 
15840   // Tags are compatible, but we might still want to warn on mismatched tags.
15841   // Non-class tags can't be mismatched at this point.
15842   if (!isClassCompatTagKind(NewTag))
15843     return true;
15844 
15845   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15846   // by our warning analysis. We don't want to warn about mismatches with (eg)
15847   // declarations in system headers that are designed to be specialized, but if
15848   // a user asks us to warn, we should warn if their code contains mismatched
15849   // declarations.
15850   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15851     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15852                                       Loc);
15853   };
15854   if (IsIgnoredLoc(NewTagLoc))
15855     return true;
15856 
15857   auto IsIgnored = [&](const TagDecl *Tag) {
15858     return IsIgnoredLoc(Tag->getLocation());
15859   };
15860   while (IsIgnored(Previous)) {
15861     Previous = Previous->getPreviousDecl();
15862     if (!Previous)
15863       return true;
15864     OldTag = Previous->getTagKind();
15865   }
15866 
15867   bool isTemplate = false;
15868   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15869     isTemplate = Record->getDescribedClassTemplate();
15870 
15871   if (inTemplateInstantiation()) {
15872     if (OldTag != NewTag) {
15873       // In a template instantiation, do not offer fix-its for tag mismatches
15874       // since they usually mess up the template instead of fixing the problem.
15875       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15876         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15877         << getRedeclDiagFromTagKind(OldTag);
15878       // FIXME: Note previous location?
15879     }
15880     return true;
15881   }
15882 
15883   if (isDefinition) {
15884     // On definitions, check all previous tags and issue a fix-it for each
15885     // one that doesn't match the current tag.
15886     if (Previous->getDefinition()) {
15887       // Don't suggest fix-its for redefinitions.
15888       return true;
15889     }
15890 
15891     bool previousMismatch = false;
15892     for (const TagDecl *I : Previous->redecls()) {
15893       if (I->getTagKind() != NewTag) {
15894         // Ignore previous declarations for which the warning was disabled.
15895         if (IsIgnored(I))
15896           continue;
15897 
15898         if (!previousMismatch) {
15899           previousMismatch = true;
15900           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15901             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15902             << getRedeclDiagFromTagKind(I->getTagKind());
15903         }
15904         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15905           << getRedeclDiagFromTagKind(NewTag)
15906           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15907                TypeWithKeyword::getTagTypeKindName(NewTag));
15908       }
15909     }
15910     return true;
15911   }
15912 
15913   // Identify the prevailing tag kind: this is the kind of the definition (if
15914   // there is a non-ignored definition), or otherwise the kind of the prior
15915   // (non-ignored) declaration.
15916   const TagDecl *PrevDef = Previous->getDefinition();
15917   if (PrevDef && IsIgnored(PrevDef))
15918     PrevDef = nullptr;
15919   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15920   if (Redecl->getTagKind() != NewTag) {
15921     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15922       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15923       << getRedeclDiagFromTagKind(OldTag);
15924     Diag(Redecl->getLocation(), diag::note_previous_use);
15925 
15926     // If there is a previous definition, suggest a fix-it.
15927     if (PrevDef) {
15928       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15929         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15930         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15931              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15932     }
15933   }
15934 
15935   return true;
15936 }
15937 
15938 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15939 /// from an outer enclosing namespace or file scope inside a friend declaration.
15940 /// This should provide the commented out code in the following snippet:
15941 ///   namespace N {
15942 ///     struct X;
15943 ///     namespace M {
15944 ///       struct Y { friend struct /*N::*/ X; };
15945 ///     }
15946 ///   }
15947 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15948                                          SourceLocation NameLoc) {
15949   // While the decl is in a namespace, do repeated lookup of that name and see
15950   // if we get the same namespace back.  If we do not, continue until
15951   // translation unit scope, at which point we have a fully qualified NNS.
15952   SmallVector<IdentifierInfo *, 4> Namespaces;
15953   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15954   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15955     // This tag should be declared in a namespace, which can only be enclosed by
15956     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15957     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15958     if (!Namespace || Namespace->isAnonymousNamespace())
15959       return FixItHint();
15960     IdentifierInfo *II = Namespace->getIdentifier();
15961     Namespaces.push_back(II);
15962     NamedDecl *Lookup = SemaRef.LookupSingleName(
15963         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15964     if (Lookup == Namespace)
15965       break;
15966   }
15967 
15968   // Once we have all the namespaces, reverse them to go outermost first, and
15969   // build an NNS.
15970   SmallString<64> Insertion;
15971   llvm::raw_svector_ostream OS(Insertion);
15972   if (DC->isTranslationUnit())
15973     OS << "::";
15974   std::reverse(Namespaces.begin(), Namespaces.end());
15975   for (auto *II : Namespaces)
15976     OS << II->getName() << "::";
15977   return FixItHint::CreateInsertion(NameLoc, Insertion);
15978 }
15979 
15980 /// Determine whether a tag originally declared in context \p OldDC can
15981 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15982 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15983 /// using-declaration).
15984 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15985                                          DeclContext *NewDC) {
15986   OldDC = OldDC->getRedeclContext();
15987   NewDC = NewDC->getRedeclContext();
15988 
15989   if (OldDC->Equals(NewDC))
15990     return true;
15991 
15992   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15993   // encloses the other).
15994   if (S.getLangOpts().MSVCCompat &&
15995       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15996     return true;
15997 
15998   return false;
15999 }
16000 
16001 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16002 /// former case, Name will be non-null.  In the later case, Name will be null.
16003 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16004 /// reference/declaration/definition of a tag.
16005 ///
16006 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16007 /// trailing-type-specifier) other than one in an alias-declaration.
16008 ///
16009 /// \param SkipBody If non-null, will be set to indicate if the caller should
16010 /// skip the definition of this tag and treat it as if it were a declaration.
16011 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16012                      SourceLocation KWLoc, CXXScopeSpec &SS,
16013                      IdentifierInfo *Name, SourceLocation NameLoc,
16014                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16015                      SourceLocation ModulePrivateLoc,
16016                      MultiTemplateParamsArg TemplateParameterLists,
16017                      bool &OwnedDecl, bool &IsDependent,
16018                      SourceLocation ScopedEnumKWLoc,
16019                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16020                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16021                      SkipBodyInfo *SkipBody) {
16022   // If this is not a definition, it must have a name.
16023   IdentifierInfo *OrigName = Name;
16024   assert((Name != nullptr || TUK == TUK_Definition) &&
16025          "Nameless record must be a definition!");
16026   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16027 
16028   OwnedDecl = false;
16029   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16030   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16031 
16032   // FIXME: Check member specializations more carefully.
16033   bool isMemberSpecialization = false;
16034   bool Invalid = false;
16035 
16036   // We only need to do this matching if we have template parameters
16037   // or a scope specifier, which also conveniently avoids this work
16038   // for non-C++ cases.
16039   if (TemplateParameterLists.size() > 0 ||
16040       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16041     if (TemplateParameterList *TemplateParams =
16042             MatchTemplateParametersToScopeSpecifier(
16043                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16044                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16045       if (Kind == TTK_Enum) {
16046         Diag(KWLoc, diag::err_enum_template);
16047         return nullptr;
16048       }
16049 
16050       if (TemplateParams->size() > 0) {
16051         // This is a declaration or definition of a class template (which may
16052         // be a member of another template).
16053 
16054         if (Invalid)
16055           return nullptr;
16056 
16057         OwnedDecl = false;
16058         DeclResult Result = CheckClassTemplate(
16059             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16060             AS, ModulePrivateLoc,
16061             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16062             TemplateParameterLists.data(), SkipBody);
16063         return Result.get();
16064       } else {
16065         // The "template<>" header is extraneous.
16066         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16067           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16068         isMemberSpecialization = true;
16069       }
16070     }
16071 
16072     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16073         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16074       return nullptr;
16075   }
16076 
16077   // Figure out the underlying type if this a enum declaration. We need to do
16078   // this early, because it's needed to detect if this is an incompatible
16079   // redeclaration.
16080   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16081   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16082 
16083   if (Kind == TTK_Enum) {
16084     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16085       // No underlying type explicitly specified, or we failed to parse the
16086       // type, default to int.
16087       EnumUnderlying = Context.IntTy.getTypePtr();
16088     } else if (UnderlyingType.get()) {
16089       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16090       // integral type; any cv-qualification is ignored.
16091       TypeSourceInfo *TI = nullptr;
16092       GetTypeFromParser(UnderlyingType.get(), &TI);
16093       EnumUnderlying = TI;
16094 
16095       if (CheckEnumUnderlyingType(TI))
16096         // Recover by falling back to int.
16097         EnumUnderlying = Context.IntTy.getTypePtr();
16098 
16099       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16100                                           UPPC_FixedUnderlyingType))
16101         EnumUnderlying = Context.IntTy.getTypePtr();
16102 
16103     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16104       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16105       // of 'int'. However, if this is an unfixed forward declaration, don't set
16106       // the underlying type unless the user enables -fms-compatibility. This
16107       // makes unfixed forward declared enums incomplete and is more conforming.
16108       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16109         EnumUnderlying = Context.IntTy.getTypePtr();
16110     }
16111   }
16112 
16113   DeclContext *SearchDC = CurContext;
16114   DeclContext *DC = CurContext;
16115   bool isStdBadAlloc = false;
16116   bool isStdAlignValT = false;
16117 
16118   RedeclarationKind Redecl = forRedeclarationInCurContext();
16119   if (TUK == TUK_Friend || TUK == TUK_Reference)
16120     Redecl = NotForRedeclaration;
16121 
16122   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16123   /// implemented asks for structural equivalence checking, the returned decl
16124   /// here is passed back to the parser, allowing the tag body to be parsed.
16125   auto createTagFromNewDecl = [&]() -> TagDecl * {
16126     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16127     // If there is an identifier, use the location of the identifier as the
16128     // location of the decl, otherwise use the location of the struct/union
16129     // keyword.
16130     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16131     TagDecl *New = nullptr;
16132 
16133     if (Kind == TTK_Enum) {
16134       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16135                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16136       // If this is an undefined enum, bail.
16137       if (TUK != TUK_Definition && !Invalid)
16138         return nullptr;
16139       if (EnumUnderlying) {
16140         EnumDecl *ED = cast<EnumDecl>(New);
16141         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16142           ED->setIntegerTypeSourceInfo(TI);
16143         else
16144           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16145         ED->setPromotionType(ED->getIntegerType());
16146       }
16147     } else { // struct/union
16148       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16149                                nullptr);
16150     }
16151 
16152     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16153       // Add alignment attributes if necessary; these attributes are checked
16154       // when the ASTContext lays out the structure.
16155       //
16156       // It is important for implementing the correct semantics that this
16157       // happen here (in ActOnTag). The #pragma pack stack is
16158       // maintained as a result of parser callbacks which can occur at
16159       // many points during the parsing of a struct declaration (because
16160       // the #pragma tokens are effectively skipped over during the
16161       // parsing of the struct).
16162       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16163         AddAlignmentAttributesForRecord(RD);
16164         AddMsStructLayoutForRecord(RD);
16165       }
16166     }
16167     New->setLexicalDeclContext(CurContext);
16168     return New;
16169   };
16170 
16171   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16172   if (Name && SS.isNotEmpty()) {
16173     // We have a nested-name tag ('struct foo::bar').
16174 
16175     // Check for invalid 'foo::'.
16176     if (SS.isInvalid()) {
16177       Name = nullptr;
16178       goto CreateNewDecl;
16179     }
16180 
16181     // If this is a friend or a reference to a class in a dependent
16182     // context, don't try to make a decl for it.
16183     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16184       DC = computeDeclContext(SS, false);
16185       if (!DC) {
16186         IsDependent = true;
16187         return nullptr;
16188       }
16189     } else {
16190       DC = computeDeclContext(SS, true);
16191       if (!DC) {
16192         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16193           << SS.getRange();
16194         return nullptr;
16195       }
16196     }
16197 
16198     if (RequireCompleteDeclContext(SS, DC))
16199       return nullptr;
16200 
16201     SearchDC = DC;
16202     // Look-up name inside 'foo::'.
16203     LookupQualifiedName(Previous, DC);
16204 
16205     if (Previous.isAmbiguous())
16206       return nullptr;
16207 
16208     if (Previous.empty()) {
16209       // Name lookup did not find anything. However, if the
16210       // nested-name-specifier refers to the current instantiation,
16211       // and that current instantiation has any dependent base
16212       // classes, we might find something at instantiation time: treat
16213       // this as a dependent elaborated-type-specifier.
16214       // But this only makes any sense for reference-like lookups.
16215       if (Previous.wasNotFoundInCurrentInstantiation() &&
16216           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16217         IsDependent = true;
16218         return nullptr;
16219       }
16220 
16221       // A tag 'foo::bar' must already exist.
16222       Diag(NameLoc, diag::err_not_tag_in_scope)
16223         << Kind << Name << DC << SS.getRange();
16224       Name = nullptr;
16225       Invalid = true;
16226       goto CreateNewDecl;
16227     }
16228   } else if (Name) {
16229     // C++14 [class.mem]p14:
16230     //   If T is the name of a class, then each of the following shall have a
16231     //   name different from T:
16232     //    -- every member of class T that is itself a type
16233     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16234         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16235       return nullptr;
16236 
16237     // If this is a named struct, check to see if there was a previous forward
16238     // declaration or definition.
16239     // FIXME: We're looking into outer scopes here, even when we
16240     // shouldn't be. Doing so can result in ambiguities that we
16241     // shouldn't be diagnosing.
16242     LookupName(Previous, S);
16243 
16244     // When declaring or defining a tag, ignore ambiguities introduced
16245     // by types using'ed into this scope.
16246     if (Previous.isAmbiguous() &&
16247         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16248       LookupResult::Filter F = Previous.makeFilter();
16249       while (F.hasNext()) {
16250         NamedDecl *ND = F.next();
16251         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16252                 SearchDC->getRedeclContext()))
16253           F.erase();
16254       }
16255       F.done();
16256     }
16257 
16258     // C++11 [namespace.memdef]p3:
16259     //   If the name in a friend declaration is neither qualified nor
16260     //   a template-id and the declaration is a function or an
16261     //   elaborated-type-specifier, the lookup to determine whether
16262     //   the entity has been previously declared shall not consider
16263     //   any scopes outside the innermost enclosing namespace.
16264     //
16265     // MSVC doesn't implement the above rule for types, so a friend tag
16266     // declaration may be a redeclaration of a type declared in an enclosing
16267     // scope.  They do implement this rule for friend functions.
16268     //
16269     // Does it matter that this should be by scope instead of by
16270     // semantic context?
16271     if (!Previous.empty() && TUK == TUK_Friend) {
16272       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16273       LookupResult::Filter F = Previous.makeFilter();
16274       bool FriendSawTagOutsideEnclosingNamespace = false;
16275       while (F.hasNext()) {
16276         NamedDecl *ND = F.next();
16277         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16278         if (DC->isFileContext() &&
16279             !EnclosingNS->Encloses(ND->getDeclContext())) {
16280           if (getLangOpts().MSVCCompat)
16281             FriendSawTagOutsideEnclosingNamespace = true;
16282           else
16283             F.erase();
16284         }
16285       }
16286       F.done();
16287 
16288       // Diagnose this MSVC extension in the easy case where lookup would have
16289       // unambiguously found something outside the enclosing namespace.
16290       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16291         NamedDecl *ND = Previous.getFoundDecl();
16292         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16293             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16294       }
16295     }
16296 
16297     // Note:  there used to be some attempt at recovery here.
16298     if (Previous.isAmbiguous())
16299       return nullptr;
16300 
16301     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16302       // FIXME: This makes sure that we ignore the contexts associated
16303       // with C structs, unions, and enums when looking for a matching
16304       // tag declaration or definition. See the similar lookup tweak
16305       // in Sema::LookupName; is there a better way to deal with this?
16306       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16307         SearchDC = SearchDC->getParent();
16308     } else if (getLangOpts().CPlusPlus) {
16309       // Inside ObjCContainer want to keep it as a lexical decl context but go
16310       // past it (most often to TranslationUnit) to find the semantic decl
16311       // context.
16312       while (isa<ObjCContainerDecl>(SearchDC))
16313         SearchDC = SearchDC->getParent();
16314     }
16315   } else if (getLangOpts().CPlusPlus) {
16316     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16317     // TagDecl the same way as we skip it for named TagDecl.
16318     while (isa<ObjCContainerDecl>(SearchDC))
16319       SearchDC = SearchDC->getParent();
16320   }
16321 
16322   if (Previous.isSingleResult() &&
16323       Previous.getFoundDecl()->isTemplateParameter()) {
16324     // Maybe we will complain about the shadowed template parameter.
16325     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16326     // Just pretend that we didn't see the previous declaration.
16327     Previous.clear();
16328   }
16329 
16330   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16331       DC->Equals(getStdNamespace())) {
16332     if (Name->isStr("bad_alloc")) {
16333       // This is a declaration of or a reference to "std::bad_alloc".
16334       isStdBadAlloc = true;
16335 
16336       // If std::bad_alloc has been implicitly declared (but made invisible to
16337       // name lookup), fill in this implicit declaration as the previous
16338       // declaration, so that the declarations get chained appropriately.
16339       if (Previous.empty() && StdBadAlloc)
16340         Previous.addDecl(getStdBadAlloc());
16341     } else if (Name->isStr("align_val_t")) {
16342       isStdAlignValT = true;
16343       if (Previous.empty() && StdAlignValT)
16344         Previous.addDecl(getStdAlignValT());
16345     }
16346   }
16347 
16348   // If we didn't find a previous declaration, and this is a reference
16349   // (or friend reference), move to the correct scope.  In C++, we
16350   // also need to do a redeclaration lookup there, just in case
16351   // there's a shadow friend decl.
16352   if (Name && Previous.empty() &&
16353       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16354     if (Invalid) goto CreateNewDecl;
16355     assert(SS.isEmpty());
16356 
16357     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16358       // C++ [basic.scope.pdecl]p5:
16359       //   -- for an elaborated-type-specifier of the form
16360       //
16361       //          class-key identifier
16362       //
16363       //      if the elaborated-type-specifier is used in the
16364       //      decl-specifier-seq or parameter-declaration-clause of a
16365       //      function defined in namespace scope, the identifier is
16366       //      declared as a class-name in the namespace that contains
16367       //      the declaration; otherwise, except as a friend
16368       //      declaration, the identifier is declared in the smallest
16369       //      non-class, non-function-prototype scope that contains the
16370       //      declaration.
16371       //
16372       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16373       // C structs and unions.
16374       //
16375       // It is an error in C++ to declare (rather than define) an enum
16376       // type, including via an elaborated type specifier.  We'll
16377       // diagnose that later; for now, declare the enum in the same
16378       // scope as we would have picked for any other tag type.
16379       //
16380       // GNU C also supports this behavior as part of its incomplete
16381       // enum types extension, while GNU C++ does not.
16382       //
16383       // Find the context where we'll be declaring the tag.
16384       // FIXME: We would like to maintain the current DeclContext as the
16385       // lexical context,
16386       SearchDC = getTagInjectionContext(SearchDC);
16387 
16388       // Find the scope where we'll be declaring the tag.
16389       S = getTagInjectionScope(S, getLangOpts());
16390     } else {
16391       assert(TUK == TUK_Friend);
16392       // C++ [namespace.memdef]p3:
16393       //   If a friend declaration in a non-local class first declares a
16394       //   class or function, the friend class or function is a member of
16395       //   the innermost enclosing namespace.
16396       SearchDC = SearchDC->getEnclosingNamespaceContext();
16397     }
16398 
16399     // In C++, we need to do a redeclaration lookup to properly
16400     // diagnose some problems.
16401     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16402     // hidden declaration so that we don't get ambiguity errors when using a
16403     // type declared by an elaborated-type-specifier.  In C that is not correct
16404     // and we should instead merge compatible types found by lookup.
16405     if (getLangOpts().CPlusPlus) {
16406       // FIXME: This can perform qualified lookups into function contexts,
16407       // which are meaningless.
16408       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16409       LookupQualifiedName(Previous, SearchDC);
16410     } else {
16411       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16412       LookupName(Previous, S);
16413     }
16414   }
16415 
16416   // If we have a known previous declaration to use, then use it.
16417   if (Previous.empty() && SkipBody && SkipBody->Previous)
16418     Previous.addDecl(SkipBody->Previous);
16419 
16420   if (!Previous.empty()) {
16421     NamedDecl *PrevDecl = Previous.getFoundDecl();
16422     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16423 
16424     // It's okay to have a tag decl in the same scope as a typedef
16425     // which hides a tag decl in the same scope.  Finding this
16426     // with a redeclaration lookup can only actually happen in C++.
16427     //
16428     // This is also okay for elaborated-type-specifiers, which is
16429     // technically forbidden by the current standard but which is
16430     // okay according to the likely resolution of an open issue;
16431     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16432     if (getLangOpts().CPlusPlus) {
16433       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16434         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16435           TagDecl *Tag = TT->getDecl();
16436           if (Tag->getDeclName() == Name &&
16437               Tag->getDeclContext()->getRedeclContext()
16438                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16439             PrevDecl = Tag;
16440             Previous.clear();
16441             Previous.addDecl(Tag);
16442             Previous.resolveKind();
16443           }
16444         }
16445       }
16446     }
16447 
16448     // If this is a redeclaration of a using shadow declaration, it must
16449     // declare a tag in the same context. In MSVC mode, we allow a
16450     // redefinition if either context is within the other.
16451     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16452       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16453       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16454           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16455           !(OldTag && isAcceptableTagRedeclContext(
16456                           *this, OldTag->getDeclContext(), SearchDC))) {
16457         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16458         Diag(Shadow->getTargetDecl()->getLocation(),
16459              diag::note_using_decl_target);
16460         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16461             << 0;
16462         // Recover by ignoring the old declaration.
16463         Previous.clear();
16464         goto CreateNewDecl;
16465       }
16466     }
16467 
16468     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16469       // If this is a use of a previous tag, or if the tag is already declared
16470       // in the same scope (so that the definition/declaration completes or
16471       // rementions the tag), reuse the decl.
16472       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16473           isDeclInScope(DirectPrevDecl, SearchDC, S,
16474                         SS.isNotEmpty() || isMemberSpecialization)) {
16475         // Make sure that this wasn't declared as an enum and now used as a
16476         // struct or something similar.
16477         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16478                                           TUK == TUK_Definition, KWLoc,
16479                                           Name)) {
16480           bool SafeToContinue
16481             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16482                Kind != TTK_Enum);
16483           if (SafeToContinue)
16484             Diag(KWLoc, diag::err_use_with_wrong_tag)
16485               << Name
16486               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16487                                               PrevTagDecl->getKindName());
16488           else
16489             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16490           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16491 
16492           if (SafeToContinue)
16493             Kind = PrevTagDecl->getTagKind();
16494           else {
16495             // Recover by making this an anonymous redefinition.
16496             Name = nullptr;
16497             Previous.clear();
16498             Invalid = true;
16499           }
16500         }
16501 
16502         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16503           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16504           if (TUK == TUK_Reference || TUK == TUK_Friend)
16505             return PrevTagDecl;
16506 
16507           QualType EnumUnderlyingTy;
16508           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16509             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16510           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16511             EnumUnderlyingTy = QualType(T, 0);
16512 
16513           // All conflicts with previous declarations are recovered by
16514           // returning the previous declaration, unless this is a definition,
16515           // in which case we want the caller to bail out.
16516           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16517                                      ScopedEnum, EnumUnderlyingTy,
16518                                      IsFixed, PrevEnum))
16519             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16520         }
16521 
16522         // C++11 [class.mem]p1:
16523         //   A member shall not be declared twice in the member-specification,
16524         //   except that a nested class or member class template can be declared
16525         //   and then later defined.
16526         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16527             S->isDeclScope(PrevDecl)) {
16528           Diag(NameLoc, diag::ext_member_redeclared);
16529           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16530         }
16531 
16532         if (!Invalid) {
16533           // If this is a use, just return the declaration we found, unless
16534           // we have attributes.
16535           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16536             if (!Attrs.empty()) {
16537               // FIXME: Diagnose these attributes. For now, we create a new
16538               // declaration to hold them.
16539             } else if (TUK == TUK_Reference &&
16540                        (PrevTagDecl->getFriendObjectKind() ==
16541                             Decl::FOK_Undeclared ||
16542                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16543                        SS.isEmpty()) {
16544               // This declaration is a reference to an existing entity, but
16545               // has different visibility from that entity: it either makes
16546               // a friend visible or it makes a type visible in a new module.
16547               // In either case, create a new declaration. We only do this if
16548               // the declaration would have meant the same thing if no prior
16549               // declaration were found, that is, if it was found in the same
16550               // scope where we would have injected a declaration.
16551               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16552                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16553                 return PrevTagDecl;
16554               // This is in the injected scope, create a new declaration in
16555               // that scope.
16556               S = getTagInjectionScope(S, getLangOpts());
16557             } else {
16558               return PrevTagDecl;
16559             }
16560           }
16561 
16562           // Diagnose attempts to redefine a tag.
16563           if (TUK == TUK_Definition) {
16564             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16565               // If we're defining a specialization and the previous definition
16566               // is from an implicit instantiation, don't emit an error
16567               // here; we'll catch this in the general case below.
16568               bool IsExplicitSpecializationAfterInstantiation = false;
16569               if (isMemberSpecialization) {
16570                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16571                   IsExplicitSpecializationAfterInstantiation =
16572                     RD->getTemplateSpecializationKind() !=
16573                     TSK_ExplicitSpecialization;
16574                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16575                   IsExplicitSpecializationAfterInstantiation =
16576                     ED->getTemplateSpecializationKind() !=
16577                     TSK_ExplicitSpecialization;
16578               }
16579 
16580               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16581               // not keep more that one definition around (merge them). However,
16582               // ensure the decl passes the structural compatibility check in
16583               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16584               NamedDecl *Hidden = nullptr;
16585               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16586                 // There is a definition of this tag, but it is not visible. We
16587                 // explicitly make use of C++'s one definition rule here, and
16588                 // assume that this definition is identical to the hidden one
16589                 // we already have. Make the existing definition visible and
16590                 // use it in place of this one.
16591                 if (!getLangOpts().CPlusPlus) {
16592                   // Postpone making the old definition visible until after we
16593                   // complete parsing the new one and do the structural
16594                   // comparison.
16595                   SkipBody->CheckSameAsPrevious = true;
16596                   SkipBody->New = createTagFromNewDecl();
16597                   SkipBody->Previous = Def;
16598                   return Def;
16599                 } else {
16600                   SkipBody->ShouldSkip = true;
16601                   SkipBody->Previous = Def;
16602                   makeMergedDefinitionVisible(Hidden);
16603                   // Carry on and handle it like a normal definition. We'll
16604                   // skip starting the definitiion later.
16605                 }
16606               } else if (!IsExplicitSpecializationAfterInstantiation) {
16607                 // A redeclaration in function prototype scope in C isn't
16608                 // visible elsewhere, so merely issue a warning.
16609                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16610                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16611                 else
16612                   Diag(NameLoc, diag::err_redefinition) << Name;
16613                 notePreviousDefinition(Def,
16614                                        NameLoc.isValid() ? NameLoc : KWLoc);
16615                 // If this is a redefinition, recover by making this
16616                 // struct be anonymous, which will make any later
16617                 // references get the previous definition.
16618                 Name = nullptr;
16619                 Previous.clear();
16620                 Invalid = true;
16621               }
16622             } else {
16623               // If the type is currently being defined, complain
16624               // about a nested redefinition.
16625               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16626               if (TD->isBeingDefined()) {
16627                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16628                 Diag(PrevTagDecl->getLocation(),
16629                      diag::note_previous_definition);
16630                 Name = nullptr;
16631                 Previous.clear();
16632                 Invalid = true;
16633               }
16634             }
16635 
16636             // Okay, this is definition of a previously declared or referenced
16637             // tag. We're going to create a new Decl for it.
16638           }
16639 
16640           // Okay, we're going to make a redeclaration.  If this is some kind
16641           // of reference, make sure we build the redeclaration in the same DC
16642           // as the original, and ignore the current access specifier.
16643           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16644             SearchDC = PrevTagDecl->getDeclContext();
16645             AS = AS_none;
16646           }
16647         }
16648         // If we get here we have (another) forward declaration or we
16649         // have a definition.  Just create a new decl.
16650 
16651       } else {
16652         // If we get here, this is a definition of a new tag type in a nested
16653         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16654         // new decl/type.  We set PrevDecl to NULL so that the entities
16655         // have distinct types.
16656         Previous.clear();
16657       }
16658       // If we get here, we're going to create a new Decl. If PrevDecl
16659       // is non-NULL, it's a definition of the tag declared by
16660       // PrevDecl. If it's NULL, we have a new definition.
16661 
16662     // Otherwise, PrevDecl is not a tag, but was found with tag
16663     // lookup.  This is only actually possible in C++, where a few
16664     // things like templates still live in the tag namespace.
16665     } else {
16666       // Use a better diagnostic if an elaborated-type-specifier
16667       // found the wrong kind of type on the first
16668       // (non-redeclaration) lookup.
16669       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16670           !Previous.isForRedeclaration()) {
16671         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16672         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16673                                                        << Kind;
16674         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16675         Invalid = true;
16676 
16677       // Otherwise, only diagnose if the declaration is in scope.
16678       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16679                                 SS.isNotEmpty() || isMemberSpecialization)) {
16680         // do nothing
16681 
16682       // Diagnose implicit declarations introduced by elaborated types.
16683       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16684         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16685         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16686         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16687         Invalid = true;
16688 
16689       // Otherwise it's a declaration.  Call out a particularly common
16690       // case here.
16691       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16692         unsigned Kind = 0;
16693         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16694         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16695           << Name << Kind << TND->getUnderlyingType();
16696         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16697         Invalid = true;
16698 
16699       // Otherwise, diagnose.
16700       } else {
16701         // The tag name clashes with something else in the target scope,
16702         // issue an error and recover by making this tag be anonymous.
16703         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16704         notePreviousDefinition(PrevDecl, NameLoc);
16705         Name = nullptr;
16706         Invalid = true;
16707       }
16708 
16709       // The existing declaration isn't relevant to us; we're in a
16710       // new scope, so clear out the previous declaration.
16711       Previous.clear();
16712     }
16713   }
16714 
16715 CreateNewDecl:
16716 
16717   TagDecl *PrevDecl = nullptr;
16718   if (Previous.isSingleResult())
16719     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16720 
16721   // If there is an identifier, use the location of the identifier as the
16722   // location of the decl, otherwise use the location of the struct/union
16723   // keyword.
16724   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16725 
16726   // Otherwise, create a new declaration. If there is a previous
16727   // declaration of the same entity, the two will be linked via
16728   // PrevDecl.
16729   TagDecl *New;
16730 
16731   if (Kind == TTK_Enum) {
16732     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16733     // enum X { A, B, C } D;    D should chain to X.
16734     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16735                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16736                            ScopedEnumUsesClassTag, IsFixed);
16737 
16738     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16739       StdAlignValT = cast<EnumDecl>(New);
16740 
16741     // If this is an undefined enum, warn.
16742     if (TUK != TUK_Definition && !Invalid) {
16743       TagDecl *Def;
16744       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16745         // C++0x: 7.2p2: opaque-enum-declaration.
16746         // Conflicts are diagnosed above. Do nothing.
16747       }
16748       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16749         Diag(Loc, diag::ext_forward_ref_enum_def)
16750           << New;
16751         Diag(Def->getLocation(), diag::note_previous_definition);
16752       } else {
16753         unsigned DiagID = diag::ext_forward_ref_enum;
16754         if (getLangOpts().MSVCCompat)
16755           DiagID = diag::ext_ms_forward_ref_enum;
16756         else if (getLangOpts().CPlusPlus)
16757           DiagID = diag::err_forward_ref_enum;
16758         Diag(Loc, DiagID);
16759       }
16760     }
16761 
16762     if (EnumUnderlying) {
16763       EnumDecl *ED = cast<EnumDecl>(New);
16764       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16765         ED->setIntegerTypeSourceInfo(TI);
16766       else
16767         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16768       ED->setPromotionType(ED->getIntegerType());
16769       assert(ED->isComplete() && "enum with type should be complete");
16770     }
16771   } else {
16772     // struct/union/class
16773 
16774     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16775     // struct X { int A; } D;    D should chain to X.
16776     if (getLangOpts().CPlusPlus) {
16777       // FIXME: Look for a way to use RecordDecl for simple structs.
16778       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16779                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16780 
16781       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16782         StdBadAlloc = cast<CXXRecordDecl>(New);
16783     } else
16784       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16785                                cast_or_null<RecordDecl>(PrevDecl));
16786   }
16787 
16788   // C++11 [dcl.type]p3:
16789   //   A type-specifier-seq shall not define a class or enumeration [...].
16790   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16791       TUK == TUK_Definition) {
16792     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16793       << Context.getTagDeclType(New);
16794     Invalid = true;
16795   }
16796 
16797   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16798       DC->getDeclKind() == Decl::Enum) {
16799     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16800       << Context.getTagDeclType(New);
16801     Invalid = true;
16802   }
16803 
16804   // Maybe add qualifier info.
16805   if (SS.isNotEmpty()) {
16806     if (SS.isSet()) {
16807       // If this is either a declaration or a definition, check the
16808       // nested-name-specifier against the current context.
16809       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16810           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16811                                        isMemberSpecialization))
16812         Invalid = true;
16813 
16814       New->setQualifierInfo(SS.getWithLocInContext(Context));
16815       if (TemplateParameterLists.size() > 0) {
16816         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16817       }
16818     }
16819     else
16820       Invalid = true;
16821   }
16822 
16823   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16824     // Add alignment attributes if necessary; these attributes are checked when
16825     // the ASTContext lays out the structure.
16826     //
16827     // It is important for implementing the correct semantics that this
16828     // happen here (in ActOnTag). The #pragma pack stack is
16829     // maintained as a result of parser callbacks which can occur at
16830     // many points during the parsing of a struct declaration (because
16831     // the #pragma tokens are effectively skipped over during the
16832     // parsing of the struct).
16833     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16834       AddAlignmentAttributesForRecord(RD);
16835       AddMsStructLayoutForRecord(RD);
16836     }
16837   }
16838 
16839   if (ModulePrivateLoc.isValid()) {
16840     if (isMemberSpecialization)
16841       Diag(New->getLocation(), diag::err_module_private_specialization)
16842         << 2
16843         << FixItHint::CreateRemoval(ModulePrivateLoc);
16844     // __module_private__ does not apply to local classes. However, we only
16845     // diagnose this as an error when the declaration specifiers are
16846     // freestanding. Here, we just ignore the __module_private__.
16847     else if (!SearchDC->isFunctionOrMethod())
16848       New->setModulePrivate();
16849   }
16850 
16851   // If this is a specialization of a member class (of a class template),
16852   // check the specialization.
16853   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16854     Invalid = true;
16855 
16856   // If we're declaring or defining a tag in function prototype scope in C,
16857   // note that this type can only be used within the function and add it to
16858   // the list of decls to inject into the function definition scope.
16859   if ((Name || Kind == TTK_Enum) &&
16860       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16861     if (getLangOpts().CPlusPlus) {
16862       // C++ [dcl.fct]p6:
16863       //   Types shall not be defined in return or parameter types.
16864       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16865         Diag(Loc, diag::err_type_defined_in_param_type)
16866             << Name;
16867         Invalid = true;
16868       }
16869     } else if (!PrevDecl) {
16870       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16871     }
16872   }
16873 
16874   if (Invalid)
16875     New->setInvalidDecl();
16876 
16877   // Set the lexical context. If the tag has a C++ scope specifier, the
16878   // lexical context will be different from the semantic context.
16879   New->setLexicalDeclContext(CurContext);
16880 
16881   // Mark this as a friend decl if applicable.
16882   // In Microsoft mode, a friend declaration also acts as a forward
16883   // declaration so we always pass true to setObjectOfFriendDecl to make
16884   // the tag name visible.
16885   if (TUK == TUK_Friend)
16886     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16887 
16888   // Set the access specifier.
16889   if (!Invalid && SearchDC->isRecord())
16890     SetMemberAccessSpecifier(New, PrevDecl, AS);
16891 
16892   if (PrevDecl)
16893     CheckRedeclarationInModule(New, PrevDecl);
16894 
16895   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16896     New->startDefinition();
16897 
16898   ProcessDeclAttributeList(S, New, Attrs);
16899   AddPragmaAttributes(S, New);
16900 
16901   // If this has an identifier, add it to the scope stack.
16902   if (TUK == TUK_Friend) {
16903     // We might be replacing an existing declaration in the lookup tables;
16904     // if so, borrow its access specifier.
16905     if (PrevDecl)
16906       New->setAccess(PrevDecl->getAccess());
16907 
16908     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16909     DC->makeDeclVisibleInContext(New);
16910     if (Name) // can be null along some error paths
16911       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16912         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16913   } else if (Name) {
16914     S = getNonFieldDeclScope(S);
16915     PushOnScopeChains(New, S, true);
16916   } else {
16917     CurContext->addDecl(New);
16918   }
16919 
16920   // If this is the C FILE type, notify the AST context.
16921   if (IdentifierInfo *II = New->getIdentifier())
16922     if (!New->isInvalidDecl() &&
16923         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16924         II->isStr("FILE"))
16925       Context.setFILEDecl(New);
16926 
16927   if (PrevDecl)
16928     mergeDeclAttributes(New, PrevDecl);
16929 
16930   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16931     inferGslOwnerPointerAttribute(CXXRD);
16932 
16933   // If there's a #pragma GCC visibility in scope, set the visibility of this
16934   // record.
16935   AddPushedVisibilityAttribute(New);
16936 
16937   if (isMemberSpecialization && !New->isInvalidDecl())
16938     CompleteMemberSpecialization(New, Previous);
16939 
16940   OwnedDecl = true;
16941   // In C++, don't return an invalid declaration. We can't recover well from
16942   // the cases where we make the type anonymous.
16943   if (Invalid && getLangOpts().CPlusPlus) {
16944     if (New->isBeingDefined())
16945       if (auto RD = dyn_cast<RecordDecl>(New))
16946         RD->completeDefinition();
16947     return nullptr;
16948   } else if (SkipBody && SkipBody->ShouldSkip) {
16949     return SkipBody->Previous;
16950   } else {
16951     return New;
16952   }
16953 }
16954 
16955 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16956   AdjustDeclIfTemplate(TagD);
16957   TagDecl *Tag = cast<TagDecl>(TagD);
16958 
16959   // Enter the tag context.
16960   PushDeclContext(S, Tag);
16961 
16962   ActOnDocumentableDecl(TagD);
16963 
16964   // If there's a #pragma GCC visibility in scope, set the visibility of this
16965   // record.
16966   AddPushedVisibilityAttribute(Tag);
16967 }
16968 
16969 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16970   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16971     return false;
16972 
16973   // Make the previous decl visible.
16974   makeMergedDefinitionVisible(SkipBody.Previous);
16975   return true;
16976 }
16977 
16978 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
16979   assert(IDecl->getLexicalParent() == CurContext &&
16980       "The next DeclContext should be lexically contained in the current one.");
16981   CurContext = IDecl;
16982 }
16983 
16984 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16985                                            SourceLocation FinalLoc,
16986                                            bool IsFinalSpelledSealed,
16987                                            bool IsAbstract,
16988                                            SourceLocation LBraceLoc) {
16989   AdjustDeclIfTemplate(TagD);
16990   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16991 
16992   FieldCollector->StartClass();
16993 
16994   if (!Record->getIdentifier())
16995     return;
16996 
16997   if (IsAbstract)
16998     Record->markAbstract();
16999 
17000   if (FinalLoc.isValid()) {
17001     Record->addAttr(FinalAttr::Create(
17002         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17003         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17004   }
17005   // C++ [class]p2:
17006   //   [...] The class-name is also inserted into the scope of the
17007   //   class itself; this is known as the injected-class-name. For
17008   //   purposes of access checking, the injected-class-name is treated
17009   //   as if it were a public member name.
17010   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17011       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17012       Record->getLocation(), Record->getIdentifier(),
17013       /*PrevDecl=*/nullptr,
17014       /*DelayTypeCreation=*/true);
17015   Context.getTypeDeclType(InjectedClassName, Record);
17016   InjectedClassName->setImplicit();
17017   InjectedClassName->setAccess(AS_public);
17018   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17019       InjectedClassName->setDescribedClassTemplate(Template);
17020   PushOnScopeChains(InjectedClassName, S);
17021   assert(InjectedClassName->isInjectedClassName() &&
17022          "Broken injected-class-name");
17023 }
17024 
17025 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17026                                     SourceRange BraceRange) {
17027   AdjustDeclIfTemplate(TagD);
17028   TagDecl *Tag = cast<TagDecl>(TagD);
17029   Tag->setBraceRange(BraceRange);
17030 
17031   // Make sure we "complete" the definition even it is invalid.
17032   if (Tag->isBeingDefined()) {
17033     assert(Tag->isInvalidDecl() && "We should already have completed it");
17034     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17035       RD->completeDefinition();
17036   }
17037 
17038   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17039     FieldCollector->FinishClass();
17040     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17041       auto *Def = RD->getDefinition();
17042       assert(Def && "The record is expected to have a completed definition");
17043       unsigned NumInitMethods = 0;
17044       for (auto *Method : Def->methods()) {
17045         if (!Method->getIdentifier())
17046             continue;
17047         if (Method->getName() == "__init")
17048           NumInitMethods++;
17049       }
17050       if (NumInitMethods > 1 || !Def->hasInitMethod())
17051         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17052     }
17053   }
17054 
17055   // Exit this scope of this tag's definition.
17056   PopDeclContext();
17057 
17058   if (getCurLexicalContext()->isObjCContainer() &&
17059       Tag->getDeclContext()->isFileContext())
17060     Tag->setTopLevelDeclInObjCContainer();
17061 
17062   // Notify the consumer that we've defined a tag.
17063   if (!Tag->isInvalidDecl())
17064     Consumer.HandleTagDeclDefinition(Tag);
17065 
17066   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17067   // from XLs and instead matches the XL #pragma pack(1) behavior.
17068   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17069       AlignPackStack.hasValue()) {
17070     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17071     // Only diagnose #pragma align(packed).
17072     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17073       return;
17074     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17075     if (!RD)
17076       return;
17077     // Only warn if there is at least 1 bitfield member.
17078     if (llvm::any_of(RD->fields(),
17079                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17080       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17081   }
17082 }
17083 
17084 void Sema::ActOnObjCContainerFinishDefinition() {
17085   // Exit this scope of this interface definition.
17086   PopDeclContext();
17087 }
17088 
17089 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17090   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17091   OriginalLexicalContext = ObjCCtx;
17092   ActOnObjCContainerFinishDefinition();
17093 }
17094 
17095 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17096   ActOnObjCContainerStartDefinition(ObjCCtx);
17097   OriginalLexicalContext = nullptr;
17098 }
17099 
17100 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17101   AdjustDeclIfTemplate(TagD);
17102   TagDecl *Tag = cast<TagDecl>(TagD);
17103   Tag->setInvalidDecl();
17104 
17105   // Make sure we "complete" the definition even it is invalid.
17106   if (Tag->isBeingDefined()) {
17107     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17108       RD->completeDefinition();
17109   }
17110 
17111   // We're undoing ActOnTagStartDefinition here, not
17112   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17113   // the FieldCollector.
17114 
17115   PopDeclContext();
17116 }
17117 
17118 // Note that FieldName may be null for anonymous bitfields.
17119 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17120                                 IdentifierInfo *FieldName, QualType FieldTy,
17121                                 bool IsMsStruct, Expr *BitWidth) {
17122   assert(BitWidth);
17123   if (BitWidth->containsErrors())
17124     return ExprError();
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   // Zero-width bitfield is ok for anonymous field.
17154   if (Value == 0 && FieldName)
17155     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17156 
17157   if (Value.isSigned() && Value.isNegative()) {
17158     if (FieldName)
17159       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17160                << FieldName << toString(Value, 10);
17161     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17162       << toString(Value, 10);
17163   }
17164 
17165   // The size of the bit-field must not exceed our maximum permitted object
17166   // size.
17167   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17168     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17169            << !FieldName << FieldName << toString(Value, 10);
17170   }
17171 
17172   if (!FieldTy->isDependentType()) {
17173     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17174     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17175     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17176 
17177     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17178     // ABI.
17179     bool CStdConstraintViolation =
17180         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17181     bool MSBitfieldViolation =
17182         Value.ugt(TypeStorageSize) &&
17183         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17184     if (CStdConstraintViolation || MSBitfieldViolation) {
17185       unsigned DiagWidth =
17186           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17187       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17188              << (bool)FieldName << FieldName << toString(Value, 10)
17189              << !CStdConstraintViolation << DiagWidth;
17190     }
17191 
17192     // Warn on types where the user might conceivably expect to get all
17193     // specified bits as value bits: that's all integral types other than
17194     // 'bool'.
17195     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17196       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17197           << FieldName << toString(Value, 10)
17198           << (unsigned)TypeWidth;
17199     }
17200   }
17201 
17202   return BitWidth;
17203 }
17204 
17205 /// ActOnField - Each field of a C struct/union is passed into this in order
17206 /// to create a FieldDecl object for it.
17207 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17208                        Declarator &D, Expr *BitfieldWidth) {
17209   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17210                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17211                                /*InitStyle=*/ICIS_NoInit, AS_public);
17212   return Res;
17213 }
17214 
17215 /// HandleField - Analyze a field of a C struct or a C++ data member.
17216 ///
17217 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17218                              SourceLocation DeclStart,
17219                              Declarator &D, Expr *BitWidth,
17220                              InClassInitStyle InitStyle,
17221                              AccessSpecifier AS) {
17222   if (D.isDecompositionDeclarator()) {
17223     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17224     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17225       << Decomp.getSourceRange();
17226     return nullptr;
17227   }
17228 
17229   IdentifierInfo *II = D.getIdentifier();
17230   SourceLocation Loc = DeclStart;
17231   if (II) Loc = D.getIdentifierLoc();
17232 
17233   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17234   QualType T = TInfo->getType();
17235   if (getLangOpts().CPlusPlus) {
17236     CheckExtraCXXDefaultArguments(D);
17237 
17238     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17239                                         UPPC_DataMemberType)) {
17240       D.setInvalidType();
17241       T = Context.IntTy;
17242       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17243     }
17244   }
17245 
17246   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17247 
17248   if (D.getDeclSpec().isInlineSpecified())
17249     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17250         << getLangOpts().CPlusPlus17;
17251   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17252     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17253          diag::err_invalid_thread)
17254       << DeclSpec::getSpecifierName(TSCS);
17255 
17256   // Check to see if this name was declared as a member previously
17257   NamedDecl *PrevDecl = nullptr;
17258   LookupResult Previous(*this, II, Loc, LookupMemberName,
17259                         ForVisibleRedeclaration);
17260   LookupName(Previous, S);
17261   switch (Previous.getResultKind()) {
17262     case LookupResult::Found:
17263     case LookupResult::FoundUnresolvedValue:
17264       PrevDecl = Previous.getAsSingle<NamedDecl>();
17265       break;
17266 
17267     case LookupResult::FoundOverloaded:
17268       PrevDecl = Previous.getRepresentativeDecl();
17269       break;
17270 
17271     case LookupResult::NotFound:
17272     case LookupResult::NotFoundInCurrentInstantiation:
17273     case LookupResult::Ambiguous:
17274       break;
17275   }
17276   Previous.suppressDiagnostics();
17277 
17278   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17279     // Maybe we will complain about the shadowed template parameter.
17280     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17281     // Just pretend that we didn't see the previous declaration.
17282     PrevDecl = nullptr;
17283   }
17284 
17285   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17286     PrevDecl = nullptr;
17287 
17288   bool Mutable
17289     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17290   SourceLocation TSSL = D.getBeginLoc();
17291   FieldDecl *NewFD
17292     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17293                      TSSL, AS, PrevDecl, &D);
17294 
17295   if (NewFD->isInvalidDecl())
17296     Record->setInvalidDecl();
17297 
17298   if (D.getDeclSpec().isModulePrivateSpecified())
17299     NewFD->setModulePrivate();
17300 
17301   if (NewFD->isInvalidDecl() && PrevDecl) {
17302     // Don't introduce NewFD into scope; there's already something
17303     // with the same name in the same scope.
17304   } else if (II) {
17305     PushOnScopeChains(NewFD, S);
17306   } else
17307     Record->addDecl(NewFD);
17308 
17309   return NewFD;
17310 }
17311 
17312 /// Build a new FieldDecl and check its well-formedness.
17313 ///
17314 /// This routine builds a new FieldDecl given the fields name, type,
17315 /// record, etc. \p PrevDecl should refer to any previous declaration
17316 /// with the same name and in the same scope as the field to be
17317 /// created.
17318 ///
17319 /// \returns a new FieldDecl.
17320 ///
17321 /// \todo The Declarator argument is a hack. It will be removed once
17322 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17323                                 TypeSourceInfo *TInfo,
17324                                 RecordDecl *Record, SourceLocation Loc,
17325                                 bool Mutable, Expr *BitWidth,
17326                                 InClassInitStyle InitStyle,
17327                                 SourceLocation TSSL,
17328                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17329                                 Declarator *D) {
17330   IdentifierInfo *II = Name.getAsIdentifierInfo();
17331   bool InvalidDecl = false;
17332   if (D) InvalidDecl = D->isInvalidType();
17333 
17334   // If we receive a broken type, recover by assuming 'int' and
17335   // marking this declaration as invalid.
17336   if (T.isNull() || T->containsErrors()) {
17337     InvalidDecl = true;
17338     T = Context.IntTy;
17339   }
17340 
17341   QualType EltTy = Context.getBaseElementType(T);
17342   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17343     if (RequireCompleteSizedType(Loc, EltTy,
17344                                  diag::err_field_incomplete_or_sizeless)) {
17345       // Fields of incomplete type force their record to be invalid.
17346       Record->setInvalidDecl();
17347       InvalidDecl = true;
17348     } else {
17349       NamedDecl *Def;
17350       EltTy->isIncompleteType(&Def);
17351       if (Def && Def->isInvalidDecl()) {
17352         Record->setInvalidDecl();
17353         InvalidDecl = true;
17354       }
17355     }
17356   }
17357 
17358   // TR 18037 does not allow fields to be declared with address space
17359   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17360       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17361     Diag(Loc, diag::err_field_with_address_space);
17362     Record->setInvalidDecl();
17363     InvalidDecl = true;
17364   }
17365 
17366   if (LangOpts.OpenCL) {
17367     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17368     // used as structure or union field: image, sampler, event or block types.
17369     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17370         T->isBlockPointerType()) {
17371       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17372       Record->setInvalidDecl();
17373       InvalidDecl = true;
17374     }
17375     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17376     // is enabled.
17377     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17378                         "__cl_clang_bitfields", LangOpts)) {
17379       Diag(Loc, diag::err_opencl_bitfields);
17380       InvalidDecl = true;
17381     }
17382   }
17383 
17384   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17385   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17386       T.hasQualifiers()) {
17387     InvalidDecl = true;
17388     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17389   }
17390 
17391   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17392   // than a variably modified type.
17393   if (!InvalidDecl && T->isVariablyModifiedType()) {
17394     if (!tryToFixVariablyModifiedVarType(
17395             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17396       InvalidDecl = true;
17397   }
17398 
17399   // Fields can not have abstract class types
17400   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17401                                              diag::err_abstract_type_in_decl,
17402                                              AbstractFieldType))
17403     InvalidDecl = true;
17404 
17405   if (InvalidDecl)
17406     BitWidth = nullptr;
17407   // If this is declared as a bit-field, check the bit-field.
17408   if (BitWidth) {
17409     BitWidth =
17410         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17411     if (!BitWidth) {
17412       InvalidDecl = true;
17413       BitWidth = nullptr;
17414     }
17415   }
17416 
17417   // Check that 'mutable' is consistent with the type of the declaration.
17418   if (!InvalidDecl && Mutable) {
17419     unsigned DiagID = 0;
17420     if (T->isReferenceType())
17421       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17422                                         : diag::err_mutable_reference;
17423     else if (T.isConstQualified())
17424       DiagID = diag::err_mutable_const;
17425 
17426     if (DiagID) {
17427       SourceLocation ErrLoc = Loc;
17428       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17429         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17430       Diag(ErrLoc, DiagID);
17431       if (DiagID != diag::ext_mutable_reference) {
17432         Mutable = false;
17433         InvalidDecl = true;
17434       }
17435     }
17436   }
17437 
17438   // C++11 [class.union]p8 (DR1460):
17439   //   At most one variant member of a union may have a
17440   //   brace-or-equal-initializer.
17441   if (InitStyle != ICIS_NoInit)
17442     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17443 
17444   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17445                                        BitWidth, Mutable, InitStyle);
17446   if (InvalidDecl)
17447     NewFD->setInvalidDecl();
17448 
17449   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17450     Diag(Loc, diag::err_duplicate_member) << II;
17451     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17452     NewFD->setInvalidDecl();
17453   }
17454 
17455   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17456     if (Record->isUnion()) {
17457       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17458         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17459         if (RDecl->getDefinition()) {
17460           // C++ [class.union]p1: An object of a class with a non-trivial
17461           // constructor, a non-trivial copy constructor, a non-trivial
17462           // destructor, or a non-trivial copy assignment operator
17463           // cannot be a member of a union, nor can an array of such
17464           // objects.
17465           if (CheckNontrivialField(NewFD))
17466             NewFD->setInvalidDecl();
17467         }
17468       }
17469 
17470       // C++ [class.union]p1: If a union contains a member of reference type,
17471       // the program is ill-formed, except when compiling with MSVC extensions
17472       // enabled.
17473       if (EltTy->isReferenceType()) {
17474         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17475                                     diag::ext_union_member_of_reference_type :
17476                                     diag::err_union_member_of_reference_type)
17477           << NewFD->getDeclName() << EltTy;
17478         if (!getLangOpts().MicrosoftExt)
17479           NewFD->setInvalidDecl();
17480       }
17481     }
17482   }
17483 
17484   // FIXME: We need to pass in the attributes given an AST
17485   // representation, not a parser representation.
17486   if (D) {
17487     // FIXME: The current scope is almost... but not entirely... correct here.
17488     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17489 
17490     if (NewFD->hasAttrs())
17491       CheckAlignasUnderalignment(NewFD);
17492   }
17493 
17494   // In auto-retain/release, infer strong retension for fields of
17495   // retainable type.
17496   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17497     NewFD->setInvalidDecl();
17498 
17499   if (T.isObjCGCWeak())
17500     Diag(Loc, diag::warn_attribute_weak_on_field);
17501 
17502   // PPC MMA non-pointer types are not allowed as field types.
17503   if (Context.getTargetInfo().getTriple().isPPC64() &&
17504       CheckPPCMMAType(T, NewFD->getLocation()))
17505     NewFD->setInvalidDecl();
17506 
17507   NewFD->setAccess(AS);
17508   return NewFD;
17509 }
17510 
17511 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17512   assert(FD);
17513   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17514 
17515   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17516     return false;
17517 
17518   QualType EltTy = Context.getBaseElementType(FD->getType());
17519   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17520     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17521     if (RDecl->getDefinition()) {
17522       // We check for copy constructors before constructors
17523       // because otherwise we'll never get complaints about
17524       // copy constructors.
17525 
17526       CXXSpecialMember member = CXXInvalid;
17527       // We're required to check for any non-trivial constructors. Since the
17528       // implicit default constructor is suppressed if there are any
17529       // user-declared constructors, we just need to check that there is a
17530       // trivial default constructor and a trivial copy constructor. (We don't
17531       // worry about move constructors here, since this is a C++98 check.)
17532       if (RDecl->hasNonTrivialCopyConstructor())
17533         member = CXXCopyConstructor;
17534       else if (!RDecl->hasTrivialDefaultConstructor())
17535         member = CXXDefaultConstructor;
17536       else if (RDecl->hasNonTrivialCopyAssignment())
17537         member = CXXCopyAssignment;
17538       else if (RDecl->hasNonTrivialDestructor())
17539         member = CXXDestructor;
17540 
17541       if (member != CXXInvalid) {
17542         if (!getLangOpts().CPlusPlus11 &&
17543             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17544           // Objective-C++ ARC: it is an error to have a non-trivial field of
17545           // a union. However, system headers in Objective-C programs
17546           // occasionally have Objective-C lifetime objects within unions,
17547           // and rather than cause the program to fail, we make those
17548           // members unavailable.
17549           SourceLocation Loc = FD->getLocation();
17550           if (getSourceManager().isInSystemHeader(Loc)) {
17551             if (!FD->hasAttr<UnavailableAttr>())
17552               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17553                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17554             return false;
17555           }
17556         }
17557 
17558         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17559                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17560                diag::err_illegal_union_or_anon_struct_member)
17561           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17562         DiagnoseNontrivial(RDecl, member);
17563         return !getLangOpts().CPlusPlus11;
17564       }
17565     }
17566   }
17567 
17568   return false;
17569 }
17570 
17571 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17572 ///  AST enum value.
17573 static ObjCIvarDecl::AccessControl
17574 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17575   switch (ivarVisibility) {
17576   default: llvm_unreachable("Unknown visitibility kind");
17577   case tok::objc_private: return ObjCIvarDecl::Private;
17578   case tok::objc_public: return ObjCIvarDecl::Public;
17579   case tok::objc_protected: return ObjCIvarDecl::Protected;
17580   case tok::objc_package: return ObjCIvarDecl::Package;
17581   }
17582 }
17583 
17584 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17585 /// in order to create an IvarDecl object for it.
17586 Decl *Sema::ActOnIvar(Scope *S,
17587                                 SourceLocation DeclStart,
17588                                 Declarator &D, Expr *BitfieldWidth,
17589                                 tok::ObjCKeywordKind Visibility) {
17590 
17591   IdentifierInfo *II = D.getIdentifier();
17592   Expr *BitWidth = (Expr*)BitfieldWidth;
17593   SourceLocation Loc = DeclStart;
17594   if (II) Loc = D.getIdentifierLoc();
17595 
17596   // FIXME: Unnamed fields can be handled in various different ways, for
17597   // example, unnamed unions inject all members into the struct namespace!
17598 
17599   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17600   QualType T = TInfo->getType();
17601 
17602   if (BitWidth) {
17603     // 6.7.2.1p3, 6.7.2.1p4
17604     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17605     if (!BitWidth)
17606       D.setInvalidType();
17607   } else {
17608     // Not a bitfield.
17609 
17610     // validate II.
17611 
17612   }
17613   if (T->isReferenceType()) {
17614     Diag(Loc, diag::err_ivar_reference_type);
17615     D.setInvalidType();
17616   }
17617   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17618   // than a variably modified type.
17619   else if (T->isVariablyModifiedType()) {
17620     if (!tryToFixVariablyModifiedVarType(
17621             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17622       D.setInvalidType();
17623   }
17624 
17625   // Get the visibility (access control) for this ivar.
17626   ObjCIvarDecl::AccessControl ac =
17627     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17628                                         : ObjCIvarDecl::None;
17629   // Must set ivar's DeclContext to its enclosing interface.
17630   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17631   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17632     return nullptr;
17633   ObjCContainerDecl *EnclosingContext;
17634   if (ObjCImplementationDecl *IMPDecl =
17635       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17636     if (LangOpts.ObjCRuntime.isFragile()) {
17637     // Case of ivar declared in an implementation. Context is that of its class.
17638       EnclosingContext = IMPDecl->getClassInterface();
17639       assert(EnclosingContext && "Implementation has no class interface!");
17640     }
17641     else
17642       EnclosingContext = EnclosingDecl;
17643   } else {
17644     if (ObjCCategoryDecl *CDecl =
17645         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17646       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17647         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17648         return nullptr;
17649       }
17650     }
17651     EnclosingContext = EnclosingDecl;
17652   }
17653 
17654   // Construct the decl.
17655   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17656                                              DeclStart, Loc, II, T,
17657                                              TInfo, ac, (Expr *)BitfieldWidth);
17658 
17659   if (II) {
17660     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17661                                            ForVisibleRedeclaration);
17662     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17663         && !isa<TagDecl>(PrevDecl)) {
17664       Diag(Loc, diag::err_duplicate_member) << II;
17665       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17666       NewID->setInvalidDecl();
17667     }
17668   }
17669 
17670   // Process attributes attached to the ivar.
17671   ProcessDeclAttributes(S, NewID, D);
17672 
17673   if (D.isInvalidType())
17674     NewID->setInvalidDecl();
17675 
17676   // In ARC, infer 'retaining' for ivars of retainable type.
17677   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17678     NewID->setInvalidDecl();
17679 
17680   if (D.getDeclSpec().isModulePrivateSpecified())
17681     NewID->setModulePrivate();
17682 
17683   if (II) {
17684     // FIXME: When interfaces are DeclContexts, we'll need to add
17685     // these to the interface.
17686     S->AddDecl(NewID);
17687     IdResolver.AddDecl(NewID);
17688   }
17689 
17690   if (LangOpts.ObjCRuntime.isNonFragile() &&
17691       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17692     Diag(Loc, diag::warn_ivars_in_interface);
17693 
17694   return NewID;
17695 }
17696 
17697 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17698 /// class and class extensions. For every class \@interface and class
17699 /// extension \@interface, if the last ivar is a bitfield of any type,
17700 /// then add an implicit `char :0` ivar to the end of that interface.
17701 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17702                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17703   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17704     return;
17705 
17706   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17707   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17708 
17709   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17710     return;
17711   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17712   if (!ID) {
17713     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17714       if (!CD->IsClassExtension())
17715         return;
17716     }
17717     // No need to add this to end of @implementation.
17718     else
17719       return;
17720   }
17721   // All conditions are met. Add a new bitfield to the tail end of ivars.
17722   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17723   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17724 
17725   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17726                               DeclLoc, DeclLoc, nullptr,
17727                               Context.CharTy,
17728                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17729                                                                DeclLoc),
17730                               ObjCIvarDecl::Private, BW,
17731                               true);
17732   AllIvarDecls.push_back(Ivar);
17733 }
17734 
17735 namespace {
17736 /// [class.dtor]p4:
17737 ///   At the end of the definition of a class, overload resolution is
17738 ///   performed among the prospective destructors declared in that class with
17739 ///   an empty argument list to select the destructor for the class, also
17740 ///   known as the selected destructor.
17741 ///
17742 /// We do the overload resolution here, then mark the selected constructor in the AST.
17743 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17744 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17745   if (!Record->hasUserDeclaredDestructor()) {
17746     return;
17747   }
17748 
17749   SourceLocation Loc = Record->getLocation();
17750   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17751 
17752   for (auto *Decl : Record->decls()) {
17753     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17754       if (DD->isInvalidDecl())
17755         continue;
17756       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17757                              OCS);
17758       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17759     }
17760   }
17761 
17762   if (OCS.empty()) {
17763     return;
17764   }
17765   OverloadCandidateSet::iterator Best;
17766   unsigned Msg = 0;
17767   OverloadCandidateDisplayKind DisplayKind;
17768 
17769   switch (OCS.BestViableFunction(S, Loc, Best)) {
17770   case OR_Success:
17771   case OR_Deleted:
17772     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17773     break;
17774 
17775   case OR_Ambiguous:
17776     Msg = diag::err_ambiguous_destructor;
17777     DisplayKind = OCD_AmbiguousCandidates;
17778     break;
17779 
17780   case OR_No_Viable_Function:
17781     Msg = diag::err_no_viable_destructor;
17782     DisplayKind = OCD_AllCandidates;
17783     break;
17784   }
17785 
17786   if (Msg) {
17787     // OpenCL have got their own thing going with destructors. It's slightly broken,
17788     // but we allow it.
17789     if (!S.LangOpts.OpenCL) {
17790       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17791       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17792       Record->setInvalidDecl();
17793     }
17794     // It's a bit hacky: At this point we've raised an error but we want the
17795     // rest of the compiler to continue somehow working. However almost
17796     // everything we'll try to do with the class will depend on there being a
17797     // destructor. So let's pretend the first one is selected and hope for the
17798     // best.
17799     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17800   }
17801 }
17802 } // namespace
17803 
17804 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17805                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17806                        SourceLocation RBrac,
17807                        const ParsedAttributesView &Attrs) {
17808   assert(EnclosingDecl && "missing record or interface decl");
17809 
17810   // If this is an Objective-C @implementation or category and we have
17811   // new fields here we should reset the layout of the interface since
17812   // it will now change.
17813   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17814     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17815     switch (DC->getKind()) {
17816     default: break;
17817     case Decl::ObjCCategory:
17818       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17819       break;
17820     case Decl::ObjCImplementation:
17821       Context.
17822         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17823       break;
17824     }
17825   }
17826 
17827   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17828   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17829 
17830   if (CXXRecord && !CXXRecord->isDependentType())
17831     ComputeSelectedDestructor(*this, CXXRecord);
17832 
17833   // Start counting up the number of named members; make sure to include
17834   // members of anonymous structs and unions in the total.
17835   unsigned NumNamedMembers = 0;
17836   if (Record) {
17837     for (const auto *I : Record->decls()) {
17838       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17839         if (IFD->getDeclName())
17840           ++NumNamedMembers;
17841     }
17842   }
17843 
17844   // Verify that all the fields are okay.
17845   SmallVector<FieldDecl*, 32> RecFields;
17846 
17847   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17848        i != end; ++i) {
17849     FieldDecl *FD = cast<FieldDecl>(*i);
17850 
17851     // Get the type for the field.
17852     const Type *FDTy = FD->getType().getTypePtr();
17853 
17854     if (!FD->isAnonymousStructOrUnion()) {
17855       // Remember all fields written by the user.
17856       RecFields.push_back(FD);
17857     }
17858 
17859     // If the field is already invalid for some reason, don't emit more
17860     // diagnostics about it.
17861     if (FD->isInvalidDecl()) {
17862       EnclosingDecl->setInvalidDecl();
17863       continue;
17864     }
17865 
17866     // C99 6.7.2.1p2:
17867     //   A structure or union shall not contain a member with
17868     //   incomplete or function type (hence, a structure shall not
17869     //   contain an instance of itself, but may contain a pointer to
17870     //   an instance of itself), except that the last member of a
17871     //   structure with more than one named member may have incomplete
17872     //   array type; such a structure (and any union containing,
17873     //   possibly recursively, a member that is such a structure)
17874     //   shall not be a member of a structure or an element of an
17875     //   array.
17876     bool IsLastField = (i + 1 == Fields.end());
17877     if (FDTy->isFunctionType()) {
17878       // Field declared as a function.
17879       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17880         << FD->getDeclName();
17881       FD->setInvalidDecl();
17882       EnclosingDecl->setInvalidDecl();
17883       continue;
17884     } else if (FDTy->isIncompleteArrayType() &&
17885                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17886       if (Record) {
17887         // Flexible array member.
17888         // Microsoft and g++ is more permissive regarding flexible array.
17889         // It will accept flexible array in union and also
17890         // as the sole element of a struct/class.
17891         unsigned DiagID = 0;
17892         if (!Record->isUnion() && !IsLastField) {
17893           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17894             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17895           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17896           FD->setInvalidDecl();
17897           EnclosingDecl->setInvalidDecl();
17898           continue;
17899         } else if (Record->isUnion())
17900           DiagID = getLangOpts().MicrosoftExt
17901                        ? diag::ext_flexible_array_union_ms
17902                        : getLangOpts().CPlusPlus
17903                              ? diag::ext_flexible_array_union_gnu
17904                              : diag::err_flexible_array_union;
17905         else if (NumNamedMembers < 1)
17906           DiagID = getLangOpts().MicrosoftExt
17907                        ? diag::ext_flexible_array_empty_aggregate_ms
17908                        : getLangOpts().CPlusPlus
17909                              ? diag::ext_flexible_array_empty_aggregate_gnu
17910                              : diag::err_flexible_array_empty_aggregate;
17911 
17912         if (DiagID)
17913           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17914                                           << Record->getTagKind();
17915         // While the layout of types that contain virtual bases is not specified
17916         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17917         // virtual bases after the derived members.  This would make a flexible
17918         // array member declared at the end of an object not adjacent to the end
17919         // of the type.
17920         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17921           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17922               << FD->getDeclName() << Record->getTagKind();
17923         if (!getLangOpts().C99)
17924           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17925             << FD->getDeclName() << Record->getTagKind();
17926 
17927         // If the element type has a non-trivial destructor, we would not
17928         // implicitly destroy the elements, so disallow it for now.
17929         //
17930         // FIXME: GCC allows this. We should probably either implicitly delete
17931         // the destructor of the containing class, or just allow this.
17932         QualType BaseElem = Context.getBaseElementType(FD->getType());
17933         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17934           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17935             << FD->getDeclName() << FD->getType();
17936           FD->setInvalidDecl();
17937           EnclosingDecl->setInvalidDecl();
17938           continue;
17939         }
17940         // Okay, we have a legal flexible array member at the end of the struct.
17941         Record->setHasFlexibleArrayMember(true);
17942       } else {
17943         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17944         // unless they are followed by another ivar. That check is done
17945         // elsewhere, after synthesized ivars are known.
17946       }
17947     } else if (!FDTy->isDependentType() &&
17948                RequireCompleteSizedType(
17949                    FD->getLocation(), FD->getType(),
17950                    diag::err_field_incomplete_or_sizeless)) {
17951       // Incomplete type
17952       FD->setInvalidDecl();
17953       EnclosingDecl->setInvalidDecl();
17954       continue;
17955     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17956       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17957         // A type which contains a flexible array member is considered to be a
17958         // flexible array member.
17959         Record->setHasFlexibleArrayMember(true);
17960         if (!Record->isUnion()) {
17961           // If this is a struct/class and this is not the last element, reject
17962           // it.  Note that GCC supports variable sized arrays in the middle of
17963           // structures.
17964           if (!IsLastField)
17965             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17966               << FD->getDeclName() << FD->getType();
17967           else {
17968             // We support flexible arrays at the end of structs in
17969             // other structs as an extension.
17970             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17971               << FD->getDeclName();
17972           }
17973         }
17974       }
17975       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17976           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17977                                  diag::err_abstract_type_in_decl,
17978                                  AbstractIvarType)) {
17979         // Ivars can not have abstract class types
17980         FD->setInvalidDecl();
17981       }
17982       if (Record && FDTTy->getDecl()->hasObjectMember())
17983         Record->setHasObjectMember(true);
17984       if (Record && FDTTy->getDecl()->hasVolatileMember())
17985         Record->setHasVolatileMember(true);
17986     } else if (FDTy->isObjCObjectType()) {
17987       /// A field cannot be an Objective-c object
17988       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17989         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17990       QualType T = Context.getObjCObjectPointerType(FD->getType());
17991       FD->setType(T);
17992     } else if (Record && Record->isUnion() &&
17993                FD->getType().hasNonTrivialObjCLifetime() &&
17994                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17995                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17996                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17997                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17998       // For backward compatibility, fields of C unions declared in system
17999       // headers that have non-trivial ObjC ownership qualifications are marked
18000       // as unavailable unless the qualifier is explicit and __strong. This can
18001       // break ABI compatibility between programs compiled with ARC and MRR, but
18002       // is a better option than rejecting programs using those unions under
18003       // ARC.
18004       FD->addAttr(UnavailableAttr::CreateImplicit(
18005           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18006           FD->getLocation()));
18007     } else if (getLangOpts().ObjC &&
18008                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18009                !Record->hasObjectMember()) {
18010       if (FD->getType()->isObjCObjectPointerType() ||
18011           FD->getType().isObjCGCStrong())
18012         Record->setHasObjectMember(true);
18013       else if (Context.getAsArrayType(FD->getType())) {
18014         QualType BaseType = Context.getBaseElementType(FD->getType());
18015         if (BaseType->isRecordType() &&
18016             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18017           Record->setHasObjectMember(true);
18018         else if (BaseType->isObjCObjectPointerType() ||
18019                  BaseType.isObjCGCStrong())
18020                Record->setHasObjectMember(true);
18021       }
18022     }
18023 
18024     if (Record && !getLangOpts().CPlusPlus &&
18025         !shouldIgnoreForRecordTriviality(FD)) {
18026       QualType FT = FD->getType();
18027       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18028         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18029         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18030             Record->isUnion())
18031           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18032       }
18033       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18034       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18035         Record->setNonTrivialToPrimitiveCopy(true);
18036         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18037           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18038       }
18039       if (FT.isDestructedType()) {
18040         Record->setNonTrivialToPrimitiveDestroy(true);
18041         Record->setParamDestroyedInCallee(true);
18042         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18043           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18044       }
18045 
18046       if (const auto *RT = FT->getAs<RecordType>()) {
18047         if (RT->getDecl()->getArgPassingRestrictions() ==
18048             RecordDecl::APK_CanNeverPassInRegs)
18049           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18050       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18051         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18052     }
18053 
18054     if (Record && FD->getType().isVolatileQualified())
18055       Record->setHasVolatileMember(true);
18056     // Keep track of the number of named members.
18057     if (FD->getIdentifier())
18058       ++NumNamedMembers;
18059   }
18060 
18061   // Okay, we successfully defined 'Record'.
18062   if (Record) {
18063     bool Completed = false;
18064     if (CXXRecord) {
18065       if (!CXXRecord->isInvalidDecl()) {
18066         // Set access bits correctly on the directly-declared conversions.
18067         for (CXXRecordDecl::conversion_iterator
18068                I = CXXRecord->conversion_begin(),
18069                E = CXXRecord->conversion_end(); I != E; ++I)
18070           I.setAccess((*I)->getAccess());
18071       }
18072 
18073       // Add any implicitly-declared members to this class.
18074       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18075 
18076       if (!CXXRecord->isDependentType()) {
18077         if (!CXXRecord->isInvalidDecl()) {
18078           // If we have virtual base classes, we may end up finding multiple
18079           // final overriders for a given virtual function. Check for this
18080           // problem now.
18081           if (CXXRecord->getNumVBases()) {
18082             CXXFinalOverriderMap FinalOverriders;
18083             CXXRecord->getFinalOverriders(FinalOverriders);
18084 
18085             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18086                                              MEnd = FinalOverriders.end();
18087                  M != MEnd; ++M) {
18088               for (OverridingMethods::iterator SO = M->second.begin(),
18089                                             SOEnd = M->second.end();
18090                    SO != SOEnd; ++SO) {
18091                 assert(SO->second.size() > 0 &&
18092                        "Virtual function without overriding functions?");
18093                 if (SO->second.size() == 1)
18094                   continue;
18095 
18096                 // C++ [class.virtual]p2:
18097                 //   In a derived class, if a virtual member function of a base
18098                 //   class subobject has more than one final overrider the
18099                 //   program is ill-formed.
18100                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18101                   << (const NamedDecl *)M->first << Record;
18102                 Diag(M->first->getLocation(),
18103                      diag::note_overridden_virtual_function);
18104                 for (OverridingMethods::overriding_iterator
18105                           OM = SO->second.begin(),
18106                        OMEnd = SO->second.end();
18107                      OM != OMEnd; ++OM)
18108                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18109                     << (const NamedDecl *)M->first << OM->Method->getParent();
18110 
18111                 Record->setInvalidDecl();
18112               }
18113             }
18114             CXXRecord->completeDefinition(&FinalOverriders);
18115             Completed = true;
18116           }
18117         }
18118       }
18119     }
18120 
18121     if (!Completed)
18122       Record->completeDefinition();
18123 
18124     // Handle attributes before checking the layout.
18125     ProcessDeclAttributeList(S, Record, Attrs);
18126 
18127     // Check to see if a FieldDecl is a pointer to a function.
18128     auto IsFunctionPointer = [&](const Decl *D) {
18129       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18130       if (!FD)
18131         return false;
18132       QualType FieldType = FD->getType().getDesugaredType(Context);
18133       if (isa<PointerType>(FieldType)) {
18134         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18135         return PointeeType.getDesugaredType(Context)->isFunctionType();
18136       }
18137       return false;
18138     };
18139 
18140     // Maybe randomize the record's decls. We automatically randomize a record
18141     // of function pointers, unless it has the "no_randomize_layout" attribute.
18142     if (!getLangOpts().CPlusPlus &&
18143         (Record->hasAttr<RandomizeLayoutAttr>() ||
18144          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18145           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18146         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18147         !Record->isRandomized()) {
18148       SmallVector<Decl *, 32> NewDeclOrdering;
18149       if (randstruct::randomizeStructureLayout(Context, Record,
18150                                                NewDeclOrdering))
18151         Record->reorderDecls(NewDeclOrdering);
18152     }
18153 
18154     // We may have deferred checking for a deleted destructor. Check now.
18155     if (CXXRecord) {
18156       auto *Dtor = CXXRecord->getDestructor();
18157       if (Dtor && Dtor->isImplicit() &&
18158           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18159         CXXRecord->setImplicitDestructorIsDeleted();
18160         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18161       }
18162     }
18163 
18164     if (Record->hasAttrs()) {
18165       CheckAlignasUnderalignment(Record);
18166 
18167       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18168         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18169                                            IA->getRange(), IA->getBestCase(),
18170                                            IA->getInheritanceModel());
18171     }
18172 
18173     // Check if the structure/union declaration is a type that can have zero
18174     // size in C. For C this is a language extension, for C++ it may cause
18175     // compatibility problems.
18176     bool CheckForZeroSize;
18177     if (!getLangOpts().CPlusPlus) {
18178       CheckForZeroSize = true;
18179     } else {
18180       // For C++ filter out types that cannot be referenced in C code.
18181       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18182       CheckForZeroSize =
18183           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18184           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18185           CXXRecord->isCLike();
18186     }
18187     if (CheckForZeroSize) {
18188       bool ZeroSize = true;
18189       bool IsEmpty = true;
18190       unsigned NonBitFields = 0;
18191       for (RecordDecl::field_iterator I = Record->field_begin(),
18192                                       E = Record->field_end();
18193            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18194         IsEmpty = false;
18195         if (I->isUnnamedBitfield()) {
18196           if (!I->isZeroLengthBitField(Context))
18197             ZeroSize = false;
18198         } else {
18199           ++NonBitFields;
18200           QualType FieldType = I->getType();
18201           if (FieldType->isIncompleteType() ||
18202               !Context.getTypeSizeInChars(FieldType).isZero())
18203             ZeroSize = false;
18204         }
18205       }
18206 
18207       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18208       // allowed in C++, but warn if its declaration is inside
18209       // extern "C" block.
18210       if (ZeroSize) {
18211         Diag(RecLoc, getLangOpts().CPlusPlus ?
18212                          diag::warn_zero_size_struct_union_in_extern_c :
18213                          diag::warn_zero_size_struct_union_compat)
18214           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18215       }
18216 
18217       // Structs without named members are extension in C (C99 6.7.2.1p7),
18218       // but are accepted by GCC.
18219       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18220         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18221                                diag::ext_no_named_members_in_struct_union)
18222           << Record->isUnion();
18223       }
18224     }
18225   } else {
18226     ObjCIvarDecl **ClsFields =
18227       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18228     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18229       ID->setEndOfDefinitionLoc(RBrac);
18230       // Add ivar's to class's DeclContext.
18231       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18232         ClsFields[i]->setLexicalDeclContext(ID);
18233         ID->addDecl(ClsFields[i]);
18234       }
18235       // Must enforce the rule that ivars in the base classes may not be
18236       // duplicates.
18237       if (ID->getSuperClass())
18238         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18239     } else if (ObjCImplementationDecl *IMPDecl =
18240                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18241       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18242       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18243         // Ivar declared in @implementation never belongs to the implementation.
18244         // Only it is in implementation's lexical context.
18245         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18246       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18247       IMPDecl->setIvarLBraceLoc(LBrac);
18248       IMPDecl->setIvarRBraceLoc(RBrac);
18249     } else if (ObjCCategoryDecl *CDecl =
18250                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18251       // case of ivars in class extension; all other cases have been
18252       // reported as errors elsewhere.
18253       // FIXME. Class extension does not have a LocEnd field.
18254       // CDecl->setLocEnd(RBrac);
18255       // Add ivar's to class extension's DeclContext.
18256       // Diagnose redeclaration of private ivars.
18257       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18258       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18259         if (IDecl) {
18260           if (const ObjCIvarDecl *ClsIvar =
18261               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18262             Diag(ClsFields[i]->getLocation(),
18263                  diag::err_duplicate_ivar_declaration);
18264             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18265             continue;
18266           }
18267           for (const auto *Ext : IDecl->known_extensions()) {
18268             if (const ObjCIvarDecl *ClsExtIvar
18269                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18270               Diag(ClsFields[i]->getLocation(),
18271                    diag::err_duplicate_ivar_declaration);
18272               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18273               continue;
18274             }
18275           }
18276         }
18277         ClsFields[i]->setLexicalDeclContext(CDecl);
18278         CDecl->addDecl(ClsFields[i]);
18279       }
18280       CDecl->setIvarLBraceLoc(LBrac);
18281       CDecl->setIvarRBraceLoc(RBrac);
18282     }
18283   }
18284 }
18285 
18286 /// Determine whether the given integral value is representable within
18287 /// the given type T.
18288 static bool isRepresentableIntegerValue(ASTContext &Context,
18289                                         llvm::APSInt &Value,
18290                                         QualType T) {
18291   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18292          "Integral type required!");
18293   unsigned BitWidth = Context.getIntWidth(T);
18294 
18295   if (Value.isUnsigned() || Value.isNonNegative()) {
18296     if (T->isSignedIntegerOrEnumerationType())
18297       --BitWidth;
18298     return Value.getActiveBits() <= BitWidth;
18299   }
18300   return Value.getMinSignedBits() <= BitWidth;
18301 }
18302 
18303 // Given an integral type, return the next larger integral type
18304 // (or a NULL type of no such type exists).
18305 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18306   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18307   // enum checking below.
18308   assert((T->isIntegralType(Context) ||
18309          T->isEnumeralType()) && "Integral type required!");
18310   const unsigned NumTypes = 4;
18311   QualType SignedIntegralTypes[NumTypes] = {
18312     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18313   };
18314   QualType UnsignedIntegralTypes[NumTypes] = {
18315     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18316     Context.UnsignedLongLongTy
18317   };
18318 
18319   unsigned BitWidth = Context.getTypeSize(T);
18320   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18321                                                         : UnsignedIntegralTypes;
18322   for (unsigned I = 0; I != NumTypes; ++I)
18323     if (Context.getTypeSize(Types[I]) > BitWidth)
18324       return Types[I];
18325 
18326   return QualType();
18327 }
18328 
18329 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18330                                           EnumConstantDecl *LastEnumConst,
18331                                           SourceLocation IdLoc,
18332                                           IdentifierInfo *Id,
18333                                           Expr *Val) {
18334   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18335   llvm::APSInt EnumVal(IntWidth);
18336   QualType EltTy;
18337 
18338   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18339     Val = nullptr;
18340 
18341   if (Val)
18342     Val = DefaultLvalueConversion(Val).get();
18343 
18344   if (Val) {
18345     if (Enum->isDependentType() || Val->isTypeDependent() ||
18346         Val->containsErrors())
18347       EltTy = Context.DependentTy;
18348     else {
18349       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18350       // underlying type, but do allow it in all other contexts.
18351       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18352         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18353         // constant-expression in the enumerator-definition shall be a converted
18354         // constant expression of the underlying type.
18355         EltTy = Enum->getIntegerType();
18356         ExprResult Converted =
18357           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18358                                            CCEK_Enumerator);
18359         if (Converted.isInvalid())
18360           Val = nullptr;
18361         else
18362           Val = Converted.get();
18363       } else if (!Val->isValueDependent() &&
18364                  !(Val =
18365                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18366                            .get())) {
18367         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18368       } else {
18369         if (Enum->isComplete()) {
18370           EltTy = Enum->getIntegerType();
18371 
18372           // In Obj-C and Microsoft mode, require the enumeration value to be
18373           // representable in the underlying type of the enumeration. In C++11,
18374           // we perform a non-narrowing conversion as part of converted constant
18375           // expression checking.
18376           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18377             if (Context.getTargetInfo()
18378                     .getTriple()
18379                     .isWindowsMSVCEnvironment()) {
18380               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18381             } else {
18382               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18383             }
18384           }
18385 
18386           // Cast to the underlying type.
18387           Val = ImpCastExprToType(Val, EltTy,
18388                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18389                                                          : CK_IntegralCast)
18390                     .get();
18391         } else if (getLangOpts().CPlusPlus) {
18392           // C++11 [dcl.enum]p5:
18393           //   If the underlying type is not fixed, the type of each enumerator
18394           //   is the type of its initializing value:
18395           //     - If an initializer is specified for an enumerator, the
18396           //       initializing value has the same type as the expression.
18397           EltTy = Val->getType();
18398         } else {
18399           // C99 6.7.2.2p2:
18400           //   The expression that defines the value of an enumeration constant
18401           //   shall be an integer constant expression that has a value
18402           //   representable as an int.
18403 
18404           // Complain if the value is not representable in an int.
18405           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18406             Diag(IdLoc, diag::ext_enum_value_not_int)
18407               << toString(EnumVal, 10) << Val->getSourceRange()
18408               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18409           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18410             // Force the type of the expression to 'int'.
18411             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18412           }
18413           EltTy = Val->getType();
18414         }
18415       }
18416     }
18417   }
18418 
18419   if (!Val) {
18420     if (Enum->isDependentType())
18421       EltTy = Context.DependentTy;
18422     else if (!LastEnumConst) {
18423       // C++0x [dcl.enum]p5:
18424       //   If the underlying type is not fixed, the type of each enumerator
18425       //   is the type of its initializing value:
18426       //     - If no initializer is specified for the first enumerator, the
18427       //       initializing value has an unspecified integral type.
18428       //
18429       // GCC uses 'int' for its unspecified integral type, as does
18430       // C99 6.7.2.2p3.
18431       if (Enum->isFixed()) {
18432         EltTy = Enum->getIntegerType();
18433       }
18434       else {
18435         EltTy = Context.IntTy;
18436       }
18437     } else {
18438       // Assign the last value + 1.
18439       EnumVal = LastEnumConst->getInitVal();
18440       ++EnumVal;
18441       EltTy = LastEnumConst->getType();
18442 
18443       // Check for overflow on increment.
18444       if (EnumVal < LastEnumConst->getInitVal()) {
18445         // C++0x [dcl.enum]p5:
18446         //   If the underlying type is not fixed, the type of each enumerator
18447         //   is the type of its initializing value:
18448         //
18449         //     - Otherwise the type of the initializing value is the same as
18450         //       the type of the initializing value of the preceding enumerator
18451         //       unless the incremented value is not representable in that type,
18452         //       in which case the type is an unspecified integral type
18453         //       sufficient to contain the incremented value. If no such type
18454         //       exists, the program is ill-formed.
18455         QualType T = getNextLargerIntegralType(Context, EltTy);
18456         if (T.isNull() || Enum->isFixed()) {
18457           // There is no integral type larger enough to represent this
18458           // value. Complain, then allow the value to wrap around.
18459           EnumVal = LastEnumConst->getInitVal();
18460           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18461           ++EnumVal;
18462           if (Enum->isFixed())
18463             // When the underlying type is fixed, this is ill-formed.
18464             Diag(IdLoc, diag::err_enumerator_wrapped)
18465               << toString(EnumVal, 10)
18466               << EltTy;
18467           else
18468             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18469               << toString(EnumVal, 10);
18470         } else {
18471           EltTy = T;
18472         }
18473 
18474         // Retrieve the last enumerator's value, extent that type to the
18475         // type that is supposed to be large enough to represent the incremented
18476         // value, then increment.
18477         EnumVal = LastEnumConst->getInitVal();
18478         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18479         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18480         ++EnumVal;
18481 
18482         // If we're not in C++, diagnose the overflow of enumerator values,
18483         // which in C99 means that the enumerator value is not representable in
18484         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18485         // permits enumerator values that are representable in some larger
18486         // integral type.
18487         if (!getLangOpts().CPlusPlus && !T.isNull())
18488           Diag(IdLoc, diag::warn_enum_value_overflow);
18489       } else if (!getLangOpts().CPlusPlus &&
18490                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18491         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18492         Diag(IdLoc, diag::ext_enum_value_not_int)
18493           << toString(EnumVal, 10) << 1;
18494       }
18495     }
18496   }
18497 
18498   if (!EltTy->isDependentType()) {
18499     // Make the enumerator value match the signedness and size of the
18500     // enumerator's type.
18501     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18502     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18503   }
18504 
18505   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18506                                   Val, EnumVal);
18507 }
18508 
18509 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18510                                                 SourceLocation IILoc) {
18511   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18512       !getLangOpts().CPlusPlus)
18513     return SkipBodyInfo();
18514 
18515   // We have an anonymous enum definition. Look up the first enumerator to
18516   // determine if we should merge the definition with an existing one and
18517   // skip the body.
18518   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18519                                          forRedeclarationInCurContext());
18520   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18521   if (!PrevECD)
18522     return SkipBodyInfo();
18523 
18524   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18525   NamedDecl *Hidden;
18526   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18527     SkipBodyInfo Skip;
18528     Skip.Previous = Hidden;
18529     return Skip;
18530   }
18531 
18532   return SkipBodyInfo();
18533 }
18534 
18535 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18536                               SourceLocation IdLoc, IdentifierInfo *Id,
18537                               const ParsedAttributesView &Attrs,
18538                               SourceLocation EqualLoc, Expr *Val) {
18539   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18540   EnumConstantDecl *LastEnumConst =
18541     cast_or_null<EnumConstantDecl>(lastEnumConst);
18542 
18543   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18544   // we find one that is.
18545   S = getNonFieldDeclScope(S);
18546 
18547   // Verify that there isn't already something declared with this name in this
18548   // scope.
18549   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18550   LookupName(R, S);
18551   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18552 
18553   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18554     // Maybe we will complain about the shadowed template parameter.
18555     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18556     // Just pretend that we didn't see the previous declaration.
18557     PrevDecl = nullptr;
18558   }
18559 
18560   // C++ [class.mem]p15:
18561   // If T is the name of a class, then each of the following shall have a name
18562   // different from T:
18563   // - every enumerator of every member of class T that is an unscoped
18564   // enumerated type
18565   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18566     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18567                             DeclarationNameInfo(Id, IdLoc));
18568 
18569   EnumConstantDecl *New =
18570     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18571   if (!New)
18572     return nullptr;
18573 
18574   if (PrevDecl) {
18575     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18576       // Check for other kinds of shadowing not already handled.
18577       CheckShadow(New, PrevDecl, R);
18578     }
18579 
18580     // When in C++, we may get a TagDecl with the same name; in this case the
18581     // enum constant will 'hide' the tag.
18582     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18583            "Received TagDecl when not in C++!");
18584     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18585       if (isa<EnumConstantDecl>(PrevDecl))
18586         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18587       else
18588         Diag(IdLoc, diag::err_redefinition) << Id;
18589       notePreviousDefinition(PrevDecl, IdLoc);
18590       return nullptr;
18591     }
18592   }
18593 
18594   // Process attributes.
18595   ProcessDeclAttributeList(S, New, Attrs);
18596   AddPragmaAttributes(S, New);
18597 
18598   // Register this decl in the current scope stack.
18599   New->setAccess(TheEnumDecl->getAccess());
18600   PushOnScopeChains(New, S);
18601 
18602   ActOnDocumentableDecl(New);
18603 
18604   return New;
18605 }
18606 
18607 // Returns true when the enum initial expression does not trigger the
18608 // duplicate enum warning.  A few common cases are exempted as follows:
18609 // Element2 = Element1
18610 // Element2 = Element1 + 1
18611 // Element2 = Element1 - 1
18612 // Where Element2 and Element1 are from the same enum.
18613 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18614   Expr *InitExpr = ECD->getInitExpr();
18615   if (!InitExpr)
18616     return true;
18617   InitExpr = InitExpr->IgnoreImpCasts();
18618 
18619   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18620     if (!BO->isAdditiveOp())
18621       return true;
18622     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18623     if (!IL)
18624       return true;
18625     if (IL->getValue() != 1)
18626       return true;
18627 
18628     InitExpr = BO->getLHS();
18629   }
18630 
18631   // This checks if the elements are from the same enum.
18632   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18633   if (!DRE)
18634     return true;
18635 
18636   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18637   if (!EnumConstant)
18638     return true;
18639 
18640   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18641       Enum)
18642     return true;
18643 
18644   return false;
18645 }
18646 
18647 // Emits a warning when an element is implicitly set a value that
18648 // a previous element has already been set to.
18649 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18650                                         EnumDecl *Enum, QualType EnumType) {
18651   // Avoid anonymous enums
18652   if (!Enum->getIdentifier())
18653     return;
18654 
18655   // Only check for small enums.
18656   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18657     return;
18658 
18659   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18660     return;
18661 
18662   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18663   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18664 
18665   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18666 
18667   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18668   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18669 
18670   // Use int64_t as a key to avoid needing special handling for map keys.
18671   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18672     llvm::APSInt Val = D->getInitVal();
18673     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18674   };
18675 
18676   DuplicatesVector DupVector;
18677   ValueToVectorMap EnumMap;
18678 
18679   // Populate the EnumMap with all values represented by enum constants without
18680   // an initializer.
18681   for (auto *Element : Elements) {
18682     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18683 
18684     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18685     // this constant.  Skip this enum since it may be ill-formed.
18686     if (!ECD) {
18687       return;
18688     }
18689 
18690     // Constants with initalizers are handled in the next loop.
18691     if (ECD->getInitExpr())
18692       continue;
18693 
18694     // Duplicate values are handled in the next loop.
18695     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18696   }
18697 
18698   if (EnumMap.size() == 0)
18699     return;
18700 
18701   // Create vectors for any values that has duplicates.
18702   for (auto *Element : Elements) {
18703     // The last loop returned if any constant was null.
18704     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18705     if (!ValidDuplicateEnum(ECD, Enum))
18706       continue;
18707 
18708     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18709     if (Iter == EnumMap.end())
18710       continue;
18711 
18712     DeclOrVector& Entry = Iter->second;
18713     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18714       // Ensure constants are different.
18715       if (D == ECD)
18716         continue;
18717 
18718       // Create new vector and push values onto it.
18719       auto Vec = std::make_unique<ECDVector>();
18720       Vec->push_back(D);
18721       Vec->push_back(ECD);
18722 
18723       // Update entry to point to the duplicates vector.
18724       Entry = Vec.get();
18725 
18726       // Store the vector somewhere we can consult later for quick emission of
18727       // diagnostics.
18728       DupVector.emplace_back(std::move(Vec));
18729       continue;
18730     }
18731 
18732     ECDVector *Vec = Entry.get<ECDVector*>();
18733     // Make sure constants are not added more than once.
18734     if (*Vec->begin() == ECD)
18735       continue;
18736 
18737     Vec->push_back(ECD);
18738   }
18739 
18740   // Emit diagnostics.
18741   for (const auto &Vec : DupVector) {
18742     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18743 
18744     // Emit warning for one enum constant.
18745     auto *FirstECD = Vec->front();
18746     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18747       << FirstECD << toString(FirstECD->getInitVal(), 10)
18748       << FirstECD->getSourceRange();
18749 
18750     // Emit one note for each of the remaining enum constants with
18751     // the same value.
18752     for (auto *ECD : llvm::drop_begin(*Vec))
18753       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18754         << ECD << toString(ECD->getInitVal(), 10)
18755         << ECD->getSourceRange();
18756   }
18757 }
18758 
18759 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18760                              bool AllowMask) const {
18761   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18762   assert(ED->isCompleteDefinition() && "expected enum definition");
18763 
18764   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18765   llvm::APInt &FlagBits = R.first->second;
18766 
18767   if (R.second) {
18768     for (auto *E : ED->enumerators()) {
18769       const auto &EVal = E->getInitVal();
18770       // Only single-bit enumerators introduce new flag values.
18771       if (EVal.isPowerOf2())
18772         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18773     }
18774   }
18775 
18776   // A value is in a flag enum if either its bits are a subset of the enum's
18777   // flag bits (the first condition) or we are allowing masks and the same is
18778   // true of its complement (the second condition). When masks are allowed, we
18779   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18780   //
18781   // While it's true that any value could be used as a mask, the assumption is
18782   // that a mask will have all of the insignificant bits set. Anything else is
18783   // likely a logic error.
18784   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18785   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18786 }
18787 
18788 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18789                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18790                          const ParsedAttributesView &Attrs) {
18791   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18792   QualType EnumType = Context.getTypeDeclType(Enum);
18793 
18794   ProcessDeclAttributeList(S, Enum, Attrs);
18795 
18796   if (Enum->isDependentType()) {
18797     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18798       EnumConstantDecl *ECD =
18799         cast_or_null<EnumConstantDecl>(Elements[i]);
18800       if (!ECD) continue;
18801 
18802       ECD->setType(EnumType);
18803     }
18804 
18805     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18806     return;
18807   }
18808 
18809   // TODO: If the result value doesn't fit in an int, it must be a long or long
18810   // long value.  ISO C does not support this, but GCC does as an extension,
18811   // emit a warning.
18812   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18813   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18814   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18815 
18816   // Verify that all the values are okay, compute the size of the values, and
18817   // reverse the list.
18818   unsigned NumNegativeBits = 0;
18819   unsigned NumPositiveBits = 0;
18820 
18821   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18822     EnumConstantDecl *ECD =
18823       cast_or_null<EnumConstantDecl>(Elements[i]);
18824     if (!ECD) continue;  // Already issued a diagnostic.
18825 
18826     const llvm::APSInt &InitVal = ECD->getInitVal();
18827 
18828     // Keep track of the size of positive and negative values.
18829     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18830       NumPositiveBits = std::max(NumPositiveBits,
18831                                  (unsigned)InitVal.getActiveBits());
18832     else
18833       NumNegativeBits = std::max(NumNegativeBits,
18834                                  (unsigned)InitVal.getMinSignedBits());
18835   }
18836 
18837   // Figure out the type that should be used for this enum.
18838   QualType BestType;
18839   unsigned BestWidth;
18840 
18841   // C++0x N3000 [conv.prom]p3:
18842   //   An rvalue of an unscoped enumeration type whose underlying
18843   //   type is not fixed can be converted to an rvalue of the first
18844   //   of the following types that can represent all the values of
18845   //   the enumeration: int, unsigned int, long int, unsigned long
18846   //   int, long long int, or unsigned long long int.
18847   // C99 6.4.4.3p2:
18848   //   An identifier declared as an enumeration constant has type int.
18849   // The C99 rule is modified by a gcc extension
18850   QualType BestPromotionType;
18851 
18852   bool Packed = Enum->hasAttr<PackedAttr>();
18853   // -fshort-enums is the equivalent to specifying the packed attribute on all
18854   // enum definitions.
18855   if (LangOpts.ShortEnums)
18856     Packed = true;
18857 
18858   // If the enum already has a type because it is fixed or dictated by the
18859   // target, promote that type instead of analyzing the enumerators.
18860   if (Enum->isComplete()) {
18861     BestType = Enum->getIntegerType();
18862     if (BestType->isPromotableIntegerType())
18863       BestPromotionType = Context.getPromotedIntegerType(BestType);
18864     else
18865       BestPromotionType = BestType;
18866 
18867     BestWidth = Context.getIntWidth(BestType);
18868   }
18869   else if (NumNegativeBits) {
18870     // If there is a negative value, figure out the smallest integer type (of
18871     // int/long/longlong) that fits.
18872     // If it's packed, check also if it fits a char or a short.
18873     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18874       BestType = Context.SignedCharTy;
18875       BestWidth = CharWidth;
18876     } else if (Packed && NumNegativeBits <= ShortWidth &&
18877                NumPositiveBits < ShortWidth) {
18878       BestType = Context.ShortTy;
18879       BestWidth = ShortWidth;
18880     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18881       BestType = Context.IntTy;
18882       BestWidth = IntWidth;
18883     } else {
18884       BestWidth = Context.getTargetInfo().getLongWidth();
18885 
18886       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18887         BestType = Context.LongTy;
18888       } else {
18889         BestWidth = Context.getTargetInfo().getLongLongWidth();
18890 
18891         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18892           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18893         BestType = Context.LongLongTy;
18894       }
18895     }
18896     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18897   } else {
18898     // If there is no negative value, figure out the smallest type that fits
18899     // all of the enumerator values.
18900     // If it's packed, check also if it fits a char or a short.
18901     if (Packed && NumPositiveBits <= CharWidth) {
18902       BestType = Context.UnsignedCharTy;
18903       BestPromotionType = Context.IntTy;
18904       BestWidth = CharWidth;
18905     } else if (Packed && NumPositiveBits <= ShortWidth) {
18906       BestType = Context.UnsignedShortTy;
18907       BestPromotionType = Context.IntTy;
18908       BestWidth = ShortWidth;
18909     } else if (NumPositiveBits <= IntWidth) {
18910       BestType = Context.UnsignedIntTy;
18911       BestWidth = IntWidth;
18912       BestPromotionType
18913         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18914                            ? Context.UnsignedIntTy : Context.IntTy;
18915     } else if (NumPositiveBits <=
18916                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18917       BestType = Context.UnsignedLongTy;
18918       BestPromotionType
18919         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18920                            ? Context.UnsignedLongTy : Context.LongTy;
18921     } else {
18922       BestWidth = Context.getTargetInfo().getLongLongWidth();
18923       assert(NumPositiveBits <= BestWidth &&
18924              "How could an initializer get larger than ULL?");
18925       BestType = Context.UnsignedLongLongTy;
18926       BestPromotionType
18927         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18928                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18929     }
18930   }
18931 
18932   // Loop over all of the enumerator constants, changing their types to match
18933   // the type of the enum if needed.
18934   for (auto *D : Elements) {
18935     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18936     if (!ECD) continue;  // Already issued a diagnostic.
18937 
18938     // Standard C says the enumerators have int type, but we allow, as an
18939     // extension, the enumerators to be larger than int size.  If each
18940     // enumerator value fits in an int, type it as an int, otherwise type it the
18941     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18942     // that X has type 'int', not 'unsigned'.
18943 
18944     // Determine whether the value fits into an int.
18945     llvm::APSInt InitVal = ECD->getInitVal();
18946 
18947     // If it fits into an integer type, force it.  Otherwise force it to match
18948     // the enum decl type.
18949     QualType NewTy;
18950     unsigned NewWidth;
18951     bool NewSign;
18952     if (!getLangOpts().CPlusPlus &&
18953         !Enum->isFixed() &&
18954         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18955       NewTy = Context.IntTy;
18956       NewWidth = IntWidth;
18957       NewSign = true;
18958     } else if (ECD->getType() == BestType) {
18959       // Already the right type!
18960       if (getLangOpts().CPlusPlus)
18961         // C++ [dcl.enum]p4: Following the closing brace of an
18962         // enum-specifier, each enumerator has the type of its
18963         // enumeration.
18964         ECD->setType(EnumType);
18965       continue;
18966     } else {
18967       NewTy = BestType;
18968       NewWidth = BestWidth;
18969       NewSign = BestType->isSignedIntegerOrEnumerationType();
18970     }
18971 
18972     // Adjust the APSInt value.
18973     InitVal = InitVal.extOrTrunc(NewWidth);
18974     InitVal.setIsSigned(NewSign);
18975     ECD->setInitVal(InitVal);
18976 
18977     // Adjust the Expr initializer and type.
18978     if (ECD->getInitExpr() &&
18979         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18980       ECD->setInitExpr(ImplicitCastExpr::Create(
18981           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18982           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18983     if (getLangOpts().CPlusPlus)
18984       // C++ [dcl.enum]p4: Following the closing brace of an
18985       // enum-specifier, each enumerator has the type of its
18986       // enumeration.
18987       ECD->setType(EnumType);
18988     else
18989       ECD->setType(NewTy);
18990   }
18991 
18992   Enum->completeDefinition(BestType, BestPromotionType,
18993                            NumPositiveBits, NumNegativeBits);
18994 
18995   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18996 
18997   if (Enum->isClosedFlag()) {
18998     for (Decl *D : Elements) {
18999       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19000       if (!ECD) continue;  // Already issued a diagnostic.
19001 
19002       llvm::APSInt InitVal = ECD->getInitVal();
19003       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19004           !IsValueInFlagEnum(Enum, InitVal, true))
19005         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19006           << ECD << Enum;
19007     }
19008   }
19009 
19010   // Now that the enum type is defined, ensure it's not been underaligned.
19011   if (Enum->hasAttrs())
19012     CheckAlignasUnderalignment(Enum);
19013 }
19014 
19015 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19016                                   SourceLocation StartLoc,
19017                                   SourceLocation EndLoc) {
19018   StringLiteral *AsmString = cast<StringLiteral>(expr);
19019 
19020   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19021                                                    AsmString, StartLoc,
19022                                                    EndLoc);
19023   CurContext->addDecl(New);
19024   return New;
19025 }
19026 
19027 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19028                                       IdentifierInfo* AliasName,
19029                                       SourceLocation PragmaLoc,
19030                                       SourceLocation NameLoc,
19031                                       SourceLocation AliasNameLoc) {
19032   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19033                                          LookupOrdinaryName);
19034   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19035                            AttributeCommonInfo::AS_Pragma);
19036   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19037       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19038 
19039   // If a declaration that:
19040   // 1) declares a function or a variable
19041   // 2) has external linkage
19042   // already exists, add a label attribute to it.
19043   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19044     if (isDeclExternC(PrevDecl))
19045       PrevDecl->addAttr(Attr);
19046     else
19047       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19048           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19049   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19050   } else
19051     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19052 }
19053 
19054 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19055                              SourceLocation PragmaLoc,
19056                              SourceLocation NameLoc) {
19057   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19058 
19059   if (PrevDecl) {
19060     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19061   } else {
19062     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19063   }
19064 }
19065 
19066 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19067                                 IdentifierInfo* AliasName,
19068                                 SourceLocation PragmaLoc,
19069                                 SourceLocation NameLoc,
19070                                 SourceLocation AliasNameLoc) {
19071   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19072                                     LookupOrdinaryName);
19073   WeakInfo W = WeakInfo(Name, NameLoc);
19074 
19075   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19076     if (!PrevDecl->hasAttr<AliasAttr>())
19077       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19078         DeclApplyPragmaWeak(TUScope, ND, W);
19079   } else {
19080     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19081   }
19082 }
19083 
19084 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19085   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19086 }
19087 
19088 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19089                                                      bool Final) {
19090   assert(FD && "Expected non-null FunctionDecl");
19091 
19092   // SYCL functions can be template, so we check if they have appropriate
19093   // attribute prior to checking if it is a template.
19094   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19095     return FunctionEmissionStatus::Emitted;
19096 
19097   // Templates are emitted when they're instantiated.
19098   if (FD->isDependentContext())
19099     return FunctionEmissionStatus::TemplateDiscarded;
19100 
19101   // Check whether this function is an externally visible definition.
19102   auto IsEmittedForExternalSymbol = [this, FD]() {
19103     // We have to check the GVA linkage of the function's *definition* -- if we
19104     // only have a declaration, we don't know whether or not the function will
19105     // be emitted, because (say) the definition could include "inline".
19106     FunctionDecl *Def = FD->getDefinition();
19107 
19108     return Def && !isDiscardableGVALinkage(
19109                       getASTContext().GetGVALinkageForFunction(Def));
19110   };
19111 
19112   if (LangOpts.OpenMPIsDevice) {
19113     // In OpenMP device mode we will not emit host only functions, or functions
19114     // we don't need due to their linkage.
19115     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19116         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19117     // DevTy may be changed later by
19118     //  #pragma omp declare target to(*) device_type(*).
19119     // Therefore DevTy having no value does not imply host. The emission status
19120     // will be checked again at the end of compilation unit with Final = true.
19121     if (DevTy)
19122       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19123         return FunctionEmissionStatus::OMPDiscarded;
19124     // If we have an explicit value for the device type, or we are in a target
19125     // declare context, we need to emit all extern and used symbols.
19126     if (isInOpenMPDeclareTargetContext() || DevTy)
19127       if (IsEmittedForExternalSymbol())
19128         return FunctionEmissionStatus::Emitted;
19129     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19130     // we'll omit it.
19131     if (Final)
19132       return FunctionEmissionStatus::OMPDiscarded;
19133   } else if (LangOpts.OpenMP > 45) {
19134     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19135     // function. In 5.0, no_host was introduced which might cause a function to
19136     // be ommitted.
19137     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19138         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19139     if (DevTy)
19140       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19141         return FunctionEmissionStatus::OMPDiscarded;
19142   }
19143 
19144   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19145     return FunctionEmissionStatus::Emitted;
19146 
19147   if (LangOpts.CUDA) {
19148     // When compiling for device, host functions are never emitted.  Similarly,
19149     // when compiling for host, device and global functions are never emitted.
19150     // (Technically, we do emit a host-side stub for global functions, but this
19151     // doesn't count for our purposes here.)
19152     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19153     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19154       return FunctionEmissionStatus::CUDADiscarded;
19155     if (!LangOpts.CUDAIsDevice &&
19156         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19157       return FunctionEmissionStatus::CUDADiscarded;
19158 
19159     if (IsEmittedForExternalSymbol())
19160       return FunctionEmissionStatus::Emitted;
19161   }
19162 
19163   // Otherwise, the function is known-emitted if it's in our set of
19164   // known-emitted functions.
19165   return FunctionEmissionStatus::Unknown;
19166 }
19167 
19168 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19169   // Host-side references to a __global__ function refer to the stub, so the
19170   // function itself is never emitted and therefore should not be marked.
19171   // If we have host fn calls kernel fn calls host+device, the HD function
19172   // does not get instantiated on the host. We model this by omitting at the
19173   // call to the kernel from the callgraph. This ensures that, when compiling
19174   // for host, only HD functions actually called from the host get marked as
19175   // known-emitted.
19176   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19177          IdentifyCUDATarget(Callee) == CFT_Global;
19178 }
19179