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->Kind == Module::PrivateModuleFragment)
1629     NewM = NewM->Parent;
1630   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1631     OldM = OldM->Parent;
1632 
1633   // If we have a decl in a module partition, it is part of the containing
1634   // module (which is the only thing that can be importing it).
1635   if (NewM && OldM &&
1636       (OldM->Kind == Module::ModulePartitionInterface ||
1637        OldM->Kind == Module::ModulePartitionImplementation)) {
1638     return false;
1639   }
1640 
1641   if (NewM == OldM)
1642     return false;
1643 
1644   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1645   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1646   if (NewIsModuleInterface || OldIsModuleInterface) {
1647     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1648     //   if a declaration of D [...] appears in the purview of a module, all
1649     //   other such declarations shall appear in the purview of the same module
1650     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1651       << New
1652       << NewIsModuleInterface
1653       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1654       << OldIsModuleInterface
1655       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1656     Diag(Old->getLocation(), diag::note_previous_declaration);
1657     New->setInvalidDecl();
1658     return true;
1659   }
1660 
1661   return false;
1662 }
1663 
1664 // [module.interface]p6:
1665 // A redeclaration of an entity X is implicitly exported if X was introduced by
1666 // an exported declaration; otherwise it shall not be exported.
1667 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1668   // [module.interface]p1:
1669   // An export-declaration shall inhabit a namespace scope.
1670   //
1671   // So it is meaningless to talk about redeclaration which is not at namespace
1672   // scope.
1673   if (!New->getLexicalDeclContext()
1674            ->getNonTransparentContext()
1675            ->isFileContext() ||
1676       !Old->getLexicalDeclContext()
1677            ->getNonTransparentContext()
1678            ->isFileContext())
1679     return false;
1680 
1681   bool IsNewExported = New->isInExportDeclContext();
1682   bool IsOldExported = Old->isInExportDeclContext();
1683 
1684   // It should be irrevelant if both of them are not exported.
1685   if (!IsNewExported && !IsOldExported)
1686     return false;
1687 
1688   if (IsOldExported)
1689     return false;
1690 
1691   assert(IsNewExported);
1692 
1693   auto Lk = Old->getFormalLinkage();
1694   int S = 0;
1695   if (Lk == Linkage::InternalLinkage)
1696     S = 1;
1697   else if (Lk == Linkage::ModuleLinkage)
1698     S = 2;
1699   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1700   Diag(Old->getLocation(), diag::note_previous_declaration);
1701   return true;
1702 }
1703 
1704 // A wrapper function for checking the semantic restrictions of
1705 // a redeclaration within a module.
1706 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1707   if (CheckRedeclarationModuleOwnership(New, Old))
1708     return true;
1709 
1710   if (CheckRedeclarationExported(New, Old))
1711     return true;
1712 
1713   return false;
1714 }
1715 
1716 static bool isUsingDecl(NamedDecl *D) {
1717   return isa<UsingShadowDecl>(D) ||
1718          isa<UnresolvedUsingTypenameDecl>(D) ||
1719          isa<UnresolvedUsingValueDecl>(D);
1720 }
1721 
1722 /// Removes using shadow declarations from the lookup results.
1723 static void RemoveUsingDecls(LookupResult &R) {
1724   LookupResult::Filter F = R.makeFilter();
1725   while (F.hasNext())
1726     if (isUsingDecl(F.next()))
1727       F.erase();
1728 
1729   F.done();
1730 }
1731 
1732 /// Check for this common pattern:
1733 /// @code
1734 /// class S {
1735 ///   S(const S&); // DO NOT IMPLEMENT
1736 ///   void operator=(const S&); // DO NOT IMPLEMENT
1737 /// };
1738 /// @endcode
1739 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1740   // FIXME: Should check for private access too but access is set after we get
1741   // the decl here.
1742   if (D->doesThisDeclarationHaveABody())
1743     return false;
1744 
1745   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1746     return CD->isCopyConstructor();
1747   return D->isCopyAssignmentOperator();
1748 }
1749 
1750 // We need this to handle
1751 //
1752 // typedef struct {
1753 //   void *foo() { return 0; }
1754 // } A;
1755 //
1756 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1757 // for example. If 'A', foo will have external linkage. If we have '*A',
1758 // foo will have no linkage. Since we can't know until we get to the end
1759 // of the typedef, this function finds out if D might have non-external linkage.
1760 // Callers should verify at the end of the TU if it D has external linkage or
1761 // not.
1762 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1763   const DeclContext *DC = D->getDeclContext();
1764   while (!DC->isTranslationUnit()) {
1765     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1766       if (!RD->hasNameForLinkage())
1767         return true;
1768     }
1769     DC = DC->getParent();
1770   }
1771 
1772   return !D->isExternallyVisible();
1773 }
1774 
1775 // FIXME: This needs to be refactored; some other isInMainFile users want
1776 // these semantics.
1777 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1778   if (S.TUKind != TU_Complete)
1779     return false;
1780   return S.SourceMgr.isInMainFile(Loc);
1781 }
1782 
1783 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1784   assert(D);
1785 
1786   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1787     return false;
1788 
1789   // Ignore all entities declared within templates, and out-of-line definitions
1790   // of members of class templates.
1791   if (D->getDeclContext()->isDependentContext() ||
1792       D->getLexicalDeclContext()->isDependentContext())
1793     return false;
1794 
1795   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1796     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1797       return false;
1798     // A non-out-of-line declaration of a member specialization was implicitly
1799     // instantiated; it's the out-of-line declaration that we're interested in.
1800     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1801         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1802       return false;
1803 
1804     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1805       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1806         return false;
1807     } else {
1808       // 'static inline' functions are defined in headers; don't warn.
1809       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1810         return false;
1811     }
1812 
1813     if (FD->doesThisDeclarationHaveABody() &&
1814         Context.DeclMustBeEmitted(FD))
1815       return false;
1816   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1817     // Constants and utility variables are defined in headers with internal
1818     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1819     // like "inline".)
1820     if (!isMainFileLoc(*this, VD->getLocation()))
1821       return false;
1822 
1823     if (Context.DeclMustBeEmitted(VD))
1824       return false;
1825 
1826     if (VD->isStaticDataMember() &&
1827         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1828       return false;
1829     if (VD->isStaticDataMember() &&
1830         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1831         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1832       return false;
1833 
1834     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1835       return false;
1836   } else {
1837     return false;
1838   }
1839 
1840   // Only warn for unused decls internal to the translation unit.
1841   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1842   // for inline functions defined in the main source file, for instance.
1843   return mightHaveNonExternalLinkage(D);
1844 }
1845 
1846 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1847   if (!D)
1848     return;
1849 
1850   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1851     const FunctionDecl *First = FD->getFirstDecl();
1852     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1853       return; // First should already be in the vector.
1854   }
1855 
1856   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1857     const VarDecl *First = VD->getFirstDecl();
1858     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1859       return; // First should already be in the vector.
1860   }
1861 
1862   if (ShouldWarnIfUnusedFileScopedDecl(D))
1863     UnusedFileScopedDecls.push_back(D);
1864 }
1865 
1866 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1867   if (D->isInvalidDecl())
1868     return false;
1869 
1870   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1871     // For a decomposition declaration, warn if none of the bindings are
1872     // referenced, instead of if the variable itself is referenced (which
1873     // it is, by the bindings' expressions).
1874     for (auto *BD : DD->bindings())
1875       if (BD->isReferenced())
1876         return false;
1877   } else if (!D->getDeclName()) {
1878     return false;
1879   } else if (D->isReferenced() || D->isUsed()) {
1880     return false;
1881   }
1882 
1883   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1884     return false;
1885 
1886   if (isa<LabelDecl>(D))
1887     return true;
1888 
1889   // Except for labels, we only care about unused decls that are local to
1890   // functions.
1891   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1892   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1893     // For dependent types, the diagnostic is deferred.
1894     WithinFunction =
1895         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1896   if (!WithinFunction)
1897     return false;
1898 
1899   if (isa<TypedefNameDecl>(D))
1900     return true;
1901 
1902   // White-list anything that isn't a local variable.
1903   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1904     return false;
1905 
1906   // Types of valid local variables should be complete, so this should succeed.
1907   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1908 
1909     const Expr *Init = VD->getInit();
1910     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1911       Init = Cleanups->getSubExpr();
1912 
1913     const auto *Ty = VD->getType().getTypePtr();
1914 
1915     // Only look at the outermost level of typedef.
1916     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1917       // Allow anything marked with __attribute__((unused)).
1918       if (TT->getDecl()->hasAttr<UnusedAttr>())
1919         return false;
1920     }
1921 
1922     // Warn for reference variables whose initializtion performs lifetime
1923     // extension.
1924     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1925       if (MTE->getExtendingDecl()) {
1926         Ty = VD->getType().getNonReferenceType().getTypePtr();
1927         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1928       }
1929     }
1930 
1931     // If we failed to complete the type for some reason, or if the type is
1932     // dependent, don't diagnose the variable.
1933     if (Ty->isIncompleteType() || Ty->isDependentType())
1934       return false;
1935 
1936     // Look at the element type to ensure that the warning behaviour is
1937     // consistent for both scalars and arrays.
1938     Ty = Ty->getBaseElementTypeUnsafe();
1939 
1940     if (const TagType *TT = Ty->getAs<TagType>()) {
1941       const TagDecl *Tag = TT->getDecl();
1942       if (Tag->hasAttr<UnusedAttr>())
1943         return false;
1944 
1945       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1946         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1947           return false;
1948 
1949         if (Init) {
1950           const CXXConstructExpr *Construct =
1951             dyn_cast<CXXConstructExpr>(Init);
1952           if (Construct && !Construct->isElidable()) {
1953             CXXConstructorDecl *CD = Construct->getConstructor();
1954             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1955                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1956               return false;
1957           }
1958 
1959           // Suppress the warning if we don't know how this is constructed, and
1960           // it could possibly be non-trivial constructor.
1961           if (Init->isTypeDependent()) {
1962             for (const CXXConstructorDecl *Ctor : RD->ctors())
1963               if (!Ctor->isTrivial())
1964                 return false;
1965           }
1966 
1967           // Suppress the warning if the constructor is unresolved because
1968           // its arguments are dependent.
1969           if (isa<CXXUnresolvedConstructExpr>(Init))
1970             return false;
1971         }
1972       }
1973     }
1974 
1975     // TODO: __attribute__((unused)) templates?
1976   }
1977 
1978   return true;
1979 }
1980 
1981 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1982                                      FixItHint &Hint) {
1983   if (isa<LabelDecl>(D)) {
1984     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1985         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1986         true);
1987     if (AfterColon.isInvalid())
1988       return;
1989     Hint = FixItHint::CreateRemoval(
1990         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1991   }
1992 }
1993 
1994 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1995   if (D->getTypeForDecl()->isDependentType())
1996     return;
1997 
1998   for (auto *TmpD : D->decls()) {
1999     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2000       DiagnoseUnusedDecl(T);
2001     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2002       DiagnoseUnusedNestedTypedefs(R);
2003   }
2004 }
2005 
2006 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2007 /// unless they are marked attr(unused).
2008 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2009   if (!ShouldDiagnoseUnusedDecl(D))
2010     return;
2011 
2012   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2013     // typedefs can be referenced later on, so the diagnostics are emitted
2014     // at end-of-translation-unit.
2015     UnusedLocalTypedefNameCandidates.insert(TD);
2016     return;
2017   }
2018 
2019   FixItHint Hint;
2020   GenerateFixForUnusedDecl(D, Context, Hint);
2021 
2022   unsigned DiagID;
2023   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2024     DiagID = diag::warn_unused_exception_param;
2025   else if (isa<LabelDecl>(D))
2026     DiagID = diag::warn_unused_label;
2027   else
2028     DiagID = diag::warn_unused_variable;
2029 
2030   Diag(D->getLocation(), DiagID) << D << Hint;
2031 }
2032 
2033 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2034   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2035   // it's not really unused.
2036   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2037       VD->hasAttr<CleanupAttr>())
2038     return;
2039 
2040   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2041 
2042   if (Ty->isReferenceType() || Ty->isDependentType())
2043     return;
2044 
2045   if (const TagType *TT = Ty->getAs<TagType>()) {
2046     const TagDecl *Tag = TT->getDecl();
2047     if (Tag->hasAttr<UnusedAttr>())
2048       return;
2049     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2050     // mimic gcc's behavior.
2051     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2052       if (!RD->hasAttr<WarnUnusedAttr>())
2053         return;
2054     }
2055   }
2056 
2057   // Don't warn about __block Objective-C pointer variables, as they might
2058   // be assigned in the block but not used elsewhere for the purpose of lifetime
2059   // extension.
2060   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2061     return;
2062 
2063   // Don't warn about Objective-C pointer variables with precise lifetime
2064   // semantics; they can be used to ensure ARC releases the object at a known
2065   // time, which may mean assignment but no other references.
2066   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2067     return;
2068 
2069   auto iter = RefsMinusAssignments.find(VD);
2070   if (iter == RefsMinusAssignments.end())
2071     return;
2072 
2073   assert(iter->getSecond() >= 0 &&
2074          "Found a negative number of references to a VarDecl");
2075   if (iter->getSecond() != 0)
2076     return;
2077   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2078                                          : diag::warn_unused_but_set_variable;
2079   Diag(VD->getLocation(), DiagID) << VD;
2080 }
2081 
2082 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2083   // Verify that we have no forward references left.  If so, there was a goto
2084   // or address of a label taken, but no definition of it.  Label fwd
2085   // definitions are indicated with a null substmt which is also not a resolved
2086   // MS inline assembly label name.
2087   bool Diagnose = false;
2088   if (L->isMSAsmLabel())
2089     Diagnose = !L->isResolvedMSAsmLabel();
2090   else
2091     Diagnose = L->getStmt() == nullptr;
2092   if (Diagnose)
2093     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2094 }
2095 
2096 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2097   S->mergeNRVOIntoParent();
2098 
2099   if (S->decl_empty()) return;
2100   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2101          "Scope shouldn't contain decls!");
2102 
2103   for (auto *TmpD : S->decls()) {
2104     assert(TmpD && "This decl didn't get pushed??");
2105 
2106     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2107     NamedDecl *D = cast<NamedDecl>(TmpD);
2108 
2109     // Diagnose unused variables in this scope.
2110     if (!S->hasUnrecoverableErrorOccurred()) {
2111       DiagnoseUnusedDecl(D);
2112       if (const auto *RD = dyn_cast<RecordDecl>(D))
2113         DiagnoseUnusedNestedTypedefs(RD);
2114       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2115         DiagnoseUnusedButSetDecl(VD);
2116         RefsMinusAssignments.erase(VD);
2117       }
2118     }
2119 
2120     if (!D->getDeclName()) continue;
2121 
2122     // If this was a forward reference to a label, verify it was defined.
2123     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2124       CheckPoppedLabel(LD, *this);
2125 
2126     // Remove this name from our lexical scope, and warn on it if we haven't
2127     // already.
2128     IdResolver.RemoveDecl(D);
2129     auto ShadowI = ShadowingDecls.find(D);
2130     if (ShadowI != ShadowingDecls.end()) {
2131       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2132         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2133             << D << FD << FD->getParent();
2134         Diag(FD->getLocation(), diag::note_previous_declaration);
2135       }
2136       ShadowingDecls.erase(ShadowI);
2137     }
2138   }
2139 }
2140 
2141 /// Look for an Objective-C class in the translation unit.
2142 ///
2143 /// \param Id The name of the Objective-C class we're looking for. If
2144 /// typo-correction fixes this name, the Id will be updated
2145 /// to the fixed name.
2146 ///
2147 /// \param IdLoc The location of the name in the translation unit.
2148 ///
2149 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2150 /// if there is no class with the given name.
2151 ///
2152 /// \returns The declaration of the named Objective-C class, or NULL if the
2153 /// class could not be found.
2154 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2155                                               SourceLocation IdLoc,
2156                                               bool DoTypoCorrection) {
2157   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2158   // creation from this context.
2159   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2160 
2161   if (!IDecl && DoTypoCorrection) {
2162     // Perform typo correction at the given location, but only if we
2163     // find an Objective-C class name.
2164     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2165     if (TypoCorrection C =
2166             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2167                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2168       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2169       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2170       Id = IDecl->getIdentifier();
2171     }
2172   }
2173   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2174   // This routine must always return a class definition, if any.
2175   if (Def && Def->getDefinition())
2176       Def = Def->getDefinition();
2177   return Def;
2178 }
2179 
2180 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2181 /// from S, where a non-field would be declared. This routine copes
2182 /// with the difference between C and C++ scoping rules in structs and
2183 /// unions. For example, the following code is well-formed in C but
2184 /// ill-formed in C++:
2185 /// @code
2186 /// struct S6 {
2187 ///   enum { BAR } e;
2188 /// };
2189 ///
2190 /// void test_S6() {
2191 ///   struct S6 a;
2192 ///   a.e = BAR;
2193 /// }
2194 /// @endcode
2195 /// For the declaration of BAR, this routine will return a different
2196 /// scope. The scope S will be the scope of the unnamed enumeration
2197 /// within S6. In C++, this routine will return the scope associated
2198 /// with S6, because the enumeration's scope is a transparent
2199 /// context but structures can contain non-field names. In C, this
2200 /// routine will return the translation unit scope, since the
2201 /// enumeration's scope is a transparent context and structures cannot
2202 /// contain non-field names.
2203 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2204   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2205          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2206          (S->isClassScope() && !getLangOpts().CPlusPlus))
2207     S = S->getParent();
2208   return S;
2209 }
2210 
2211 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2212                                ASTContext::GetBuiltinTypeError Error) {
2213   switch (Error) {
2214   case ASTContext::GE_None:
2215     return "";
2216   case ASTContext::GE_Missing_type:
2217     return BuiltinInfo.getHeaderName(ID);
2218   case ASTContext::GE_Missing_stdio:
2219     return "stdio.h";
2220   case ASTContext::GE_Missing_setjmp:
2221     return "setjmp.h";
2222   case ASTContext::GE_Missing_ucontext:
2223     return "ucontext.h";
2224   }
2225   llvm_unreachable("unhandled error kind");
2226 }
2227 
2228 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2229                                   unsigned ID, SourceLocation Loc) {
2230   DeclContext *Parent = Context.getTranslationUnitDecl();
2231 
2232   if (getLangOpts().CPlusPlus) {
2233     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2234         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2235     CLinkageDecl->setImplicit();
2236     Parent->addDecl(CLinkageDecl);
2237     Parent = CLinkageDecl;
2238   }
2239 
2240   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2241                                            /*TInfo=*/nullptr, SC_Extern,
2242                                            getCurFPFeatures().isFPConstrained(),
2243                                            false, Type->isFunctionProtoType());
2244   New->setImplicit();
2245   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2246 
2247   // Create Decl objects for each parameter, adding them to the
2248   // FunctionDecl.
2249   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2250     SmallVector<ParmVarDecl *, 16> Params;
2251     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2252       ParmVarDecl *parm = ParmVarDecl::Create(
2253           Context, New, SourceLocation(), SourceLocation(), nullptr,
2254           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2255       parm->setScopeInfo(0, i);
2256       Params.push_back(parm);
2257     }
2258     New->setParams(Params);
2259   }
2260 
2261   AddKnownFunctionAttributes(New);
2262   return New;
2263 }
2264 
2265 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2266 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2267 /// if we're creating this built-in in anticipation of redeclaring the
2268 /// built-in.
2269 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2270                                      Scope *S, bool ForRedeclaration,
2271                                      SourceLocation Loc) {
2272   LookupNecessaryTypesForBuiltin(S, ID);
2273 
2274   ASTContext::GetBuiltinTypeError Error;
2275   QualType R = Context.GetBuiltinType(ID, Error);
2276   if (Error) {
2277     if (!ForRedeclaration)
2278       return nullptr;
2279 
2280     // If we have a builtin without an associated type we should not emit a
2281     // warning when we were not able to find a type for it.
2282     if (Error == ASTContext::GE_Missing_type ||
2283         Context.BuiltinInfo.allowTypeMismatch(ID))
2284       return nullptr;
2285 
2286     // If we could not find a type for setjmp it is because the jmp_buf type was
2287     // not defined prior to the setjmp declaration.
2288     if (Error == ASTContext::GE_Missing_setjmp) {
2289       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2290           << Context.BuiltinInfo.getName(ID);
2291       return nullptr;
2292     }
2293 
2294     // Generally, we emit a warning that the declaration requires the
2295     // appropriate header.
2296     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2297         << getHeaderName(Context.BuiltinInfo, ID, Error)
2298         << Context.BuiltinInfo.getName(ID);
2299     return nullptr;
2300   }
2301 
2302   if (!ForRedeclaration &&
2303       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2304        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2305     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2306                            : diag::ext_implicit_lib_function_decl)
2307         << Context.BuiltinInfo.getName(ID) << R;
2308     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2309       Diag(Loc, diag::note_include_header_or_declare)
2310           << Header << Context.BuiltinInfo.getName(ID);
2311   }
2312 
2313   if (R.isNull())
2314     return nullptr;
2315 
2316   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2317   RegisterLocallyScopedExternCDecl(New, S);
2318 
2319   // TUScope is the translation-unit scope to insert this function into.
2320   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2321   // relate Scopes to DeclContexts, and probably eliminate CurContext
2322   // entirely, but we're not there yet.
2323   DeclContext *SavedContext = CurContext;
2324   CurContext = New->getDeclContext();
2325   PushOnScopeChains(New, TUScope);
2326   CurContext = SavedContext;
2327   return New;
2328 }
2329 
2330 /// Typedef declarations don't have linkage, but they still denote the same
2331 /// entity if their types are the same.
2332 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2333 /// isSameEntity.
2334 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2335                                                      TypedefNameDecl *Decl,
2336                                                      LookupResult &Previous) {
2337   // This is only interesting when modules are enabled.
2338   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2339     return;
2340 
2341   // Empty sets are uninteresting.
2342   if (Previous.empty())
2343     return;
2344 
2345   LookupResult::Filter Filter = Previous.makeFilter();
2346   while (Filter.hasNext()) {
2347     NamedDecl *Old = Filter.next();
2348 
2349     // Non-hidden declarations are never ignored.
2350     if (S.isVisible(Old))
2351       continue;
2352 
2353     // Declarations of the same entity are not ignored, even if they have
2354     // different linkages.
2355     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2356       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2357                                 Decl->getUnderlyingType()))
2358         continue;
2359 
2360       // If both declarations give a tag declaration a typedef name for linkage
2361       // purposes, then they declare the same entity.
2362       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2363           Decl->getAnonDeclWithTypedefName())
2364         continue;
2365     }
2366 
2367     Filter.erase();
2368   }
2369 
2370   Filter.done();
2371 }
2372 
2373 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2374   QualType OldType;
2375   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2376     OldType = OldTypedef->getUnderlyingType();
2377   else
2378     OldType = Context.getTypeDeclType(Old);
2379   QualType NewType = New->getUnderlyingType();
2380 
2381   if (NewType->isVariablyModifiedType()) {
2382     // Must not redefine a typedef with a variably-modified type.
2383     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2384     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2385       << Kind << NewType;
2386     if (Old->getLocation().isValid())
2387       notePreviousDefinition(Old, New->getLocation());
2388     New->setInvalidDecl();
2389     return true;
2390   }
2391 
2392   if (OldType != NewType &&
2393       !OldType->isDependentType() &&
2394       !NewType->isDependentType() &&
2395       !Context.hasSameType(OldType, NewType)) {
2396     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2397     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2398       << Kind << NewType << OldType;
2399     if (Old->getLocation().isValid())
2400       notePreviousDefinition(Old, New->getLocation());
2401     New->setInvalidDecl();
2402     return true;
2403   }
2404   return false;
2405 }
2406 
2407 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2408 /// same name and scope as a previous declaration 'Old'.  Figure out
2409 /// how to resolve this situation, merging decls or emitting
2410 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2411 ///
2412 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2413                                 LookupResult &OldDecls) {
2414   // If the new decl is known invalid already, don't bother doing any
2415   // merging checks.
2416   if (New->isInvalidDecl()) return;
2417 
2418   // Allow multiple definitions for ObjC built-in typedefs.
2419   // FIXME: Verify the underlying types are equivalent!
2420   if (getLangOpts().ObjC) {
2421     const IdentifierInfo *TypeID = New->getIdentifier();
2422     switch (TypeID->getLength()) {
2423     default: break;
2424     case 2:
2425       {
2426         if (!TypeID->isStr("id"))
2427           break;
2428         QualType T = New->getUnderlyingType();
2429         if (!T->isPointerType())
2430           break;
2431         if (!T->isVoidPointerType()) {
2432           QualType PT = T->castAs<PointerType>()->getPointeeType();
2433           if (!PT->isStructureType())
2434             break;
2435         }
2436         Context.setObjCIdRedefinitionType(T);
2437         // Install the built-in type for 'id', ignoring the current definition.
2438         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2439         return;
2440       }
2441     case 5:
2442       if (!TypeID->isStr("Class"))
2443         break;
2444       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2445       // Install the built-in type for 'Class', ignoring the current definition.
2446       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2447       return;
2448     case 3:
2449       if (!TypeID->isStr("SEL"))
2450         break;
2451       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2452       // Install the built-in type for 'SEL', ignoring the current definition.
2453       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2454       return;
2455     }
2456     // Fall through - the typedef name was not a builtin type.
2457   }
2458 
2459   // Verify the old decl was also a type.
2460   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2461   if (!Old) {
2462     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2463       << New->getDeclName();
2464 
2465     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2466     if (OldD->getLocation().isValid())
2467       notePreviousDefinition(OldD, New->getLocation());
2468 
2469     return New->setInvalidDecl();
2470   }
2471 
2472   // If the old declaration is invalid, just give up here.
2473   if (Old->isInvalidDecl())
2474     return New->setInvalidDecl();
2475 
2476   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2477     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2478     auto *NewTag = New->getAnonDeclWithTypedefName();
2479     NamedDecl *Hidden = nullptr;
2480     if (OldTag && NewTag &&
2481         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2482         !hasVisibleDefinition(OldTag, &Hidden)) {
2483       // There is a definition of this tag, but it is not visible. Use it
2484       // instead of our tag.
2485       New->setTypeForDecl(OldTD->getTypeForDecl());
2486       if (OldTD->isModed())
2487         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2488                                     OldTD->getUnderlyingType());
2489       else
2490         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2491 
2492       // Make the old tag definition visible.
2493       makeMergedDefinitionVisible(Hidden);
2494 
2495       // If this was an unscoped enumeration, yank all of its enumerators
2496       // out of the scope.
2497       if (isa<EnumDecl>(NewTag)) {
2498         Scope *EnumScope = getNonFieldDeclScope(S);
2499         for (auto *D : NewTag->decls()) {
2500           auto *ED = cast<EnumConstantDecl>(D);
2501           assert(EnumScope->isDeclScope(ED));
2502           EnumScope->RemoveDecl(ED);
2503           IdResolver.RemoveDecl(ED);
2504           ED->getLexicalDeclContext()->removeDecl(ED);
2505         }
2506       }
2507     }
2508   }
2509 
2510   // If the typedef types are not identical, reject them in all languages and
2511   // with any extensions enabled.
2512   if (isIncompatibleTypedef(Old, New))
2513     return;
2514 
2515   // The types match.  Link up the redeclaration chain and merge attributes if
2516   // the old declaration was a typedef.
2517   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2518     New->setPreviousDecl(Typedef);
2519     mergeDeclAttributes(New, Old);
2520   }
2521 
2522   if (getLangOpts().MicrosoftExt)
2523     return;
2524 
2525   if (getLangOpts().CPlusPlus) {
2526     // C++ [dcl.typedef]p2:
2527     //   In a given non-class scope, a typedef specifier can be used to
2528     //   redefine the name of any type declared in that scope to refer
2529     //   to the type to which it already refers.
2530     if (!isa<CXXRecordDecl>(CurContext))
2531       return;
2532 
2533     // C++0x [dcl.typedef]p4:
2534     //   In a given class scope, a typedef specifier can be used to redefine
2535     //   any class-name declared in that scope that is not also a typedef-name
2536     //   to refer to the type to which it already refers.
2537     //
2538     // This wording came in via DR424, which was a correction to the
2539     // wording in DR56, which accidentally banned code like:
2540     //
2541     //   struct S {
2542     //     typedef struct A { } A;
2543     //   };
2544     //
2545     // in the C++03 standard. We implement the C++0x semantics, which
2546     // allow the above but disallow
2547     //
2548     //   struct S {
2549     //     typedef int I;
2550     //     typedef int I;
2551     //   };
2552     //
2553     // since that was the intent of DR56.
2554     if (!isa<TypedefNameDecl>(Old))
2555       return;
2556 
2557     Diag(New->getLocation(), diag::err_redefinition)
2558       << New->getDeclName();
2559     notePreviousDefinition(Old, New->getLocation());
2560     return New->setInvalidDecl();
2561   }
2562 
2563   // Modules always permit redefinition of typedefs, as does C11.
2564   if (getLangOpts().Modules || getLangOpts().C11)
2565     return;
2566 
2567   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2568   // is normally mapped to an error, but can be controlled with
2569   // -Wtypedef-redefinition.  If either the original or the redefinition is
2570   // in a system header, don't emit this for compatibility with GCC.
2571   if (getDiagnostics().getSuppressSystemWarnings() &&
2572       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2573       (Old->isImplicit() ||
2574        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2575        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2576     return;
2577 
2578   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2579     << New->getDeclName();
2580   notePreviousDefinition(Old, New->getLocation());
2581 }
2582 
2583 /// DeclhasAttr - returns true if decl Declaration already has the target
2584 /// attribute.
2585 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2586   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2587   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2588   for (const auto *i : D->attrs())
2589     if (i->getKind() == A->getKind()) {
2590       if (Ann) {
2591         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2592           return true;
2593         continue;
2594       }
2595       // FIXME: Don't hardcode this check
2596       if (OA && isa<OwnershipAttr>(i))
2597         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2598       return true;
2599     }
2600 
2601   return false;
2602 }
2603 
2604 static bool isAttributeTargetADefinition(Decl *D) {
2605   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2606     return VD->isThisDeclarationADefinition();
2607   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2608     return TD->isCompleteDefinition() || TD->isBeingDefined();
2609   return true;
2610 }
2611 
2612 /// Merge alignment attributes from \p Old to \p New, taking into account the
2613 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2614 ///
2615 /// \return \c true if any attributes were added to \p New.
2616 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2617   // Look for alignas attributes on Old, and pick out whichever attribute
2618   // specifies the strictest alignment requirement.
2619   AlignedAttr *OldAlignasAttr = nullptr;
2620   AlignedAttr *OldStrictestAlignAttr = nullptr;
2621   unsigned OldAlign = 0;
2622   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2623     // FIXME: We have no way of representing inherited dependent alignments
2624     // in a case like:
2625     //   template<int A, int B> struct alignas(A) X;
2626     //   template<int A, int B> struct alignas(B) X {};
2627     // For now, we just ignore any alignas attributes which are not on the
2628     // definition in such a case.
2629     if (I->isAlignmentDependent())
2630       return false;
2631 
2632     if (I->isAlignas())
2633       OldAlignasAttr = I;
2634 
2635     unsigned Align = I->getAlignment(S.Context);
2636     if (Align > OldAlign) {
2637       OldAlign = Align;
2638       OldStrictestAlignAttr = I;
2639     }
2640   }
2641 
2642   // Look for alignas attributes on New.
2643   AlignedAttr *NewAlignasAttr = nullptr;
2644   unsigned NewAlign = 0;
2645   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2646     if (I->isAlignmentDependent())
2647       return false;
2648 
2649     if (I->isAlignas())
2650       NewAlignasAttr = I;
2651 
2652     unsigned Align = I->getAlignment(S.Context);
2653     if (Align > NewAlign)
2654       NewAlign = Align;
2655   }
2656 
2657   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2658     // Both declarations have 'alignas' attributes. We require them to match.
2659     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2660     // fall short. (If two declarations both have alignas, they must both match
2661     // every definition, and so must match each other if there is a definition.)
2662 
2663     // If either declaration only contains 'alignas(0)' specifiers, then it
2664     // specifies the natural alignment for the type.
2665     if (OldAlign == 0 || NewAlign == 0) {
2666       QualType Ty;
2667       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2668         Ty = VD->getType();
2669       else
2670         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2671 
2672       if (OldAlign == 0)
2673         OldAlign = S.Context.getTypeAlign(Ty);
2674       if (NewAlign == 0)
2675         NewAlign = S.Context.getTypeAlign(Ty);
2676     }
2677 
2678     if (OldAlign != NewAlign) {
2679       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2680         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2681         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2682       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2683     }
2684   }
2685 
2686   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2687     // C++11 [dcl.align]p6:
2688     //   if any declaration of an entity has an alignment-specifier,
2689     //   every defining declaration of that entity shall specify an
2690     //   equivalent alignment.
2691     // C11 6.7.5/7:
2692     //   If the definition of an object does not have an alignment
2693     //   specifier, any other declaration of that object shall also
2694     //   have no alignment specifier.
2695     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2696       << OldAlignasAttr;
2697     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2698       << OldAlignasAttr;
2699   }
2700 
2701   bool AnyAdded = false;
2702 
2703   // Ensure we have an attribute representing the strictest alignment.
2704   if (OldAlign > NewAlign) {
2705     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2706     Clone->setInherited(true);
2707     New->addAttr(Clone);
2708     AnyAdded = true;
2709   }
2710 
2711   // Ensure we have an alignas attribute if the old declaration had one.
2712   if (OldAlignasAttr && !NewAlignasAttr &&
2713       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2714     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2715     Clone->setInherited(true);
2716     New->addAttr(Clone);
2717     AnyAdded = true;
2718   }
2719 
2720   return AnyAdded;
2721 }
2722 
2723 #define WANT_DECL_MERGE_LOGIC
2724 #include "clang/Sema/AttrParsedAttrImpl.inc"
2725 #undef WANT_DECL_MERGE_LOGIC
2726 
2727 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2728                                const InheritableAttr *Attr,
2729                                Sema::AvailabilityMergeKind AMK) {
2730   // Diagnose any mutual exclusions between the attribute that we want to add
2731   // and attributes that already exist on the declaration.
2732   if (!DiagnoseMutualExclusions(S, D, Attr))
2733     return false;
2734 
2735   // This function copies an attribute Attr from a previous declaration to the
2736   // new declaration D if the new declaration doesn't itself have that attribute
2737   // yet or if that attribute allows duplicates.
2738   // If you're adding a new attribute that requires logic different from
2739   // "use explicit attribute on decl if present, else use attribute from
2740   // previous decl", for example if the attribute needs to be consistent
2741   // between redeclarations, you need to call a custom merge function here.
2742   InheritableAttr *NewAttr = nullptr;
2743   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2744     NewAttr = S.mergeAvailabilityAttr(
2745         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2746         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2747         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2748         AA->getPriority());
2749   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2750     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2751   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2752     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2753   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2754     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2755   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2756     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2757   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2758     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2759   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2760     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2761                                 FA->getFirstArg());
2762   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2763     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2764   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2765     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2766   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2767     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2768                                        IA->getInheritanceModel());
2769   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2770     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2771                                       &S.Context.Idents.get(AA->getSpelling()));
2772   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2773            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2774             isa<CUDAGlobalAttr>(Attr))) {
2775     // CUDA target attributes are part of function signature for
2776     // overloading purposes and must not be merged.
2777     return false;
2778   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2779     NewAttr = S.mergeMinSizeAttr(D, *MA);
2780   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2781     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2782   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2783     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2784   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2785     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2786   else if (isa<AlignedAttr>(Attr))
2787     // AlignedAttrs are handled separately, because we need to handle all
2788     // such attributes on a declaration at the same time.
2789     NewAttr = nullptr;
2790   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2791            (AMK == Sema::AMK_Override ||
2792             AMK == Sema::AMK_ProtocolImplementation ||
2793             AMK == Sema::AMK_OptionalProtocolImplementation))
2794     NewAttr = nullptr;
2795   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2796     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2797   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2798     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2799   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2800     NewAttr = S.mergeImportNameAttr(D, *INA);
2801   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2802     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2803   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2804     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2805   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2806     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2807   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2808     NewAttr =
2809         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2810   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2811     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2812   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2813     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2814 
2815   if (NewAttr) {
2816     NewAttr->setInherited(true);
2817     D->addAttr(NewAttr);
2818     if (isa<MSInheritanceAttr>(NewAttr))
2819       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2820     return true;
2821   }
2822 
2823   return false;
2824 }
2825 
2826 static const NamedDecl *getDefinition(const Decl *D) {
2827   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2828     return TD->getDefinition();
2829   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2830     const VarDecl *Def = VD->getDefinition();
2831     if (Def)
2832       return Def;
2833     return VD->getActingDefinition();
2834   }
2835   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2836     const FunctionDecl *Def = nullptr;
2837     if (FD->isDefined(Def, true))
2838       return Def;
2839   }
2840   return nullptr;
2841 }
2842 
2843 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2844   for (const auto *Attribute : D->attrs())
2845     if (Attribute->getKind() == Kind)
2846       return true;
2847   return false;
2848 }
2849 
2850 /// checkNewAttributesAfterDef - If we already have a definition, check that
2851 /// there are no new attributes in this declaration.
2852 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2853   if (!New->hasAttrs())
2854     return;
2855 
2856   const NamedDecl *Def = getDefinition(Old);
2857   if (!Def || Def == New)
2858     return;
2859 
2860   AttrVec &NewAttributes = New->getAttrs();
2861   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2862     const Attr *NewAttribute = NewAttributes[I];
2863 
2864     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2865       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2866         Sema::SkipBodyInfo SkipBody;
2867         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2868 
2869         // If we're skipping this definition, drop the "alias" attribute.
2870         if (SkipBody.ShouldSkip) {
2871           NewAttributes.erase(NewAttributes.begin() + I);
2872           --E;
2873           continue;
2874         }
2875       } else {
2876         VarDecl *VD = cast<VarDecl>(New);
2877         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2878                                 VarDecl::TentativeDefinition
2879                             ? diag::err_alias_after_tentative
2880                             : diag::err_redefinition;
2881         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2882         if (Diag == diag::err_redefinition)
2883           S.notePreviousDefinition(Def, VD->getLocation());
2884         else
2885           S.Diag(Def->getLocation(), diag::note_previous_definition);
2886         VD->setInvalidDecl();
2887       }
2888       ++I;
2889       continue;
2890     }
2891 
2892     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2893       // Tentative definitions are only interesting for the alias check above.
2894       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2895         ++I;
2896         continue;
2897       }
2898     }
2899 
2900     if (hasAttribute(Def, NewAttribute->getKind())) {
2901       ++I;
2902       continue; // regular attr merging will take care of validating this.
2903     }
2904 
2905     if (isa<C11NoReturnAttr>(NewAttribute)) {
2906       // C's _Noreturn is allowed to be added to a function after it is defined.
2907       ++I;
2908       continue;
2909     } else if (isa<UuidAttr>(NewAttribute)) {
2910       // msvc will allow a subsequent definition to add an uuid to a class
2911       ++I;
2912       continue;
2913     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2914       if (AA->isAlignas()) {
2915         // C++11 [dcl.align]p6:
2916         //   if any declaration of an entity has an alignment-specifier,
2917         //   every defining declaration of that entity shall specify an
2918         //   equivalent alignment.
2919         // C11 6.7.5/7:
2920         //   If the definition of an object does not have an alignment
2921         //   specifier, any other declaration of that object shall also
2922         //   have no alignment specifier.
2923         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2924           << AA;
2925         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2926           << AA;
2927         NewAttributes.erase(NewAttributes.begin() + I);
2928         --E;
2929         continue;
2930       }
2931     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2932       // If there is a C definition followed by a redeclaration with this
2933       // attribute then there are two different definitions. In C++, prefer the
2934       // standard diagnostics.
2935       if (!S.getLangOpts().CPlusPlus) {
2936         S.Diag(NewAttribute->getLocation(),
2937                diag::err_loader_uninitialized_redeclaration);
2938         S.Diag(Def->getLocation(), diag::note_previous_definition);
2939         NewAttributes.erase(NewAttributes.begin() + I);
2940         --E;
2941         continue;
2942       }
2943     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2944                cast<VarDecl>(New)->isInline() &&
2945                !cast<VarDecl>(New)->isInlineSpecified()) {
2946       // Don't warn about applying selectany to implicitly inline variables.
2947       // Older compilers and language modes would require the use of selectany
2948       // to make such variables inline, and it would have no effect if we
2949       // honored it.
2950       ++I;
2951       continue;
2952     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2953       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2954       // declarations after defintions.
2955       ++I;
2956       continue;
2957     }
2958 
2959     S.Diag(NewAttribute->getLocation(),
2960            diag::warn_attribute_precede_definition);
2961     S.Diag(Def->getLocation(), diag::note_previous_definition);
2962     NewAttributes.erase(NewAttributes.begin() + I);
2963     --E;
2964   }
2965 }
2966 
2967 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2968                                      const ConstInitAttr *CIAttr,
2969                                      bool AttrBeforeInit) {
2970   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2971 
2972   // Figure out a good way to write this specifier on the old declaration.
2973   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2974   // enough of the attribute list spelling information to extract that without
2975   // heroics.
2976   std::string SuitableSpelling;
2977   if (S.getLangOpts().CPlusPlus20)
2978     SuitableSpelling = std::string(
2979         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2980   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2981     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2982         InsertLoc, {tok::l_square, tok::l_square,
2983                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2984                     S.PP.getIdentifierInfo("require_constant_initialization"),
2985                     tok::r_square, tok::r_square}));
2986   if (SuitableSpelling.empty())
2987     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2988         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2989                     S.PP.getIdentifierInfo("require_constant_initialization"),
2990                     tok::r_paren, tok::r_paren}));
2991   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2992     SuitableSpelling = "constinit";
2993   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2994     SuitableSpelling = "[[clang::require_constant_initialization]]";
2995   if (SuitableSpelling.empty())
2996     SuitableSpelling = "__attribute__((require_constant_initialization))";
2997   SuitableSpelling += " ";
2998 
2999   if (AttrBeforeInit) {
3000     // extern constinit int a;
3001     // int a = 0; // error (missing 'constinit'), accepted as extension
3002     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3003     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3004         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3005     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3006   } else {
3007     // int a = 0;
3008     // constinit extern int a; // error (missing 'constinit')
3009     S.Diag(CIAttr->getLocation(),
3010            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3011                                  : diag::warn_require_const_init_added_too_late)
3012         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3013     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3014         << CIAttr->isConstinit()
3015         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3016   }
3017 }
3018 
3019 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3020 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3021                                AvailabilityMergeKind AMK) {
3022   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3023     UsedAttr *NewAttr = OldAttr->clone(Context);
3024     NewAttr->setInherited(true);
3025     New->addAttr(NewAttr);
3026   }
3027   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3028     RetainAttr *NewAttr = OldAttr->clone(Context);
3029     NewAttr->setInherited(true);
3030     New->addAttr(NewAttr);
3031   }
3032 
3033   if (!Old->hasAttrs() && !New->hasAttrs())
3034     return;
3035 
3036   // [dcl.constinit]p1:
3037   //   If the [constinit] specifier is applied to any declaration of a
3038   //   variable, it shall be applied to the initializing declaration.
3039   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3040   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3041   if (bool(OldConstInit) != bool(NewConstInit)) {
3042     const auto *OldVD = cast<VarDecl>(Old);
3043     auto *NewVD = cast<VarDecl>(New);
3044 
3045     // Find the initializing declaration. Note that we might not have linked
3046     // the new declaration into the redeclaration chain yet.
3047     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3048     if (!InitDecl &&
3049         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3050       InitDecl = NewVD;
3051 
3052     if (InitDecl == NewVD) {
3053       // This is the initializing declaration. If it would inherit 'constinit',
3054       // that's ill-formed. (Note that we do not apply this to the attribute
3055       // form).
3056       if (OldConstInit && OldConstInit->isConstinit())
3057         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3058                                  /*AttrBeforeInit=*/true);
3059     } else if (NewConstInit) {
3060       // This is the first time we've been told that this declaration should
3061       // have a constant initializer. If we already saw the initializing
3062       // declaration, this is too late.
3063       if (InitDecl && InitDecl != NewVD) {
3064         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3065                                  /*AttrBeforeInit=*/false);
3066         NewVD->dropAttr<ConstInitAttr>();
3067       }
3068     }
3069   }
3070 
3071   // Attributes declared post-definition are currently ignored.
3072   checkNewAttributesAfterDef(*this, New, Old);
3073 
3074   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3075     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3076       if (!OldA->isEquivalent(NewA)) {
3077         // This redeclaration changes __asm__ label.
3078         Diag(New->getLocation(), diag::err_different_asm_label);
3079         Diag(OldA->getLocation(), diag::note_previous_declaration);
3080       }
3081     } else if (Old->isUsed()) {
3082       // This redeclaration adds an __asm__ label to a declaration that has
3083       // already been ODR-used.
3084       Diag(New->getLocation(), diag::err_late_asm_label_name)
3085         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3086     }
3087   }
3088 
3089   // Re-declaration cannot add abi_tag's.
3090   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3091     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3092       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3093         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3094           Diag(NewAbiTagAttr->getLocation(),
3095                diag::err_new_abi_tag_on_redeclaration)
3096               << NewTag;
3097           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3098         }
3099       }
3100     } else {
3101       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3102       Diag(Old->getLocation(), diag::note_previous_declaration);
3103     }
3104   }
3105 
3106   // This redeclaration adds a section attribute.
3107   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3108     if (auto *VD = dyn_cast<VarDecl>(New)) {
3109       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3110         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3111         Diag(Old->getLocation(), diag::note_previous_declaration);
3112       }
3113     }
3114   }
3115 
3116   // Redeclaration adds code-seg attribute.
3117   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3118   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3119       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3120     Diag(New->getLocation(), diag::warn_mismatched_section)
3121          << 0 /*codeseg*/;
3122     Diag(Old->getLocation(), diag::note_previous_declaration);
3123   }
3124 
3125   if (!Old->hasAttrs())
3126     return;
3127 
3128   bool foundAny = New->hasAttrs();
3129 
3130   // Ensure that any moving of objects within the allocated map is done before
3131   // we process them.
3132   if (!foundAny) New->setAttrs(AttrVec());
3133 
3134   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3135     // Ignore deprecated/unavailable/availability attributes if requested.
3136     AvailabilityMergeKind LocalAMK = AMK_None;
3137     if (isa<DeprecatedAttr>(I) ||
3138         isa<UnavailableAttr>(I) ||
3139         isa<AvailabilityAttr>(I)) {
3140       switch (AMK) {
3141       case AMK_None:
3142         continue;
3143 
3144       case AMK_Redeclaration:
3145       case AMK_Override:
3146       case AMK_ProtocolImplementation:
3147       case AMK_OptionalProtocolImplementation:
3148         LocalAMK = AMK;
3149         break;
3150       }
3151     }
3152 
3153     // Already handled.
3154     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3155       continue;
3156 
3157     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3158       foundAny = true;
3159   }
3160 
3161   if (mergeAlignedAttrs(*this, New, Old))
3162     foundAny = true;
3163 
3164   if (!foundAny) New->dropAttrs();
3165 }
3166 
3167 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3168 /// to the new one.
3169 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3170                                      const ParmVarDecl *oldDecl,
3171                                      Sema &S) {
3172   // C++11 [dcl.attr.depend]p2:
3173   //   The first declaration of a function shall specify the
3174   //   carries_dependency attribute for its declarator-id if any declaration
3175   //   of the function specifies the carries_dependency attribute.
3176   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3177   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3178     S.Diag(CDA->getLocation(),
3179            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3180     // Find the first declaration of the parameter.
3181     // FIXME: Should we build redeclaration chains for function parameters?
3182     const FunctionDecl *FirstFD =
3183       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3184     const ParmVarDecl *FirstVD =
3185       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3186     S.Diag(FirstVD->getLocation(),
3187            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3188   }
3189 
3190   if (!oldDecl->hasAttrs())
3191     return;
3192 
3193   bool foundAny = newDecl->hasAttrs();
3194 
3195   // Ensure that any moving of objects within the allocated map is
3196   // done before we process them.
3197   if (!foundAny) newDecl->setAttrs(AttrVec());
3198 
3199   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3200     if (!DeclHasAttr(newDecl, I)) {
3201       InheritableAttr *newAttr =
3202         cast<InheritableParamAttr>(I->clone(S.Context));
3203       newAttr->setInherited(true);
3204       newDecl->addAttr(newAttr);
3205       foundAny = true;
3206     }
3207   }
3208 
3209   if (!foundAny) newDecl->dropAttrs();
3210 }
3211 
3212 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3213                                 const ParmVarDecl *OldParam,
3214                                 Sema &S) {
3215   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3216     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3217       if (*Oldnullability != *Newnullability) {
3218         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3219           << DiagNullabilityKind(
3220                *Newnullability,
3221                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3222                 != 0))
3223           << DiagNullabilityKind(
3224                *Oldnullability,
3225                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3226                 != 0));
3227         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3228       }
3229     } else {
3230       QualType NewT = NewParam->getType();
3231       NewT = S.Context.getAttributedType(
3232                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3233                          NewT, NewT);
3234       NewParam->setType(NewT);
3235     }
3236   }
3237 }
3238 
3239 namespace {
3240 
3241 /// Used in MergeFunctionDecl to keep track of function parameters in
3242 /// C.
3243 struct GNUCompatibleParamWarning {
3244   ParmVarDecl *OldParm;
3245   ParmVarDecl *NewParm;
3246   QualType PromotedType;
3247 };
3248 
3249 } // end anonymous namespace
3250 
3251 // Determine whether the previous declaration was a definition, implicit
3252 // declaration, or a declaration.
3253 template <typename T>
3254 static std::pair<diag::kind, SourceLocation>
3255 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3256   diag::kind PrevDiag;
3257   SourceLocation OldLocation = Old->getLocation();
3258   if (Old->isThisDeclarationADefinition())
3259     PrevDiag = diag::note_previous_definition;
3260   else if (Old->isImplicit()) {
3261     PrevDiag = diag::note_previous_implicit_declaration;
3262     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3263       if (FD->getBuiltinID())
3264         PrevDiag = diag::note_previous_builtin_declaration;
3265     }
3266     if (OldLocation.isInvalid())
3267       OldLocation = New->getLocation();
3268   } else
3269     PrevDiag = diag::note_previous_declaration;
3270   return std::make_pair(PrevDiag, OldLocation);
3271 }
3272 
3273 /// canRedefineFunction - checks if a function can be redefined. Currently,
3274 /// only extern inline functions can be redefined, and even then only in
3275 /// GNU89 mode.
3276 static bool canRedefineFunction(const FunctionDecl *FD,
3277                                 const LangOptions& LangOpts) {
3278   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3279           !LangOpts.CPlusPlus &&
3280           FD->isInlineSpecified() &&
3281           FD->getStorageClass() == SC_Extern);
3282 }
3283 
3284 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3285   const AttributedType *AT = T->getAs<AttributedType>();
3286   while (AT && !AT->isCallingConv())
3287     AT = AT->getModifiedType()->getAs<AttributedType>();
3288   return AT;
3289 }
3290 
3291 template <typename T>
3292 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3293   const DeclContext *DC = Old->getDeclContext();
3294   if (DC->isRecord())
3295     return false;
3296 
3297   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3298   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3299     return true;
3300   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3301     return true;
3302   return false;
3303 }
3304 
3305 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3306 static bool isExternC(VarTemplateDecl *) { return false; }
3307 static bool isExternC(FunctionTemplateDecl *) { return false; }
3308 
3309 /// Check whether a redeclaration of an entity introduced by a
3310 /// using-declaration is valid, given that we know it's not an overload
3311 /// (nor a hidden tag declaration).
3312 template<typename ExpectedDecl>
3313 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3314                                    ExpectedDecl *New) {
3315   // C++11 [basic.scope.declarative]p4:
3316   //   Given a set of declarations in a single declarative region, each of
3317   //   which specifies the same unqualified name,
3318   //   -- they shall all refer to the same entity, or all refer to functions
3319   //      and function templates; or
3320   //   -- exactly one declaration shall declare a class name or enumeration
3321   //      name that is not a typedef name and the other declarations shall all
3322   //      refer to the same variable or enumerator, or all refer to functions
3323   //      and function templates; in this case the class name or enumeration
3324   //      name is hidden (3.3.10).
3325 
3326   // C++11 [namespace.udecl]p14:
3327   //   If a function declaration in namespace scope or block scope has the
3328   //   same name and the same parameter-type-list as a function introduced
3329   //   by a using-declaration, and the declarations do not declare the same
3330   //   function, the program is ill-formed.
3331 
3332   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3333   if (Old &&
3334       !Old->getDeclContext()->getRedeclContext()->Equals(
3335           New->getDeclContext()->getRedeclContext()) &&
3336       !(isExternC(Old) && isExternC(New)))
3337     Old = nullptr;
3338 
3339   if (!Old) {
3340     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3341     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3342     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3343     return true;
3344   }
3345   return false;
3346 }
3347 
3348 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3349                                             const FunctionDecl *B) {
3350   assert(A->getNumParams() == B->getNumParams());
3351 
3352   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3353     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3354     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3355     if (AttrA == AttrB)
3356       return true;
3357     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3358            AttrA->isDynamic() == AttrB->isDynamic();
3359   };
3360 
3361   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3362 }
3363 
3364 /// If necessary, adjust the semantic declaration context for a qualified
3365 /// declaration to name the correct inline namespace within the qualifier.
3366 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3367                                                DeclaratorDecl *OldD) {
3368   // The only case where we need to update the DeclContext is when
3369   // redeclaration lookup for a qualified name finds a declaration
3370   // in an inline namespace within the context named by the qualifier:
3371   //
3372   //   inline namespace N { int f(); }
3373   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3374   //
3375   // For unqualified declarations, the semantic context *can* change
3376   // along the redeclaration chain (for local extern declarations,
3377   // extern "C" declarations, and friend declarations in particular).
3378   if (!NewD->getQualifier())
3379     return;
3380 
3381   // NewD is probably already in the right context.
3382   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3383   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3384   if (NamedDC->Equals(SemaDC))
3385     return;
3386 
3387   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3388           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3389          "unexpected context for redeclaration");
3390 
3391   auto *LexDC = NewD->getLexicalDeclContext();
3392   auto FixSemaDC = [=](NamedDecl *D) {
3393     if (!D)
3394       return;
3395     D->setDeclContext(SemaDC);
3396     D->setLexicalDeclContext(LexDC);
3397   };
3398 
3399   FixSemaDC(NewD);
3400   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3401     FixSemaDC(FD->getDescribedFunctionTemplate());
3402   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3403     FixSemaDC(VD->getDescribedVarTemplate());
3404 }
3405 
3406 /// MergeFunctionDecl - We just parsed a function 'New' from
3407 /// declarator D which has the same name and scope as a previous
3408 /// declaration 'Old'.  Figure out how to resolve this situation,
3409 /// merging decls or emitting diagnostics as appropriate.
3410 ///
3411 /// In C++, New and Old must be declarations that are not
3412 /// overloaded. Use IsOverload to determine whether New and Old are
3413 /// overloaded, and to select the Old declaration that New should be
3414 /// merged with.
3415 ///
3416 /// Returns true if there was an error, false otherwise.
3417 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3418                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3419   // Verify the old decl was also a function.
3420   FunctionDecl *Old = OldD->getAsFunction();
3421   if (!Old) {
3422     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3423       if (New->getFriendObjectKind()) {
3424         Diag(New->getLocation(), diag::err_using_decl_friend);
3425         Diag(Shadow->getTargetDecl()->getLocation(),
3426              diag::note_using_decl_target);
3427         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3428             << 0;
3429         return true;
3430       }
3431 
3432       // Check whether the two declarations might declare the same function or
3433       // function template.
3434       if (FunctionTemplateDecl *NewTemplate =
3435               New->getDescribedFunctionTemplate()) {
3436         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3437                                                          NewTemplate))
3438           return true;
3439         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3440                          ->getAsFunction();
3441       } else {
3442         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3443           return true;
3444         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3445       }
3446     } else {
3447       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3448         << New->getDeclName();
3449       notePreviousDefinition(OldD, New->getLocation());
3450       return true;
3451     }
3452   }
3453 
3454   // If the old declaration was found in an inline namespace and the new
3455   // declaration was qualified, update the DeclContext to match.
3456   adjustDeclContextForDeclaratorDecl(New, Old);
3457 
3458   // If the old declaration is invalid, just give up here.
3459   if (Old->isInvalidDecl())
3460     return true;
3461 
3462   // Disallow redeclaration of some builtins.
3463   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3464     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3465     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3466         << Old << Old->getType();
3467     return true;
3468   }
3469 
3470   diag::kind PrevDiag;
3471   SourceLocation OldLocation;
3472   std::tie(PrevDiag, OldLocation) =
3473       getNoteDiagForInvalidRedeclaration(Old, New);
3474 
3475   // Don't complain about this if we're in GNU89 mode and the old function
3476   // is an extern inline function.
3477   // Don't complain about specializations. They are not supposed to have
3478   // storage classes.
3479   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3480       New->getStorageClass() == SC_Static &&
3481       Old->hasExternalFormalLinkage() &&
3482       !New->getTemplateSpecializationInfo() &&
3483       !canRedefineFunction(Old, getLangOpts())) {
3484     if (getLangOpts().MicrosoftExt) {
3485       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3486       Diag(OldLocation, PrevDiag);
3487     } else {
3488       Diag(New->getLocation(), diag::err_static_non_static) << New;
3489       Diag(OldLocation, PrevDiag);
3490       return true;
3491     }
3492   }
3493 
3494   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3495     if (!Old->hasAttr<InternalLinkageAttr>()) {
3496       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3497           << ILA;
3498       Diag(Old->getLocation(), diag::note_previous_declaration);
3499       New->dropAttr<InternalLinkageAttr>();
3500     }
3501 
3502   if (auto *EA = New->getAttr<ErrorAttr>()) {
3503     if (!Old->hasAttr<ErrorAttr>()) {
3504       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3505       Diag(Old->getLocation(), diag::note_previous_declaration);
3506       New->dropAttr<ErrorAttr>();
3507     }
3508   }
3509 
3510   if (CheckRedeclarationInModule(New, Old))
3511     return true;
3512 
3513   if (!getLangOpts().CPlusPlus) {
3514     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3515     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3516       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3517         << New << OldOvl;
3518 
3519       // Try our best to find a decl that actually has the overloadable
3520       // attribute for the note. In most cases (e.g. programs with only one
3521       // broken declaration/definition), this won't matter.
3522       //
3523       // FIXME: We could do this if we juggled some extra state in
3524       // OverloadableAttr, rather than just removing it.
3525       const Decl *DiagOld = Old;
3526       if (OldOvl) {
3527         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3528           const auto *A = D->getAttr<OverloadableAttr>();
3529           return A && !A->isImplicit();
3530         });
3531         // If we've implicitly added *all* of the overloadable attrs to this
3532         // chain, emitting a "previous redecl" note is pointless.
3533         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3534       }
3535 
3536       if (DiagOld)
3537         Diag(DiagOld->getLocation(),
3538              diag::note_attribute_overloadable_prev_overload)
3539           << OldOvl;
3540 
3541       if (OldOvl)
3542         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3543       else
3544         New->dropAttr<OverloadableAttr>();
3545     }
3546   }
3547 
3548   // If a function is first declared with a calling convention, but is later
3549   // declared or defined without one, all following decls assume the calling
3550   // convention of the first.
3551   //
3552   // It's OK if a function is first declared without a calling convention,
3553   // but is later declared or defined with the default calling convention.
3554   //
3555   // To test if either decl has an explicit calling convention, we look for
3556   // AttributedType sugar nodes on the type as written.  If they are missing or
3557   // were canonicalized away, we assume the calling convention was implicit.
3558   //
3559   // Note also that we DO NOT return at this point, because we still have
3560   // other tests to run.
3561   QualType OldQType = Context.getCanonicalType(Old->getType());
3562   QualType NewQType = Context.getCanonicalType(New->getType());
3563   const FunctionType *OldType = cast<FunctionType>(OldQType);
3564   const FunctionType *NewType = cast<FunctionType>(NewQType);
3565   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3566   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3567   bool RequiresAdjustment = false;
3568 
3569   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3570     FunctionDecl *First = Old->getFirstDecl();
3571     const FunctionType *FT =
3572         First->getType().getCanonicalType()->castAs<FunctionType>();
3573     FunctionType::ExtInfo FI = FT->getExtInfo();
3574     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3575     if (!NewCCExplicit) {
3576       // Inherit the CC from the previous declaration if it was specified
3577       // there but not here.
3578       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3579       RequiresAdjustment = true;
3580     } else if (Old->getBuiltinID()) {
3581       // Builtin attribute isn't propagated to the new one yet at this point,
3582       // so we check if the old one is a builtin.
3583 
3584       // Calling Conventions on a Builtin aren't really useful and setting a
3585       // default calling convention and cdecl'ing some builtin redeclarations is
3586       // common, so warn and ignore the calling convention on the redeclaration.
3587       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3588           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3589           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3590       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3591       RequiresAdjustment = true;
3592     } else {
3593       // Calling conventions aren't compatible, so complain.
3594       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3595       Diag(New->getLocation(), diag::err_cconv_change)
3596         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3597         << !FirstCCExplicit
3598         << (!FirstCCExplicit ? "" :
3599             FunctionType::getNameForCallConv(FI.getCC()));
3600 
3601       // Put the note on the first decl, since it is the one that matters.
3602       Diag(First->getLocation(), diag::note_previous_declaration);
3603       return true;
3604     }
3605   }
3606 
3607   // FIXME: diagnose the other way around?
3608   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3609     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3610     RequiresAdjustment = true;
3611   }
3612 
3613   // Merge regparm attribute.
3614   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3615       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3616     if (NewTypeInfo.getHasRegParm()) {
3617       Diag(New->getLocation(), diag::err_regparm_mismatch)
3618         << NewType->getRegParmType()
3619         << OldType->getRegParmType();
3620       Diag(OldLocation, diag::note_previous_declaration);
3621       return true;
3622     }
3623 
3624     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3625     RequiresAdjustment = true;
3626   }
3627 
3628   // Merge ns_returns_retained attribute.
3629   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3630     if (NewTypeInfo.getProducesResult()) {
3631       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3632           << "'ns_returns_retained'";
3633       Diag(OldLocation, diag::note_previous_declaration);
3634       return true;
3635     }
3636 
3637     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3638     RequiresAdjustment = true;
3639   }
3640 
3641   if (OldTypeInfo.getNoCallerSavedRegs() !=
3642       NewTypeInfo.getNoCallerSavedRegs()) {
3643     if (NewTypeInfo.getNoCallerSavedRegs()) {
3644       AnyX86NoCallerSavedRegistersAttr *Attr =
3645         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3646       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3647       Diag(OldLocation, diag::note_previous_declaration);
3648       return true;
3649     }
3650 
3651     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3652     RequiresAdjustment = true;
3653   }
3654 
3655   if (RequiresAdjustment) {
3656     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3657     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3658     New->setType(QualType(AdjustedType, 0));
3659     NewQType = Context.getCanonicalType(New->getType());
3660   }
3661 
3662   // If this redeclaration makes the function inline, we may need to add it to
3663   // UndefinedButUsed.
3664   if (!Old->isInlined() && New->isInlined() &&
3665       !New->hasAttr<GNUInlineAttr>() &&
3666       !getLangOpts().GNUInline &&
3667       Old->isUsed(false) &&
3668       !Old->isDefined() && !New->isThisDeclarationADefinition())
3669     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3670                                            SourceLocation()));
3671 
3672   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3673   // about it.
3674   if (New->hasAttr<GNUInlineAttr>() &&
3675       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3676     UndefinedButUsed.erase(Old->getCanonicalDecl());
3677   }
3678 
3679   // If pass_object_size params don't match up perfectly, this isn't a valid
3680   // redeclaration.
3681   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3682       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3683     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3684         << New->getDeclName();
3685     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3686     return true;
3687   }
3688 
3689   if (getLangOpts().CPlusPlus) {
3690     // C++1z [over.load]p2
3691     //   Certain function declarations cannot be overloaded:
3692     //     -- Function declarations that differ only in the return type,
3693     //        the exception specification, or both cannot be overloaded.
3694 
3695     // Check the exception specifications match. This may recompute the type of
3696     // both Old and New if it resolved exception specifications, so grab the
3697     // types again after this. Because this updates the type, we do this before
3698     // any of the other checks below, which may update the "de facto" NewQType
3699     // but do not necessarily update the type of New.
3700     if (CheckEquivalentExceptionSpec(Old, New))
3701       return true;
3702     OldQType = Context.getCanonicalType(Old->getType());
3703     NewQType = Context.getCanonicalType(New->getType());
3704 
3705     // Go back to the type source info to compare the declared return types,
3706     // per C++1y [dcl.type.auto]p13:
3707     //   Redeclarations or specializations of a function or function template
3708     //   with a declared return type that uses a placeholder type shall also
3709     //   use that placeholder, not a deduced type.
3710     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3711     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3712     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3713         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3714                                        OldDeclaredReturnType)) {
3715       QualType ResQT;
3716       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3717           OldDeclaredReturnType->isObjCObjectPointerType())
3718         // FIXME: This does the wrong thing for a deduced return type.
3719         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3720       if (ResQT.isNull()) {
3721         if (New->isCXXClassMember() && New->isOutOfLine())
3722           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3723               << New << New->getReturnTypeSourceRange();
3724         else
3725           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3726               << New->getReturnTypeSourceRange();
3727         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3728                                     << Old->getReturnTypeSourceRange();
3729         return true;
3730       }
3731       else
3732         NewQType = ResQT;
3733     }
3734 
3735     QualType OldReturnType = OldType->getReturnType();
3736     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3737     if (OldReturnType != NewReturnType) {
3738       // If this function has a deduced return type and has already been
3739       // defined, copy the deduced value from the old declaration.
3740       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3741       if (OldAT && OldAT->isDeduced()) {
3742         QualType DT = OldAT->getDeducedType();
3743         if (DT.isNull()) {
3744           New->setType(SubstAutoTypeDependent(New->getType()));
3745           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3746         } else {
3747           New->setType(SubstAutoType(New->getType(), DT));
3748           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3749         }
3750       }
3751     }
3752 
3753     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3754     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3755     if (OldMethod && NewMethod) {
3756       // Preserve triviality.
3757       NewMethod->setTrivial(OldMethod->isTrivial());
3758 
3759       // MSVC allows explicit template specialization at class scope:
3760       // 2 CXXMethodDecls referring to the same function will be injected.
3761       // We don't want a redeclaration error.
3762       bool IsClassScopeExplicitSpecialization =
3763                               OldMethod->isFunctionTemplateSpecialization() &&
3764                               NewMethod->isFunctionTemplateSpecialization();
3765       bool isFriend = NewMethod->getFriendObjectKind();
3766 
3767       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3768           !IsClassScopeExplicitSpecialization) {
3769         //    -- Member function declarations with the same name and the
3770         //       same parameter types cannot be overloaded if any of them
3771         //       is a static member function declaration.
3772         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3773           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3774           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3775           return true;
3776         }
3777 
3778         // C++ [class.mem]p1:
3779         //   [...] A member shall not be declared twice in the
3780         //   member-specification, except that a nested class or member
3781         //   class template can be declared and then later defined.
3782         if (!inTemplateInstantiation()) {
3783           unsigned NewDiag;
3784           if (isa<CXXConstructorDecl>(OldMethod))
3785             NewDiag = diag::err_constructor_redeclared;
3786           else if (isa<CXXDestructorDecl>(NewMethod))
3787             NewDiag = diag::err_destructor_redeclared;
3788           else if (isa<CXXConversionDecl>(NewMethod))
3789             NewDiag = diag::err_conv_function_redeclared;
3790           else
3791             NewDiag = diag::err_member_redeclared;
3792 
3793           Diag(New->getLocation(), NewDiag);
3794         } else {
3795           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3796             << New << New->getType();
3797         }
3798         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3799         return true;
3800 
3801       // Complain if this is an explicit declaration of a special
3802       // member that was initially declared implicitly.
3803       //
3804       // As an exception, it's okay to befriend such methods in order
3805       // to permit the implicit constructor/destructor/operator calls.
3806       } else if (OldMethod->isImplicit()) {
3807         if (isFriend) {
3808           NewMethod->setImplicit();
3809         } else {
3810           Diag(NewMethod->getLocation(),
3811                diag::err_definition_of_implicitly_declared_member)
3812             << New << getSpecialMember(OldMethod);
3813           return true;
3814         }
3815       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3816         Diag(NewMethod->getLocation(),
3817              diag::err_definition_of_explicitly_defaulted_member)
3818           << getSpecialMember(OldMethod);
3819         return true;
3820       }
3821     }
3822 
3823     // C++11 [dcl.attr.noreturn]p1:
3824     //   The first declaration of a function shall specify the noreturn
3825     //   attribute if any declaration of that function specifies the noreturn
3826     //   attribute.
3827     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3828       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3829         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3830             << NRA;
3831         Diag(Old->getLocation(), diag::note_previous_declaration);
3832       }
3833 
3834     // C++11 [dcl.attr.depend]p2:
3835     //   The first declaration of a function shall specify the
3836     //   carries_dependency attribute for its declarator-id if any declaration
3837     //   of the function specifies the carries_dependency attribute.
3838     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3839     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3840       Diag(CDA->getLocation(),
3841            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3842       Diag(Old->getFirstDecl()->getLocation(),
3843            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3844     }
3845 
3846     // (C++98 8.3.5p3):
3847     //   All declarations for a function shall agree exactly in both the
3848     //   return type and the parameter-type-list.
3849     // We also want to respect all the extended bits except noreturn.
3850 
3851     // noreturn should now match unless the old type info didn't have it.
3852     QualType OldQTypeForComparison = OldQType;
3853     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3854       auto *OldType = OldQType->castAs<FunctionProtoType>();
3855       const FunctionType *OldTypeForComparison
3856         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3857       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3858       assert(OldQTypeForComparison.isCanonical());
3859     }
3860 
3861     if (haveIncompatibleLanguageLinkages(Old, New)) {
3862       // As a special case, retain the language linkage from previous
3863       // declarations of a friend function as an extension.
3864       //
3865       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3866       // and is useful because there's otherwise no way to specify language
3867       // linkage within class scope.
3868       //
3869       // Check cautiously as the friend object kind isn't yet complete.
3870       if (New->getFriendObjectKind() != Decl::FOK_None) {
3871         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3872         Diag(OldLocation, PrevDiag);
3873       } else {
3874         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3875         Diag(OldLocation, PrevDiag);
3876         return true;
3877       }
3878     }
3879 
3880     // If the function types are compatible, merge the declarations. Ignore the
3881     // exception specifier because it was already checked above in
3882     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3883     // about incompatible types under -fms-compatibility.
3884     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3885                                                          NewQType))
3886       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3887 
3888     // If the types are imprecise (due to dependent constructs in friends or
3889     // local extern declarations), it's OK if they differ. We'll check again
3890     // during instantiation.
3891     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3892       return false;
3893 
3894     // Fall through for conflicting redeclarations and redefinitions.
3895   }
3896 
3897   // C: Function types need to be compatible, not identical. This handles
3898   // duplicate function decls like "void f(int); void f(enum X);" properly.
3899   if (!getLangOpts().CPlusPlus) {
3900     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3901     // type is specified by a function definition that contains a (possibly
3902     // empty) identifier list, both shall agree in the number of parameters
3903     // and the type of each parameter shall be compatible with the type that
3904     // results from the application of default argument promotions to the
3905     // type of the corresponding identifier. ...
3906     // This cannot be handled by ASTContext::typesAreCompatible() because that
3907     // doesn't know whether the function type is for a definition or not when
3908     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3909     // we need to cover here is that the number of arguments agree as the
3910     // default argument promotion rules were already checked by
3911     // ASTContext::typesAreCompatible().
3912     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3913         Old->getNumParams() != New->getNumParams()) {
3914       if (Old->hasInheritedPrototype())
3915         Old = Old->getCanonicalDecl();
3916       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3917       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3918       return true;
3919     }
3920 
3921     // If we are merging two functions where only one of them has a prototype,
3922     // we may have enough information to decide to issue a diagnostic that the
3923     // function without a protoype will change behavior in C2x. This handles
3924     // cases like:
3925     //   void i(); void i(int j);
3926     //   void i(int j); void i();
3927     //   void i(); void i(int j) {}
3928     // See ActOnFinishFunctionBody() for other cases of the behavior change
3929     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3930     // type without a prototype.
3931     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3932         !New->isImplicit() && !Old->isImplicit()) {
3933       const FunctionDecl *WithProto, *WithoutProto;
3934       if (New->hasWrittenPrototype()) {
3935         WithProto = New;
3936         WithoutProto = Old;
3937       } else {
3938         WithProto = Old;
3939         WithoutProto = New;
3940       }
3941 
3942       if (WithProto->getNumParams() != 0) {
3943         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3944           // The one without the prototype will be changing behavior in C2x, so
3945           // warn about that one so long as it's a user-visible declaration.
3946           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3947           if (WithoutProto == New)
3948             IsWithoutProtoADef = NewDeclIsDefn;
3949           else
3950             IsWithProtoADef = NewDeclIsDefn;
3951           Diag(WithoutProto->getLocation(),
3952                diag::warn_non_prototype_changes_behavior)
3953               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
3954               << (WithoutProto == Old) << IsWithProtoADef;
3955 
3956           // The reason the one without the prototype will be changing behavior
3957           // is because of the one with the prototype, so note that so long as
3958           // it's a user-visible declaration. There is one exception to this:
3959           // when the new declaration is a definition without a prototype, the
3960           // old declaration with a prototype is not the cause of the issue,
3961           // and that does not need to be noted because the one with a
3962           // prototype will not change behavior in C2x.
3963           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
3964               !IsWithoutProtoADef)
3965             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
3966         }
3967       }
3968     }
3969 
3970     if (Context.typesAreCompatible(OldQType, NewQType)) {
3971       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3972       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3973       const FunctionProtoType *OldProto = nullptr;
3974       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3975           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3976         // The old declaration provided a function prototype, but the
3977         // new declaration does not. Merge in the prototype.
3978         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3979         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3980         NewQType =
3981             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3982                                     OldProto->getExtProtoInfo());
3983         New->setType(NewQType);
3984         New->setHasInheritedPrototype();
3985 
3986         // Synthesize parameters with the same types.
3987         SmallVector<ParmVarDecl *, 16> Params;
3988         for (const auto &ParamType : OldProto->param_types()) {
3989           ParmVarDecl *Param = ParmVarDecl::Create(
3990               Context, New, SourceLocation(), SourceLocation(), nullptr,
3991               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
3992           Param->setScopeInfo(0, Params.size());
3993           Param->setImplicit();
3994           Params.push_back(Param);
3995         }
3996 
3997         New->setParams(Params);
3998       }
3999 
4000       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4001     }
4002   }
4003 
4004   // Check if the function types are compatible when pointer size address
4005   // spaces are ignored.
4006   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4007     return false;
4008 
4009   // GNU C permits a K&R definition to follow a prototype declaration
4010   // if the declared types of the parameters in the K&R definition
4011   // match the types in the prototype declaration, even when the
4012   // promoted types of the parameters from the K&R definition differ
4013   // from the types in the prototype. GCC then keeps the types from
4014   // the prototype.
4015   //
4016   // If a variadic prototype is followed by a non-variadic K&R definition,
4017   // the K&R definition becomes variadic.  This is sort of an edge case, but
4018   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4019   // C99 6.9.1p8.
4020   if (!getLangOpts().CPlusPlus &&
4021       Old->hasPrototype() && !New->hasPrototype() &&
4022       New->getType()->getAs<FunctionProtoType>() &&
4023       Old->getNumParams() == New->getNumParams()) {
4024     SmallVector<QualType, 16> ArgTypes;
4025     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4026     const FunctionProtoType *OldProto
4027       = Old->getType()->getAs<FunctionProtoType>();
4028     const FunctionProtoType *NewProto
4029       = New->getType()->getAs<FunctionProtoType>();
4030 
4031     // Determine whether this is the GNU C extension.
4032     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4033                                                NewProto->getReturnType());
4034     bool LooseCompatible = !MergedReturn.isNull();
4035     for (unsigned Idx = 0, End = Old->getNumParams();
4036          LooseCompatible && Idx != End; ++Idx) {
4037       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4038       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4039       if (Context.typesAreCompatible(OldParm->getType(),
4040                                      NewProto->getParamType(Idx))) {
4041         ArgTypes.push_back(NewParm->getType());
4042       } else if (Context.typesAreCompatible(OldParm->getType(),
4043                                             NewParm->getType(),
4044                                             /*CompareUnqualified=*/true)) {
4045         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4046                                            NewProto->getParamType(Idx) };
4047         Warnings.push_back(Warn);
4048         ArgTypes.push_back(NewParm->getType());
4049       } else
4050         LooseCompatible = false;
4051     }
4052 
4053     if (LooseCompatible) {
4054       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4055         Diag(Warnings[Warn].NewParm->getLocation(),
4056              diag::ext_param_promoted_not_compatible_with_prototype)
4057           << Warnings[Warn].PromotedType
4058           << Warnings[Warn].OldParm->getType();
4059         if (Warnings[Warn].OldParm->getLocation().isValid())
4060           Diag(Warnings[Warn].OldParm->getLocation(),
4061                diag::note_previous_declaration);
4062       }
4063 
4064       if (MergeTypeWithOld)
4065         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4066                                              OldProto->getExtProtoInfo()));
4067       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4068     }
4069 
4070     // Fall through to diagnose conflicting types.
4071   }
4072 
4073   // A function that has already been declared has been redeclared or
4074   // defined with a different type; show an appropriate diagnostic.
4075 
4076   // If the previous declaration was an implicitly-generated builtin
4077   // declaration, then at the very least we should use a specialized note.
4078   unsigned BuiltinID;
4079   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4080     // If it's actually a library-defined builtin function like 'malloc'
4081     // or 'printf', just warn about the incompatible redeclaration.
4082     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4083       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4084       Diag(OldLocation, diag::note_previous_builtin_declaration)
4085         << Old << Old->getType();
4086       return false;
4087     }
4088 
4089     PrevDiag = diag::note_previous_builtin_declaration;
4090   }
4091 
4092   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4093   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4094   return true;
4095 }
4096 
4097 /// Completes the merge of two function declarations that are
4098 /// known to be compatible.
4099 ///
4100 /// This routine handles the merging of attributes and other
4101 /// properties of function declarations from the old declaration to
4102 /// the new declaration, once we know that New is in fact a
4103 /// redeclaration of Old.
4104 ///
4105 /// \returns false
4106 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4107                                         Scope *S, bool MergeTypeWithOld) {
4108   // Merge the attributes
4109   mergeDeclAttributes(New, Old);
4110 
4111   // Merge "pure" flag.
4112   if (Old->isPure())
4113     New->setPure();
4114 
4115   // Merge "used" flag.
4116   if (Old->getMostRecentDecl()->isUsed(false))
4117     New->setIsUsed();
4118 
4119   // Merge attributes from the parameters.  These can mismatch with K&R
4120   // declarations.
4121   if (New->getNumParams() == Old->getNumParams())
4122       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4123         ParmVarDecl *NewParam = New->getParamDecl(i);
4124         ParmVarDecl *OldParam = Old->getParamDecl(i);
4125         mergeParamDeclAttributes(NewParam, OldParam, *this);
4126         mergeParamDeclTypes(NewParam, OldParam, *this);
4127       }
4128 
4129   if (getLangOpts().CPlusPlus)
4130     return MergeCXXFunctionDecl(New, Old, S);
4131 
4132   // Merge the function types so the we get the composite types for the return
4133   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4134   // was visible.
4135   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4136   if (!Merged.isNull() && MergeTypeWithOld)
4137     New->setType(Merged);
4138 
4139   return false;
4140 }
4141 
4142 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4143                                 ObjCMethodDecl *oldMethod) {
4144   // Merge the attributes, including deprecated/unavailable
4145   AvailabilityMergeKind MergeKind =
4146       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4147           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4148                                      : AMK_ProtocolImplementation)
4149           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4150                                                            : AMK_Override;
4151 
4152   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4153 
4154   // Merge attributes from the parameters.
4155   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4156                                        oe = oldMethod->param_end();
4157   for (ObjCMethodDecl::param_iterator
4158          ni = newMethod->param_begin(), ne = newMethod->param_end();
4159        ni != ne && oi != oe; ++ni, ++oi)
4160     mergeParamDeclAttributes(*ni, *oi, *this);
4161 
4162   CheckObjCMethodOverride(newMethod, oldMethod);
4163 }
4164 
4165 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4166   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4167 
4168   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4169          ? diag::err_redefinition_different_type
4170          : diag::err_redeclaration_different_type)
4171     << New->getDeclName() << New->getType() << Old->getType();
4172 
4173   diag::kind PrevDiag;
4174   SourceLocation OldLocation;
4175   std::tie(PrevDiag, OldLocation)
4176     = getNoteDiagForInvalidRedeclaration(Old, New);
4177   S.Diag(OldLocation, PrevDiag);
4178   New->setInvalidDecl();
4179 }
4180 
4181 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4182 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4183 /// emitting diagnostics as appropriate.
4184 ///
4185 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4186 /// to here in AddInitializerToDecl. We can't check them before the initializer
4187 /// is attached.
4188 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4189                              bool MergeTypeWithOld) {
4190   if (New->isInvalidDecl() || Old->isInvalidDecl())
4191     return;
4192 
4193   QualType MergedT;
4194   if (getLangOpts().CPlusPlus) {
4195     if (New->getType()->isUndeducedType()) {
4196       // We don't know what the new type is until the initializer is attached.
4197       return;
4198     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4199       // These could still be something that needs exception specs checked.
4200       return MergeVarDeclExceptionSpecs(New, Old);
4201     }
4202     // C++ [basic.link]p10:
4203     //   [...] the types specified by all declarations referring to a given
4204     //   object or function shall be identical, except that declarations for an
4205     //   array object can specify array types that differ by the presence or
4206     //   absence of a major array bound (8.3.4).
4207     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4208       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4209       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4210 
4211       // We are merging a variable declaration New into Old. If it has an array
4212       // bound, and that bound differs from Old's bound, we should diagnose the
4213       // mismatch.
4214       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4215         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4216              PrevVD = PrevVD->getPreviousDecl()) {
4217           QualType PrevVDTy = PrevVD->getType();
4218           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4219             continue;
4220 
4221           if (!Context.hasSameType(New->getType(), PrevVDTy))
4222             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4223         }
4224       }
4225 
4226       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4227         if (Context.hasSameType(OldArray->getElementType(),
4228                                 NewArray->getElementType()))
4229           MergedT = New->getType();
4230       }
4231       // FIXME: Check visibility. New is hidden but has a complete type. If New
4232       // has no array bound, it should not inherit one from Old, if Old is not
4233       // visible.
4234       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4235         if (Context.hasSameType(OldArray->getElementType(),
4236                                 NewArray->getElementType()))
4237           MergedT = Old->getType();
4238       }
4239     }
4240     else if (New->getType()->isObjCObjectPointerType() &&
4241                Old->getType()->isObjCObjectPointerType()) {
4242       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4243                                               Old->getType());
4244     }
4245   } else {
4246     // C 6.2.7p2:
4247     //   All declarations that refer to the same object or function shall have
4248     //   compatible type.
4249     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4250   }
4251   if (MergedT.isNull()) {
4252     // It's OK if we couldn't merge types if either type is dependent, for a
4253     // block-scope variable. In other cases (static data members of class
4254     // templates, variable templates, ...), we require the types to be
4255     // equivalent.
4256     // FIXME: The C++ standard doesn't say anything about this.
4257     if ((New->getType()->isDependentType() ||
4258          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4259       // If the old type was dependent, we can't merge with it, so the new type
4260       // becomes dependent for now. We'll reproduce the original type when we
4261       // instantiate the TypeSourceInfo for the variable.
4262       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4263         New->setType(Context.DependentTy);
4264       return;
4265     }
4266     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4267   }
4268 
4269   // Don't actually update the type on the new declaration if the old
4270   // declaration was an extern declaration in a different scope.
4271   if (MergeTypeWithOld)
4272     New->setType(MergedT);
4273 }
4274 
4275 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4276                                   LookupResult &Previous) {
4277   // C11 6.2.7p4:
4278   //   For an identifier with internal or external linkage declared
4279   //   in a scope in which a prior declaration of that identifier is
4280   //   visible, if the prior declaration specifies internal or
4281   //   external linkage, the type of the identifier at the later
4282   //   declaration becomes the composite type.
4283   //
4284   // If the variable isn't visible, we do not merge with its type.
4285   if (Previous.isShadowed())
4286     return false;
4287 
4288   if (S.getLangOpts().CPlusPlus) {
4289     // C++11 [dcl.array]p3:
4290     //   If there is a preceding declaration of the entity in the same
4291     //   scope in which the bound was specified, an omitted array bound
4292     //   is taken to be the same as in that earlier declaration.
4293     return NewVD->isPreviousDeclInSameBlockScope() ||
4294            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4295             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4296   } else {
4297     // If the old declaration was function-local, don't merge with its
4298     // type unless we're in the same function.
4299     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4300            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4301   }
4302 }
4303 
4304 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4305 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4306 /// situation, merging decls or emitting diagnostics as appropriate.
4307 ///
4308 /// Tentative definition rules (C99 6.9.2p2) are checked by
4309 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4310 /// definitions here, since the initializer hasn't been attached.
4311 ///
4312 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4313   // If the new decl is already invalid, don't do any other checking.
4314   if (New->isInvalidDecl())
4315     return;
4316 
4317   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4318     return;
4319 
4320   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4321 
4322   // Verify the old decl was also a variable or variable template.
4323   VarDecl *Old = nullptr;
4324   VarTemplateDecl *OldTemplate = nullptr;
4325   if (Previous.isSingleResult()) {
4326     if (NewTemplate) {
4327       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4328       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4329 
4330       if (auto *Shadow =
4331               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4332         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4333           return New->setInvalidDecl();
4334     } else {
4335       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4336 
4337       if (auto *Shadow =
4338               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4339         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4340           return New->setInvalidDecl();
4341     }
4342   }
4343   if (!Old) {
4344     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4345         << New->getDeclName();
4346     notePreviousDefinition(Previous.getRepresentativeDecl(),
4347                            New->getLocation());
4348     return New->setInvalidDecl();
4349   }
4350 
4351   // If the old declaration was found in an inline namespace and the new
4352   // declaration was qualified, update the DeclContext to match.
4353   adjustDeclContextForDeclaratorDecl(New, Old);
4354 
4355   // Ensure the template parameters are compatible.
4356   if (NewTemplate &&
4357       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4358                                       OldTemplate->getTemplateParameters(),
4359                                       /*Complain=*/true, TPL_TemplateMatch))
4360     return New->setInvalidDecl();
4361 
4362   // C++ [class.mem]p1:
4363   //   A member shall not be declared twice in the member-specification [...]
4364   //
4365   // Here, we need only consider static data members.
4366   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4367     Diag(New->getLocation(), diag::err_duplicate_member)
4368       << New->getIdentifier();
4369     Diag(Old->getLocation(), diag::note_previous_declaration);
4370     New->setInvalidDecl();
4371   }
4372 
4373   mergeDeclAttributes(New, Old);
4374   // Warn if an already-declared variable is made a weak_import in a subsequent
4375   // declaration
4376   if (New->hasAttr<WeakImportAttr>() &&
4377       Old->getStorageClass() == SC_None &&
4378       !Old->hasAttr<WeakImportAttr>()) {
4379     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4380     Diag(Old->getLocation(), diag::note_previous_declaration);
4381     // Remove weak_import attribute on new declaration.
4382     New->dropAttr<WeakImportAttr>();
4383   }
4384 
4385   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4386     if (!Old->hasAttr<InternalLinkageAttr>()) {
4387       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4388           << ILA;
4389       Diag(Old->getLocation(), diag::note_previous_declaration);
4390       New->dropAttr<InternalLinkageAttr>();
4391     }
4392 
4393   // Merge the types.
4394   VarDecl *MostRecent = Old->getMostRecentDecl();
4395   if (MostRecent != Old) {
4396     MergeVarDeclTypes(New, MostRecent,
4397                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4398     if (New->isInvalidDecl())
4399       return;
4400   }
4401 
4402   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4403   if (New->isInvalidDecl())
4404     return;
4405 
4406   diag::kind PrevDiag;
4407   SourceLocation OldLocation;
4408   std::tie(PrevDiag, OldLocation) =
4409       getNoteDiagForInvalidRedeclaration(Old, New);
4410 
4411   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4412   if (New->getStorageClass() == SC_Static &&
4413       !New->isStaticDataMember() &&
4414       Old->hasExternalFormalLinkage()) {
4415     if (getLangOpts().MicrosoftExt) {
4416       Diag(New->getLocation(), diag::ext_static_non_static)
4417           << New->getDeclName();
4418       Diag(OldLocation, PrevDiag);
4419     } else {
4420       Diag(New->getLocation(), diag::err_static_non_static)
4421           << New->getDeclName();
4422       Diag(OldLocation, PrevDiag);
4423       return New->setInvalidDecl();
4424     }
4425   }
4426   // C99 6.2.2p4:
4427   //   For an identifier declared with the storage-class specifier
4428   //   extern in a scope in which a prior declaration of that
4429   //   identifier is visible,23) if the prior declaration specifies
4430   //   internal or external linkage, the linkage of the identifier at
4431   //   the later declaration is the same as the linkage specified at
4432   //   the prior declaration. If no prior declaration is visible, or
4433   //   if the prior declaration specifies no linkage, then the
4434   //   identifier has external linkage.
4435   if (New->hasExternalStorage() && Old->hasLinkage())
4436     /* Okay */;
4437   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4438            !New->isStaticDataMember() &&
4439            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4440     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4441     Diag(OldLocation, PrevDiag);
4442     return New->setInvalidDecl();
4443   }
4444 
4445   // Check if extern is followed by non-extern and vice-versa.
4446   if (New->hasExternalStorage() &&
4447       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4448     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4449     Diag(OldLocation, PrevDiag);
4450     return New->setInvalidDecl();
4451   }
4452   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4453       !New->hasExternalStorage()) {
4454     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4455     Diag(OldLocation, PrevDiag);
4456     return New->setInvalidDecl();
4457   }
4458 
4459   if (CheckRedeclarationInModule(New, Old))
4460     return;
4461 
4462   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4463 
4464   // FIXME: The test for external storage here seems wrong? We still
4465   // need to check for mismatches.
4466   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4467       // Don't complain about out-of-line definitions of static members.
4468       !(Old->getLexicalDeclContext()->isRecord() &&
4469         !New->getLexicalDeclContext()->isRecord())) {
4470     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4471     Diag(OldLocation, PrevDiag);
4472     return New->setInvalidDecl();
4473   }
4474 
4475   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4476     if (VarDecl *Def = Old->getDefinition()) {
4477       // C++1z [dcl.fcn.spec]p4:
4478       //   If the definition of a variable appears in a translation unit before
4479       //   its first declaration as inline, the program is ill-formed.
4480       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4481       Diag(Def->getLocation(), diag::note_previous_definition);
4482     }
4483   }
4484 
4485   // If this redeclaration makes the variable inline, we may need to add it to
4486   // UndefinedButUsed.
4487   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4488       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4489     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4490                                            SourceLocation()));
4491 
4492   if (New->getTLSKind() != Old->getTLSKind()) {
4493     if (!Old->getTLSKind()) {
4494       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4495       Diag(OldLocation, PrevDiag);
4496     } else if (!New->getTLSKind()) {
4497       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4498       Diag(OldLocation, PrevDiag);
4499     } else {
4500       // Do not allow redeclaration to change the variable between requiring
4501       // static and dynamic initialization.
4502       // FIXME: GCC allows this, but uses the TLS keyword on the first
4503       // declaration to determine the kind. Do we need to be compatible here?
4504       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4505         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4506       Diag(OldLocation, PrevDiag);
4507     }
4508   }
4509 
4510   // C++ doesn't have tentative definitions, so go right ahead and check here.
4511   if (getLangOpts().CPlusPlus) {
4512     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4513         Old->getCanonicalDecl()->isConstexpr()) {
4514       // This definition won't be a definition any more once it's been merged.
4515       Diag(New->getLocation(),
4516            diag::warn_deprecated_redundant_constexpr_static_def);
4517     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4518       VarDecl *Def = Old->getDefinition();
4519       if (Def && checkVarDeclRedefinition(Def, New))
4520         return;
4521     }
4522   }
4523 
4524   if (haveIncompatibleLanguageLinkages(Old, New)) {
4525     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4526     Diag(OldLocation, PrevDiag);
4527     New->setInvalidDecl();
4528     return;
4529   }
4530 
4531   // Merge "used" flag.
4532   if (Old->getMostRecentDecl()->isUsed(false))
4533     New->setIsUsed();
4534 
4535   // Keep a chain of previous declarations.
4536   New->setPreviousDecl(Old);
4537   if (NewTemplate)
4538     NewTemplate->setPreviousDecl(OldTemplate);
4539 
4540   // Inherit access appropriately.
4541   New->setAccess(Old->getAccess());
4542   if (NewTemplate)
4543     NewTemplate->setAccess(New->getAccess());
4544 
4545   if (Old->isInline())
4546     New->setImplicitlyInline();
4547 }
4548 
4549 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4550   SourceManager &SrcMgr = getSourceManager();
4551   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4552   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4553   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4554   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4555   auto &HSI = PP.getHeaderSearchInfo();
4556   StringRef HdrFilename =
4557       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4558 
4559   auto noteFromModuleOrInclude = [&](Module *Mod,
4560                                      SourceLocation IncLoc) -> bool {
4561     // Redefinition errors with modules are common with non modular mapped
4562     // headers, example: a non-modular header H in module A that also gets
4563     // included directly in a TU. Pointing twice to the same header/definition
4564     // is confusing, try to get better diagnostics when modules is on.
4565     if (IncLoc.isValid()) {
4566       if (Mod) {
4567         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4568             << HdrFilename.str() << Mod->getFullModuleName();
4569         if (!Mod->DefinitionLoc.isInvalid())
4570           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4571               << Mod->getFullModuleName();
4572       } else {
4573         Diag(IncLoc, diag::note_redefinition_include_same_file)
4574             << HdrFilename.str();
4575       }
4576       return true;
4577     }
4578 
4579     return false;
4580   };
4581 
4582   // Is it the same file and same offset? Provide more information on why
4583   // this leads to a redefinition error.
4584   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4585     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4586     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4587     bool EmittedDiag =
4588         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4589     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4590 
4591     // If the header has no guards, emit a note suggesting one.
4592     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4593       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4594 
4595     if (EmittedDiag)
4596       return;
4597   }
4598 
4599   // Redefinition coming from different files or couldn't do better above.
4600   if (Old->getLocation().isValid())
4601     Diag(Old->getLocation(), diag::note_previous_definition);
4602 }
4603 
4604 /// We've just determined that \p Old and \p New both appear to be definitions
4605 /// of the same variable. Either diagnose or fix the problem.
4606 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4607   if (!hasVisibleDefinition(Old) &&
4608       (New->getFormalLinkage() == InternalLinkage ||
4609        New->isInline() ||
4610        New->getDescribedVarTemplate() ||
4611        New->getNumTemplateParameterLists() ||
4612        New->getDeclContext()->isDependentContext())) {
4613     // The previous definition is hidden, and multiple definitions are
4614     // permitted (in separate TUs). Demote this to a declaration.
4615     New->demoteThisDefinitionToDeclaration();
4616 
4617     // Make the canonical definition visible.
4618     if (auto *OldTD = Old->getDescribedVarTemplate())
4619       makeMergedDefinitionVisible(OldTD);
4620     makeMergedDefinitionVisible(Old);
4621     return false;
4622   } else {
4623     Diag(New->getLocation(), diag::err_redefinition) << New;
4624     notePreviousDefinition(Old, New->getLocation());
4625     New->setInvalidDecl();
4626     return true;
4627   }
4628 }
4629 
4630 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4631 /// no declarator (e.g. "struct foo;") is parsed.
4632 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4633                                        DeclSpec &DS,
4634                                        const ParsedAttributesView &DeclAttrs,
4635                                        RecordDecl *&AnonRecord) {
4636   return ParsedFreeStandingDeclSpec(
4637       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4638 }
4639 
4640 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4641 // disambiguate entities defined in different scopes.
4642 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4643 // compatibility.
4644 // We will pick our mangling number depending on which version of MSVC is being
4645 // targeted.
4646 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4647   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4648              ? S->getMSCurManglingNumber()
4649              : S->getMSLastManglingNumber();
4650 }
4651 
4652 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4653   if (!Context.getLangOpts().CPlusPlus)
4654     return;
4655 
4656   if (isa<CXXRecordDecl>(Tag->getParent())) {
4657     // If this tag is the direct child of a class, number it if
4658     // it is anonymous.
4659     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4660       return;
4661     MangleNumberingContext &MCtx =
4662         Context.getManglingNumberContext(Tag->getParent());
4663     Context.setManglingNumber(
4664         Tag, MCtx.getManglingNumber(
4665                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4666     return;
4667   }
4668 
4669   // If this tag isn't a direct child of a class, number it if it is local.
4670   MangleNumberingContext *MCtx;
4671   Decl *ManglingContextDecl;
4672   std::tie(MCtx, ManglingContextDecl) =
4673       getCurrentMangleNumberContext(Tag->getDeclContext());
4674   if (MCtx) {
4675     Context.setManglingNumber(
4676         Tag, MCtx->getManglingNumber(
4677                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4678   }
4679 }
4680 
4681 namespace {
4682 struct NonCLikeKind {
4683   enum {
4684     None,
4685     BaseClass,
4686     DefaultMemberInit,
4687     Lambda,
4688     Friend,
4689     OtherMember,
4690     Invalid,
4691   } Kind = None;
4692   SourceRange Range;
4693 
4694   explicit operator bool() { return Kind != None; }
4695 };
4696 }
4697 
4698 /// Determine whether a class is C-like, according to the rules of C++
4699 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4700 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4701   if (RD->isInvalidDecl())
4702     return {NonCLikeKind::Invalid, {}};
4703 
4704   // C++ [dcl.typedef]p9: [P1766R1]
4705   //   An unnamed class with a typedef name for linkage purposes shall not
4706   //
4707   //    -- have any base classes
4708   if (RD->getNumBases())
4709     return {NonCLikeKind::BaseClass,
4710             SourceRange(RD->bases_begin()->getBeginLoc(),
4711                         RD->bases_end()[-1].getEndLoc())};
4712   bool Invalid = false;
4713   for (Decl *D : RD->decls()) {
4714     // Don't complain about things we already diagnosed.
4715     if (D->isInvalidDecl()) {
4716       Invalid = true;
4717       continue;
4718     }
4719 
4720     //  -- have any [...] default member initializers
4721     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4722       if (FD->hasInClassInitializer()) {
4723         auto *Init = FD->getInClassInitializer();
4724         return {NonCLikeKind::DefaultMemberInit,
4725                 Init ? Init->getSourceRange() : D->getSourceRange()};
4726       }
4727       continue;
4728     }
4729 
4730     // FIXME: We don't allow friend declarations. This violates the wording of
4731     // P1766, but not the intent.
4732     if (isa<FriendDecl>(D))
4733       return {NonCLikeKind::Friend, D->getSourceRange()};
4734 
4735     //  -- declare any members other than non-static data members, member
4736     //     enumerations, or member classes,
4737     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4738         isa<EnumDecl>(D))
4739       continue;
4740     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4741     if (!MemberRD) {
4742       if (D->isImplicit())
4743         continue;
4744       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4745     }
4746 
4747     //  -- contain a lambda-expression,
4748     if (MemberRD->isLambda())
4749       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4750 
4751     //  and all member classes shall also satisfy these requirements
4752     //  (recursively).
4753     if (MemberRD->isThisDeclarationADefinition()) {
4754       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4755         return Kind;
4756     }
4757   }
4758 
4759   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4760 }
4761 
4762 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4763                                         TypedefNameDecl *NewTD) {
4764   if (TagFromDeclSpec->isInvalidDecl())
4765     return;
4766 
4767   // Do nothing if the tag already has a name for linkage purposes.
4768   if (TagFromDeclSpec->hasNameForLinkage())
4769     return;
4770 
4771   // A well-formed anonymous tag must always be a TUK_Definition.
4772   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4773 
4774   // The type must match the tag exactly;  no qualifiers allowed.
4775   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4776                            Context.getTagDeclType(TagFromDeclSpec))) {
4777     if (getLangOpts().CPlusPlus)
4778       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4779     return;
4780   }
4781 
4782   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4783   //   An unnamed class with a typedef name for linkage purposes shall [be
4784   //   C-like].
4785   //
4786   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4787   // shouldn't happen, but there are constructs that the language rule doesn't
4788   // disallow for which we can't reasonably avoid computing linkage early.
4789   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4790   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4791                              : NonCLikeKind();
4792   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4793   if (NonCLike || ChangesLinkage) {
4794     if (NonCLike.Kind == NonCLikeKind::Invalid)
4795       return;
4796 
4797     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4798     if (ChangesLinkage) {
4799       // If the linkage changes, we can't accept this as an extension.
4800       if (NonCLike.Kind == NonCLikeKind::None)
4801         DiagID = diag::err_typedef_changes_linkage;
4802       else
4803         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4804     }
4805 
4806     SourceLocation FixitLoc =
4807         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4808     llvm::SmallString<40> TextToInsert;
4809     TextToInsert += ' ';
4810     TextToInsert += NewTD->getIdentifier()->getName();
4811 
4812     Diag(FixitLoc, DiagID)
4813       << isa<TypeAliasDecl>(NewTD)
4814       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4815     if (NonCLike.Kind != NonCLikeKind::None) {
4816       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4817         << NonCLike.Kind - 1 << NonCLike.Range;
4818     }
4819     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4820       << NewTD << isa<TypeAliasDecl>(NewTD);
4821 
4822     if (ChangesLinkage)
4823       return;
4824   }
4825 
4826   // Otherwise, set this as the anon-decl typedef for the tag.
4827   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4828 }
4829 
4830 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4831   switch (T) {
4832   case DeclSpec::TST_class:
4833     return 0;
4834   case DeclSpec::TST_struct:
4835     return 1;
4836   case DeclSpec::TST_interface:
4837     return 2;
4838   case DeclSpec::TST_union:
4839     return 3;
4840   case DeclSpec::TST_enum:
4841     return 4;
4842   default:
4843     llvm_unreachable("unexpected type specifier");
4844   }
4845 }
4846 
4847 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4848 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4849 /// parameters to cope with template friend declarations.
4850 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4851                                        DeclSpec &DS,
4852                                        const ParsedAttributesView &DeclAttrs,
4853                                        MultiTemplateParamsArg TemplateParams,
4854                                        bool IsExplicitInstantiation,
4855                                        RecordDecl *&AnonRecord) {
4856   Decl *TagD = nullptr;
4857   TagDecl *Tag = nullptr;
4858   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4859       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4860       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4861       DS.getTypeSpecType() == DeclSpec::TST_union ||
4862       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4863     TagD = DS.getRepAsDecl();
4864 
4865     if (!TagD) // We probably had an error
4866       return nullptr;
4867 
4868     // Note that the above type specs guarantee that the
4869     // type rep is a Decl, whereas in many of the others
4870     // it's a Type.
4871     if (isa<TagDecl>(TagD))
4872       Tag = cast<TagDecl>(TagD);
4873     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4874       Tag = CTD->getTemplatedDecl();
4875   }
4876 
4877   if (Tag) {
4878     handleTagNumbering(Tag, S);
4879     Tag->setFreeStanding();
4880     if (Tag->isInvalidDecl())
4881       return Tag;
4882   }
4883 
4884   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4885     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4886     // or incomplete types shall not be restrict-qualified."
4887     if (TypeQuals & DeclSpec::TQ_restrict)
4888       Diag(DS.getRestrictSpecLoc(),
4889            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4890            << DS.getSourceRange();
4891   }
4892 
4893   if (DS.isInlineSpecified())
4894     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4895         << getLangOpts().CPlusPlus17;
4896 
4897   if (DS.hasConstexprSpecifier()) {
4898     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4899     // and definitions of functions and variables.
4900     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4901     // the declaration of a function or function template
4902     if (Tag)
4903       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4904           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4905           << static_cast<int>(DS.getConstexprSpecifier());
4906     else
4907       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4908           << static_cast<int>(DS.getConstexprSpecifier());
4909     // Don't emit warnings after this error.
4910     return TagD;
4911   }
4912 
4913   DiagnoseFunctionSpecifiers(DS);
4914 
4915   if (DS.isFriendSpecified()) {
4916     // If we're dealing with a decl but not a TagDecl, assume that
4917     // whatever routines created it handled the friendship aspect.
4918     if (TagD && !Tag)
4919       return nullptr;
4920     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4921   }
4922 
4923   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4924   bool IsExplicitSpecialization =
4925     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4926   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4927       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4928       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4929     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4930     // nested-name-specifier unless it is an explicit instantiation
4931     // or an explicit specialization.
4932     //
4933     // FIXME: We allow class template partial specializations here too, per the
4934     // obvious intent of DR1819.
4935     //
4936     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4937     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4938         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4939     return nullptr;
4940   }
4941 
4942   // Track whether this decl-specifier declares anything.
4943   bool DeclaresAnything = true;
4944 
4945   // Handle anonymous struct definitions.
4946   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4947     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4948         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4949       if (getLangOpts().CPlusPlus ||
4950           Record->getDeclContext()->isRecord()) {
4951         // If CurContext is a DeclContext that can contain statements,
4952         // RecursiveASTVisitor won't visit the decls that
4953         // BuildAnonymousStructOrUnion() will put into CurContext.
4954         // Also store them here so that they can be part of the
4955         // DeclStmt that gets created in this case.
4956         // FIXME: Also return the IndirectFieldDecls created by
4957         // BuildAnonymousStructOr union, for the same reason?
4958         if (CurContext->isFunctionOrMethod())
4959           AnonRecord = Record;
4960         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4961                                            Context.getPrintingPolicy());
4962       }
4963 
4964       DeclaresAnything = false;
4965     }
4966   }
4967 
4968   // C11 6.7.2.1p2:
4969   //   A struct-declaration that does not declare an anonymous structure or
4970   //   anonymous union shall contain a struct-declarator-list.
4971   //
4972   // This rule also existed in C89 and C99; the grammar for struct-declaration
4973   // did not permit a struct-declaration without a struct-declarator-list.
4974   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4975       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4976     // Check for Microsoft C extension: anonymous struct/union member.
4977     // Handle 2 kinds of anonymous struct/union:
4978     //   struct STRUCT;
4979     //   union UNION;
4980     // and
4981     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4982     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4983     if ((Tag && Tag->getDeclName()) ||
4984         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4985       RecordDecl *Record = nullptr;
4986       if (Tag)
4987         Record = dyn_cast<RecordDecl>(Tag);
4988       else if (const RecordType *RT =
4989                    DS.getRepAsType().get()->getAsStructureType())
4990         Record = RT->getDecl();
4991       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4992         Record = UT->getDecl();
4993 
4994       if (Record && getLangOpts().MicrosoftExt) {
4995         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4996             << Record->isUnion() << DS.getSourceRange();
4997         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4998       }
4999 
5000       DeclaresAnything = false;
5001     }
5002   }
5003 
5004   // Skip all the checks below if we have a type error.
5005   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5006       (TagD && TagD->isInvalidDecl()))
5007     return TagD;
5008 
5009   if (getLangOpts().CPlusPlus &&
5010       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5011     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5012       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5013           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5014         DeclaresAnything = false;
5015 
5016   if (!DS.isMissingDeclaratorOk()) {
5017     // Customize diagnostic for a typedef missing a name.
5018     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5019       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5020           << DS.getSourceRange();
5021     else
5022       DeclaresAnything = false;
5023   }
5024 
5025   if (DS.isModulePrivateSpecified() &&
5026       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5027     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5028       << Tag->getTagKind()
5029       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5030 
5031   ActOnDocumentableDecl(TagD);
5032 
5033   // C 6.7/2:
5034   //   A declaration [...] shall declare at least a declarator [...], a tag,
5035   //   or the members of an enumeration.
5036   // C++ [dcl.dcl]p3:
5037   //   [If there are no declarators], and except for the declaration of an
5038   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5039   //   names into the program, or shall redeclare a name introduced by a
5040   //   previous declaration.
5041   if (!DeclaresAnything) {
5042     // In C, we allow this as a (popular) extension / bug. Don't bother
5043     // producing further diagnostics for redundant qualifiers after this.
5044     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5045                                ? diag::err_no_declarators
5046                                : diag::ext_no_declarators)
5047         << DS.getSourceRange();
5048     return TagD;
5049   }
5050 
5051   // C++ [dcl.stc]p1:
5052   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5053   //   init-declarator-list of the declaration shall not be empty.
5054   // C++ [dcl.fct.spec]p1:
5055   //   If a cv-qualifier appears in a decl-specifier-seq, the
5056   //   init-declarator-list of the declaration shall not be empty.
5057   //
5058   // Spurious qualifiers here appear to be valid in C.
5059   unsigned DiagID = diag::warn_standalone_specifier;
5060   if (getLangOpts().CPlusPlus)
5061     DiagID = diag::ext_standalone_specifier;
5062 
5063   // Note that a linkage-specification sets a storage class, but
5064   // 'extern "C" struct foo;' is actually valid and not theoretically
5065   // useless.
5066   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5067     if (SCS == DeclSpec::SCS_mutable)
5068       // Since mutable is not a viable storage class specifier in C, there is
5069       // no reason to treat it as an extension. Instead, diagnose as an error.
5070       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5071     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5072       Diag(DS.getStorageClassSpecLoc(), DiagID)
5073         << DeclSpec::getSpecifierName(SCS);
5074   }
5075 
5076   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5077     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5078       << DeclSpec::getSpecifierName(TSCS);
5079   if (DS.getTypeQualifiers()) {
5080     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5081       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5082     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5083       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5084     // Restrict is covered above.
5085     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5086       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5087     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5088       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5089   }
5090 
5091   // Warn about ignored type attributes, for example:
5092   // __attribute__((aligned)) struct A;
5093   // Attributes should be placed after tag to apply to type declaration.
5094   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5095     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5096     if (TypeSpecType == DeclSpec::TST_class ||
5097         TypeSpecType == DeclSpec::TST_struct ||
5098         TypeSpecType == DeclSpec::TST_interface ||
5099         TypeSpecType == DeclSpec::TST_union ||
5100         TypeSpecType == DeclSpec::TST_enum) {
5101       for (const ParsedAttr &AL : DS.getAttributes())
5102         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5103             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5104       for (const ParsedAttr &AL : DeclAttrs)
5105         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5106             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5107     }
5108   }
5109 
5110   return TagD;
5111 }
5112 
5113 /// We are trying to inject an anonymous member into the given scope;
5114 /// check if there's an existing declaration that can't be overloaded.
5115 ///
5116 /// \return true if this is a forbidden redeclaration
5117 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5118                                          Scope *S,
5119                                          DeclContext *Owner,
5120                                          DeclarationName Name,
5121                                          SourceLocation NameLoc,
5122                                          bool IsUnion) {
5123   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5124                  Sema::ForVisibleRedeclaration);
5125   if (!SemaRef.LookupName(R, S)) return false;
5126 
5127   // Pick a representative declaration.
5128   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5129   assert(PrevDecl && "Expected a non-null Decl");
5130 
5131   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5132     return false;
5133 
5134   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5135     << IsUnion << Name;
5136   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5137 
5138   return true;
5139 }
5140 
5141 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5142 /// anonymous struct or union AnonRecord into the owning context Owner
5143 /// and scope S. This routine will be invoked just after we realize
5144 /// that an unnamed union or struct is actually an anonymous union or
5145 /// struct, e.g.,
5146 ///
5147 /// @code
5148 /// union {
5149 ///   int i;
5150 ///   float f;
5151 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5152 ///    // f into the surrounding scope.x
5153 /// @endcode
5154 ///
5155 /// This routine is recursive, injecting the names of nested anonymous
5156 /// structs/unions into the owning context and scope as well.
5157 static bool
5158 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5159                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5160                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5161   bool Invalid = false;
5162 
5163   // Look every FieldDecl and IndirectFieldDecl with a name.
5164   for (auto *D : AnonRecord->decls()) {
5165     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5166         cast<NamedDecl>(D)->getDeclName()) {
5167       ValueDecl *VD = cast<ValueDecl>(D);
5168       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5169                                        VD->getLocation(),
5170                                        AnonRecord->isUnion())) {
5171         // C++ [class.union]p2:
5172         //   The names of the members of an anonymous union shall be
5173         //   distinct from the names of any other entity in the
5174         //   scope in which the anonymous union is declared.
5175         Invalid = true;
5176       } else {
5177         // C++ [class.union]p2:
5178         //   For the purpose of name lookup, after the anonymous union
5179         //   definition, the members of the anonymous union are
5180         //   considered to have been defined in the scope in which the
5181         //   anonymous union is declared.
5182         unsigned OldChainingSize = Chaining.size();
5183         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5184           Chaining.append(IF->chain_begin(), IF->chain_end());
5185         else
5186           Chaining.push_back(VD);
5187 
5188         assert(Chaining.size() >= 2);
5189         NamedDecl **NamedChain =
5190           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5191         for (unsigned i = 0; i < Chaining.size(); i++)
5192           NamedChain[i] = Chaining[i];
5193 
5194         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5195             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5196             VD->getType(), {NamedChain, Chaining.size()});
5197 
5198         for (const auto *Attr : VD->attrs())
5199           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5200 
5201         IndirectField->setAccess(AS);
5202         IndirectField->setImplicit();
5203         SemaRef.PushOnScopeChains(IndirectField, S);
5204 
5205         // That includes picking up the appropriate access specifier.
5206         if (AS != AS_none) IndirectField->setAccess(AS);
5207 
5208         Chaining.resize(OldChainingSize);
5209       }
5210     }
5211   }
5212 
5213   return Invalid;
5214 }
5215 
5216 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5217 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5218 /// illegal input values are mapped to SC_None.
5219 static StorageClass
5220 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5221   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5222   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5223          "Parser allowed 'typedef' as storage class VarDecl.");
5224   switch (StorageClassSpec) {
5225   case DeclSpec::SCS_unspecified:    return SC_None;
5226   case DeclSpec::SCS_extern:
5227     if (DS.isExternInLinkageSpec())
5228       return SC_None;
5229     return SC_Extern;
5230   case DeclSpec::SCS_static:         return SC_Static;
5231   case DeclSpec::SCS_auto:           return SC_Auto;
5232   case DeclSpec::SCS_register:       return SC_Register;
5233   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5234     // Illegal SCSs map to None: error reporting is up to the caller.
5235   case DeclSpec::SCS_mutable:        // Fall through.
5236   case DeclSpec::SCS_typedef:        return SC_None;
5237   }
5238   llvm_unreachable("unknown storage class specifier");
5239 }
5240 
5241 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5242   assert(Record->hasInClassInitializer());
5243 
5244   for (const auto *I : Record->decls()) {
5245     const auto *FD = dyn_cast<FieldDecl>(I);
5246     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5247       FD = IFD->getAnonField();
5248     if (FD && FD->hasInClassInitializer())
5249       return FD->getLocation();
5250   }
5251 
5252   llvm_unreachable("couldn't find in-class initializer");
5253 }
5254 
5255 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5256                                       SourceLocation DefaultInitLoc) {
5257   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5258     return;
5259 
5260   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5261   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5262 }
5263 
5264 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5265                                       CXXRecordDecl *AnonUnion) {
5266   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5267     return;
5268 
5269   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5270 }
5271 
5272 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5273 /// anonymous structure or union. Anonymous unions are a C++ feature
5274 /// (C++ [class.union]) and a C11 feature; anonymous structures
5275 /// are a C11 feature and GNU C++ extension.
5276 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5277                                         AccessSpecifier AS,
5278                                         RecordDecl *Record,
5279                                         const PrintingPolicy &Policy) {
5280   DeclContext *Owner = Record->getDeclContext();
5281 
5282   // Diagnose whether this anonymous struct/union is an extension.
5283   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5284     Diag(Record->getLocation(), diag::ext_anonymous_union);
5285   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5286     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5287   else if (!Record->isUnion() && !getLangOpts().C11)
5288     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5289 
5290   // C and C++ require different kinds of checks for anonymous
5291   // structs/unions.
5292   bool Invalid = false;
5293   if (getLangOpts().CPlusPlus) {
5294     const char *PrevSpec = nullptr;
5295     if (Record->isUnion()) {
5296       // C++ [class.union]p6:
5297       // C++17 [class.union.anon]p2:
5298       //   Anonymous unions declared in a named namespace or in the
5299       //   global namespace shall be declared static.
5300       unsigned DiagID;
5301       DeclContext *OwnerScope = Owner->getRedeclContext();
5302       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5303           (OwnerScope->isTranslationUnit() ||
5304            (OwnerScope->isNamespace() &&
5305             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5306         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5307           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5308 
5309         // Recover by adding 'static'.
5310         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5311                                PrevSpec, DiagID, Policy);
5312       }
5313       // C++ [class.union]p6:
5314       //   A storage class is not allowed in a declaration of an
5315       //   anonymous union in a class scope.
5316       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5317                isa<RecordDecl>(Owner)) {
5318         Diag(DS.getStorageClassSpecLoc(),
5319              diag::err_anonymous_union_with_storage_spec)
5320           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5321 
5322         // Recover by removing the storage specifier.
5323         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5324                                SourceLocation(),
5325                                PrevSpec, DiagID, Context.getPrintingPolicy());
5326       }
5327     }
5328 
5329     // Ignore const/volatile/restrict qualifiers.
5330     if (DS.getTypeQualifiers()) {
5331       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5332         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5333           << Record->isUnion() << "const"
5334           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5335       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5336         Diag(DS.getVolatileSpecLoc(),
5337              diag::ext_anonymous_struct_union_qualified)
5338           << Record->isUnion() << "volatile"
5339           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5340       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5341         Diag(DS.getRestrictSpecLoc(),
5342              diag::ext_anonymous_struct_union_qualified)
5343           << Record->isUnion() << "restrict"
5344           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5345       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5346         Diag(DS.getAtomicSpecLoc(),
5347              diag::ext_anonymous_struct_union_qualified)
5348           << Record->isUnion() << "_Atomic"
5349           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5350       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5351         Diag(DS.getUnalignedSpecLoc(),
5352              diag::ext_anonymous_struct_union_qualified)
5353           << Record->isUnion() << "__unaligned"
5354           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5355 
5356       DS.ClearTypeQualifiers();
5357     }
5358 
5359     // C++ [class.union]p2:
5360     //   The member-specification of an anonymous union shall only
5361     //   define non-static data members. [Note: nested types and
5362     //   functions cannot be declared within an anonymous union. ]
5363     for (auto *Mem : Record->decls()) {
5364       // Ignore invalid declarations; we already diagnosed them.
5365       if (Mem->isInvalidDecl())
5366         continue;
5367 
5368       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5369         // C++ [class.union]p3:
5370         //   An anonymous union shall not have private or protected
5371         //   members (clause 11).
5372         assert(FD->getAccess() != AS_none);
5373         if (FD->getAccess() != AS_public) {
5374           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5375             << Record->isUnion() << (FD->getAccess() == AS_protected);
5376           Invalid = true;
5377         }
5378 
5379         // C++ [class.union]p1
5380         //   An object of a class with a non-trivial constructor, a non-trivial
5381         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5382         //   assignment operator cannot be a member of a union, nor can an
5383         //   array of such objects.
5384         if (CheckNontrivialField(FD))
5385           Invalid = true;
5386       } else if (Mem->isImplicit()) {
5387         // Any implicit members are fine.
5388       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5389         // This is a type that showed up in an
5390         // elaborated-type-specifier inside the anonymous struct or
5391         // union, but which actually declares a type outside of the
5392         // anonymous struct or union. It's okay.
5393       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5394         if (!MemRecord->isAnonymousStructOrUnion() &&
5395             MemRecord->getDeclName()) {
5396           // Visual C++ allows type definition in anonymous struct or union.
5397           if (getLangOpts().MicrosoftExt)
5398             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5399               << Record->isUnion();
5400           else {
5401             // This is a nested type declaration.
5402             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5403               << Record->isUnion();
5404             Invalid = true;
5405           }
5406         } else {
5407           // This is an anonymous type definition within another anonymous type.
5408           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5409           // not part of standard C++.
5410           Diag(MemRecord->getLocation(),
5411                diag::ext_anonymous_record_with_anonymous_type)
5412             << Record->isUnion();
5413         }
5414       } else if (isa<AccessSpecDecl>(Mem)) {
5415         // Any access specifier is fine.
5416       } else if (isa<StaticAssertDecl>(Mem)) {
5417         // In C++1z, static_assert declarations are also fine.
5418       } else {
5419         // We have something that isn't a non-static data
5420         // member. Complain about it.
5421         unsigned DK = diag::err_anonymous_record_bad_member;
5422         if (isa<TypeDecl>(Mem))
5423           DK = diag::err_anonymous_record_with_type;
5424         else if (isa<FunctionDecl>(Mem))
5425           DK = diag::err_anonymous_record_with_function;
5426         else if (isa<VarDecl>(Mem))
5427           DK = diag::err_anonymous_record_with_static;
5428 
5429         // Visual C++ allows type definition in anonymous struct or union.
5430         if (getLangOpts().MicrosoftExt &&
5431             DK == diag::err_anonymous_record_with_type)
5432           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5433             << Record->isUnion();
5434         else {
5435           Diag(Mem->getLocation(), DK) << Record->isUnion();
5436           Invalid = true;
5437         }
5438       }
5439     }
5440 
5441     // C++11 [class.union]p8 (DR1460):
5442     //   At most one variant member of a union may have a
5443     //   brace-or-equal-initializer.
5444     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5445         Owner->isRecord())
5446       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5447                                 cast<CXXRecordDecl>(Record));
5448   }
5449 
5450   if (!Record->isUnion() && !Owner->isRecord()) {
5451     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5452       << getLangOpts().CPlusPlus;
5453     Invalid = true;
5454   }
5455 
5456   // C++ [dcl.dcl]p3:
5457   //   [If there are no declarators], and except for the declaration of an
5458   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5459   //   names into the program
5460   // C++ [class.mem]p2:
5461   //   each such member-declaration shall either declare at least one member
5462   //   name of the class or declare at least one unnamed bit-field
5463   //
5464   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5465   if (getLangOpts().CPlusPlus && Record->field_empty())
5466     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5467 
5468   // Mock up a declarator.
5469   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5470   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5471   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5472 
5473   // Create a declaration for this anonymous struct/union.
5474   NamedDecl *Anon = nullptr;
5475   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5476     Anon = FieldDecl::Create(
5477         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5478         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5479         /*BitWidth=*/nullptr, /*Mutable=*/false,
5480         /*InitStyle=*/ICIS_NoInit);
5481     Anon->setAccess(AS);
5482     ProcessDeclAttributes(S, Anon, Dc);
5483 
5484     if (getLangOpts().CPlusPlus)
5485       FieldCollector->Add(cast<FieldDecl>(Anon));
5486   } else {
5487     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5488     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5489     if (SCSpec == DeclSpec::SCS_mutable) {
5490       // mutable can only appear on non-static class members, so it's always
5491       // an error here
5492       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5493       Invalid = true;
5494       SC = SC_None;
5495     }
5496 
5497     assert(DS.getAttributes().empty() && "No attribute expected");
5498     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5499                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5500                            Context.getTypeDeclType(Record), TInfo, SC);
5501 
5502     // Default-initialize the implicit variable. This initialization will be
5503     // trivial in almost all cases, except if a union member has an in-class
5504     // initializer:
5505     //   union { int n = 0; };
5506     ActOnUninitializedDecl(Anon);
5507   }
5508   Anon->setImplicit();
5509 
5510   // Mark this as an anonymous struct/union type.
5511   Record->setAnonymousStructOrUnion(true);
5512 
5513   // Add the anonymous struct/union object to the current
5514   // context. We'll be referencing this object when we refer to one of
5515   // its members.
5516   Owner->addDecl(Anon);
5517 
5518   // Inject the members of the anonymous struct/union into the owning
5519   // context and into the identifier resolver chain for name lookup
5520   // purposes.
5521   SmallVector<NamedDecl*, 2> Chain;
5522   Chain.push_back(Anon);
5523 
5524   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5525     Invalid = true;
5526 
5527   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5528     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5529       MangleNumberingContext *MCtx;
5530       Decl *ManglingContextDecl;
5531       std::tie(MCtx, ManglingContextDecl) =
5532           getCurrentMangleNumberContext(NewVD->getDeclContext());
5533       if (MCtx) {
5534         Context.setManglingNumber(
5535             NewVD, MCtx->getManglingNumber(
5536                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5537         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5538       }
5539     }
5540   }
5541 
5542   if (Invalid)
5543     Anon->setInvalidDecl();
5544 
5545   return Anon;
5546 }
5547 
5548 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5549 /// Microsoft C anonymous structure.
5550 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5551 /// Example:
5552 ///
5553 /// struct A { int a; };
5554 /// struct B { struct A; int b; };
5555 ///
5556 /// void foo() {
5557 ///   B var;
5558 ///   var.a = 3;
5559 /// }
5560 ///
5561 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5562                                            RecordDecl *Record) {
5563   assert(Record && "expected a record!");
5564 
5565   // Mock up a declarator.
5566   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5567   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5568   assert(TInfo && "couldn't build declarator info for anonymous struct");
5569 
5570   auto *ParentDecl = cast<RecordDecl>(CurContext);
5571   QualType RecTy = Context.getTypeDeclType(Record);
5572 
5573   // Create a declaration for this anonymous struct.
5574   NamedDecl *Anon =
5575       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5576                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5577                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5578                         /*InitStyle=*/ICIS_NoInit);
5579   Anon->setImplicit();
5580 
5581   // Add the anonymous struct object to the current context.
5582   CurContext->addDecl(Anon);
5583 
5584   // Inject the members of the anonymous struct into the current
5585   // context and into the identifier resolver chain for name lookup
5586   // purposes.
5587   SmallVector<NamedDecl*, 2> Chain;
5588   Chain.push_back(Anon);
5589 
5590   RecordDecl *RecordDef = Record->getDefinition();
5591   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5592                                diag::err_field_incomplete_or_sizeless) ||
5593       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5594                                           AS_none, Chain)) {
5595     Anon->setInvalidDecl();
5596     ParentDecl->setInvalidDecl();
5597   }
5598 
5599   return Anon;
5600 }
5601 
5602 /// GetNameForDeclarator - Determine the full declaration name for the
5603 /// given Declarator.
5604 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5605   return GetNameFromUnqualifiedId(D.getName());
5606 }
5607 
5608 /// Retrieves the declaration name from a parsed unqualified-id.
5609 DeclarationNameInfo
5610 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5611   DeclarationNameInfo NameInfo;
5612   NameInfo.setLoc(Name.StartLocation);
5613 
5614   switch (Name.getKind()) {
5615 
5616   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5617   case UnqualifiedIdKind::IK_Identifier:
5618     NameInfo.setName(Name.Identifier);
5619     return NameInfo;
5620 
5621   case UnqualifiedIdKind::IK_DeductionGuideName: {
5622     // C++ [temp.deduct.guide]p3:
5623     //   The simple-template-id shall name a class template specialization.
5624     //   The template-name shall be the same identifier as the template-name
5625     //   of the simple-template-id.
5626     // These together intend to imply that the template-name shall name a
5627     // class template.
5628     // FIXME: template<typename T> struct X {};
5629     //        template<typename T> using Y = X<T>;
5630     //        Y(int) -> Y<int>;
5631     //   satisfies these rules but does not name a class template.
5632     TemplateName TN = Name.TemplateName.get().get();
5633     auto *Template = TN.getAsTemplateDecl();
5634     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5635       Diag(Name.StartLocation,
5636            diag::err_deduction_guide_name_not_class_template)
5637         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5638       if (Template)
5639         Diag(Template->getLocation(), diag::note_template_decl_here);
5640       return DeclarationNameInfo();
5641     }
5642 
5643     NameInfo.setName(
5644         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5645     return NameInfo;
5646   }
5647 
5648   case UnqualifiedIdKind::IK_OperatorFunctionId:
5649     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5650                                            Name.OperatorFunctionId.Operator));
5651     NameInfo.setCXXOperatorNameRange(SourceRange(
5652         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5653     return NameInfo;
5654 
5655   case UnqualifiedIdKind::IK_LiteralOperatorId:
5656     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5657                                                            Name.Identifier));
5658     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5659     return NameInfo;
5660 
5661   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5662     TypeSourceInfo *TInfo;
5663     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5664     if (Ty.isNull())
5665       return DeclarationNameInfo();
5666     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5667                                                Context.getCanonicalType(Ty)));
5668     NameInfo.setNamedTypeInfo(TInfo);
5669     return NameInfo;
5670   }
5671 
5672   case UnqualifiedIdKind::IK_ConstructorName: {
5673     TypeSourceInfo *TInfo;
5674     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5675     if (Ty.isNull())
5676       return DeclarationNameInfo();
5677     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5678                                               Context.getCanonicalType(Ty)));
5679     NameInfo.setNamedTypeInfo(TInfo);
5680     return NameInfo;
5681   }
5682 
5683   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5684     // In well-formed code, we can only have a constructor
5685     // template-id that refers to the current context, so go there
5686     // to find the actual type being constructed.
5687     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5688     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5689       return DeclarationNameInfo();
5690 
5691     // Determine the type of the class being constructed.
5692     QualType CurClassType = Context.getTypeDeclType(CurClass);
5693 
5694     // FIXME: Check two things: that the template-id names the same type as
5695     // CurClassType, and that the template-id does not occur when the name
5696     // was qualified.
5697 
5698     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5699                                     Context.getCanonicalType(CurClassType)));
5700     // FIXME: should we retrieve TypeSourceInfo?
5701     NameInfo.setNamedTypeInfo(nullptr);
5702     return NameInfo;
5703   }
5704 
5705   case UnqualifiedIdKind::IK_DestructorName: {
5706     TypeSourceInfo *TInfo;
5707     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5708     if (Ty.isNull())
5709       return DeclarationNameInfo();
5710     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5711                                               Context.getCanonicalType(Ty)));
5712     NameInfo.setNamedTypeInfo(TInfo);
5713     return NameInfo;
5714   }
5715 
5716   case UnqualifiedIdKind::IK_TemplateId: {
5717     TemplateName TName = Name.TemplateId->Template.get();
5718     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5719     return Context.getNameForTemplate(TName, TNameLoc);
5720   }
5721 
5722   } // switch (Name.getKind())
5723 
5724   llvm_unreachable("Unknown name kind");
5725 }
5726 
5727 static QualType getCoreType(QualType Ty) {
5728   do {
5729     if (Ty->isPointerType() || Ty->isReferenceType())
5730       Ty = Ty->getPointeeType();
5731     else if (Ty->isArrayType())
5732       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5733     else
5734       return Ty.withoutLocalFastQualifiers();
5735   } while (true);
5736 }
5737 
5738 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5739 /// and Definition have "nearly" matching parameters. This heuristic is
5740 /// used to improve diagnostics in the case where an out-of-line function
5741 /// definition doesn't match any declaration within the class or namespace.
5742 /// Also sets Params to the list of indices to the parameters that differ
5743 /// between the declaration and the definition. If hasSimilarParameters
5744 /// returns true and Params is empty, then all of the parameters match.
5745 static bool hasSimilarParameters(ASTContext &Context,
5746                                      FunctionDecl *Declaration,
5747                                      FunctionDecl *Definition,
5748                                      SmallVectorImpl<unsigned> &Params) {
5749   Params.clear();
5750   if (Declaration->param_size() != Definition->param_size())
5751     return false;
5752   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5753     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5754     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5755 
5756     // The parameter types are identical
5757     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5758       continue;
5759 
5760     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5761     QualType DefParamBaseTy = getCoreType(DefParamTy);
5762     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5763     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5764 
5765     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5766         (DeclTyName && DeclTyName == DefTyName))
5767       Params.push_back(Idx);
5768     else  // The two parameters aren't even close
5769       return false;
5770   }
5771 
5772   return true;
5773 }
5774 
5775 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5776 /// declarator needs to be rebuilt in the current instantiation.
5777 /// Any bits of declarator which appear before the name are valid for
5778 /// consideration here.  That's specifically the type in the decl spec
5779 /// and the base type in any member-pointer chunks.
5780 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5781                                                     DeclarationName Name) {
5782   // The types we specifically need to rebuild are:
5783   //   - typenames, typeofs, and decltypes
5784   //   - types which will become injected class names
5785   // Of course, we also need to rebuild any type referencing such a
5786   // type.  It's safest to just say "dependent", but we call out a
5787   // few cases here.
5788 
5789   DeclSpec &DS = D.getMutableDeclSpec();
5790   switch (DS.getTypeSpecType()) {
5791   case DeclSpec::TST_typename:
5792   case DeclSpec::TST_typeofType:
5793   case DeclSpec::TST_underlyingType:
5794   case DeclSpec::TST_atomic: {
5795     // Grab the type from the parser.
5796     TypeSourceInfo *TSI = nullptr;
5797     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5798     if (T.isNull() || !T->isInstantiationDependentType()) break;
5799 
5800     // Make sure there's a type source info.  This isn't really much
5801     // of a waste; most dependent types should have type source info
5802     // attached already.
5803     if (!TSI)
5804       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5805 
5806     // Rebuild the type in the current instantiation.
5807     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5808     if (!TSI) return true;
5809 
5810     // Store the new type back in the decl spec.
5811     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5812     DS.UpdateTypeRep(LocType);
5813     break;
5814   }
5815 
5816   case DeclSpec::TST_decltype:
5817   case DeclSpec::TST_typeofExpr: {
5818     Expr *E = DS.getRepAsExpr();
5819     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5820     if (Result.isInvalid()) return true;
5821     DS.UpdateExprRep(Result.get());
5822     break;
5823   }
5824 
5825   default:
5826     // Nothing to do for these decl specs.
5827     break;
5828   }
5829 
5830   // It doesn't matter what order we do this in.
5831   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5832     DeclaratorChunk &Chunk = D.getTypeObject(I);
5833 
5834     // The only type information in the declarator which can come
5835     // before the declaration name is the base type of a member
5836     // pointer.
5837     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5838       continue;
5839 
5840     // Rebuild the scope specifier in-place.
5841     CXXScopeSpec &SS = Chunk.Mem.Scope();
5842     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5843       return true;
5844   }
5845 
5846   return false;
5847 }
5848 
5849 /// Returns true if the declaration is declared in a system header or from a
5850 /// system macro.
5851 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5852   return SM.isInSystemHeader(D->getLocation()) ||
5853          SM.isInSystemMacro(D->getLocation());
5854 }
5855 
5856 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5857   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5858   // of system decl.
5859   if (D->getPreviousDecl() || D->isImplicit())
5860     return;
5861   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5862   if (Status != ReservedIdentifierStatus::NotReserved &&
5863       !isFromSystemHeader(Context.getSourceManager(), D)) {
5864     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5865         << D << static_cast<int>(Status);
5866   }
5867 }
5868 
5869 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5870   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5871 
5872   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5873   // declaration only if the `bind_to_declaration` extension is set.
5874   SmallVector<FunctionDecl *, 4> Bases;
5875   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
5876     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
5877               implementation_extension_bind_to_declaration))
5878     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
5879         S, D, MultiTemplateParamsArg(), Bases);
5880 
5881   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5882 
5883   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5884       Dcl && Dcl->getDeclContext()->isFileContext())
5885     Dcl->setTopLevelDeclInObjCContainer();
5886 
5887   if (!Bases.empty())
5888     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
5889 
5890   return Dcl;
5891 }
5892 
5893 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5894 ///   If T is the name of a class, then each of the following shall have a
5895 ///   name different from T:
5896 ///     - every static data member of class T;
5897 ///     - every member function of class T
5898 ///     - every member of class T that is itself a type;
5899 /// \returns true if the declaration name violates these rules.
5900 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5901                                    DeclarationNameInfo NameInfo) {
5902   DeclarationName Name = NameInfo.getName();
5903 
5904   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5905   while (Record && Record->isAnonymousStructOrUnion())
5906     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5907   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5908     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5909     return true;
5910   }
5911 
5912   return false;
5913 }
5914 
5915 /// Diagnose a declaration whose declarator-id has the given
5916 /// nested-name-specifier.
5917 ///
5918 /// \param SS The nested-name-specifier of the declarator-id.
5919 ///
5920 /// \param DC The declaration context to which the nested-name-specifier
5921 /// resolves.
5922 ///
5923 /// \param Name The name of the entity being declared.
5924 ///
5925 /// \param Loc The location of the name of the entity being declared.
5926 ///
5927 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5928 /// we're declaring an explicit / partial specialization / instantiation.
5929 ///
5930 /// \returns true if we cannot safely recover from this error, false otherwise.
5931 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5932                                         DeclarationName Name,
5933                                         SourceLocation Loc, bool IsTemplateId) {
5934   DeclContext *Cur = CurContext;
5935   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5936     Cur = Cur->getParent();
5937 
5938   // If the user provided a superfluous scope specifier that refers back to the
5939   // class in which the entity is already declared, diagnose and ignore it.
5940   //
5941   // class X {
5942   //   void X::f();
5943   // };
5944   //
5945   // Note, it was once ill-formed to give redundant qualification in all
5946   // contexts, but that rule was removed by DR482.
5947   if (Cur->Equals(DC)) {
5948     if (Cur->isRecord()) {
5949       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5950                                       : diag::err_member_extra_qualification)
5951         << Name << FixItHint::CreateRemoval(SS.getRange());
5952       SS.clear();
5953     } else {
5954       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5955     }
5956     return false;
5957   }
5958 
5959   // Check whether the qualifying scope encloses the scope of the original
5960   // declaration. For a template-id, we perform the checks in
5961   // CheckTemplateSpecializationScope.
5962   if (!Cur->Encloses(DC) && !IsTemplateId) {
5963     if (Cur->isRecord())
5964       Diag(Loc, diag::err_member_qualification)
5965         << Name << SS.getRange();
5966     else if (isa<TranslationUnitDecl>(DC))
5967       Diag(Loc, diag::err_invalid_declarator_global_scope)
5968         << Name << SS.getRange();
5969     else if (isa<FunctionDecl>(Cur))
5970       Diag(Loc, diag::err_invalid_declarator_in_function)
5971         << Name << SS.getRange();
5972     else if (isa<BlockDecl>(Cur))
5973       Diag(Loc, diag::err_invalid_declarator_in_block)
5974         << Name << SS.getRange();
5975     else if (isa<ExportDecl>(Cur)) {
5976       if (!isa<NamespaceDecl>(DC))
5977         Diag(Loc, diag::err_export_non_namespace_scope_name)
5978             << Name << SS.getRange();
5979       else
5980         // The cases that DC is not NamespaceDecl should be handled in
5981         // CheckRedeclarationExported.
5982         return false;
5983     } else
5984       Diag(Loc, diag::err_invalid_declarator_scope)
5985       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5986 
5987     return true;
5988   }
5989 
5990   if (Cur->isRecord()) {
5991     // Cannot qualify members within a class.
5992     Diag(Loc, diag::err_member_qualification)
5993       << Name << SS.getRange();
5994     SS.clear();
5995 
5996     // C++ constructors and destructors with incorrect scopes can break
5997     // our AST invariants by having the wrong underlying types. If
5998     // that's the case, then drop this declaration entirely.
5999     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6000          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6001         !Context.hasSameType(Name.getCXXNameType(),
6002                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6003       return true;
6004 
6005     return false;
6006   }
6007 
6008   // C++11 [dcl.meaning]p1:
6009   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6010   //   not begin with a decltype-specifer"
6011   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6012   while (SpecLoc.getPrefix())
6013     SpecLoc = SpecLoc.getPrefix();
6014   if (isa_and_nonnull<DecltypeType>(
6015           SpecLoc.getNestedNameSpecifier()->getAsType()))
6016     Diag(Loc, diag::err_decltype_in_declarator)
6017       << SpecLoc.getTypeLoc().getSourceRange();
6018 
6019   return false;
6020 }
6021 
6022 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6023                                   MultiTemplateParamsArg TemplateParamLists) {
6024   // TODO: consider using NameInfo for diagnostic.
6025   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6026   DeclarationName Name = NameInfo.getName();
6027 
6028   // All of these full declarators require an identifier.  If it doesn't have
6029   // one, the ParsedFreeStandingDeclSpec action should be used.
6030   if (D.isDecompositionDeclarator()) {
6031     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6032   } else if (!Name) {
6033     if (!D.isInvalidType())  // Reject this if we think it is valid.
6034       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6035           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6036     return nullptr;
6037   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6038     return nullptr;
6039 
6040   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6041   // we find one that is.
6042   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6043          (S->getFlags() & Scope::TemplateParamScope) != 0)
6044     S = S->getParent();
6045 
6046   DeclContext *DC = CurContext;
6047   if (D.getCXXScopeSpec().isInvalid())
6048     D.setInvalidType();
6049   else if (D.getCXXScopeSpec().isSet()) {
6050     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6051                                         UPPC_DeclarationQualifier))
6052       return nullptr;
6053 
6054     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6055     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6056     if (!DC || isa<EnumDecl>(DC)) {
6057       // If we could not compute the declaration context, it's because the
6058       // declaration context is dependent but does not refer to a class,
6059       // class template, or class template partial specialization. Complain
6060       // and return early, to avoid the coming semantic disaster.
6061       Diag(D.getIdentifierLoc(),
6062            diag::err_template_qualified_declarator_no_match)
6063         << D.getCXXScopeSpec().getScopeRep()
6064         << D.getCXXScopeSpec().getRange();
6065       return nullptr;
6066     }
6067     bool IsDependentContext = DC->isDependentContext();
6068 
6069     if (!IsDependentContext &&
6070         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6071       return nullptr;
6072 
6073     // If a class is incomplete, do not parse entities inside it.
6074     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6075       Diag(D.getIdentifierLoc(),
6076            diag::err_member_def_undefined_record)
6077         << Name << DC << D.getCXXScopeSpec().getRange();
6078       return nullptr;
6079     }
6080     if (!D.getDeclSpec().isFriendSpecified()) {
6081       if (diagnoseQualifiedDeclaration(
6082               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6083               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6084         if (DC->isRecord())
6085           return nullptr;
6086 
6087         D.setInvalidType();
6088       }
6089     }
6090 
6091     // Check whether we need to rebuild the type of the given
6092     // declaration in the current instantiation.
6093     if (EnteringContext && IsDependentContext &&
6094         TemplateParamLists.size() != 0) {
6095       ContextRAII SavedContext(*this, DC);
6096       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6097         D.setInvalidType();
6098     }
6099   }
6100 
6101   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6102   QualType R = TInfo->getType();
6103 
6104   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6105                                       UPPC_DeclarationType))
6106     D.setInvalidType();
6107 
6108   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6109                         forRedeclarationInCurContext());
6110 
6111   // See if this is a redefinition of a variable in the same scope.
6112   if (!D.getCXXScopeSpec().isSet()) {
6113     bool IsLinkageLookup = false;
6114     bool CreateBuiltins = false;
6115 
6116     // If the declaration we're planning to build will be a function
6117     // or object with linkage, then look for another declaration with
6118     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6119     //
6120     // If the declaration we're planning to build will be declared with
6121     // external linkage in the translation unit, create any builtin with
6122     // the same name.
6123     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6124       /* Do nothing*/;
6125     else if (CurContext->isFunctionOrMethod() &&
6126              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6127               R->isFunctionType())) {
6128       IsLinkageLookup = true;
6129       CreateBuiltins =
6130           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6131     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6132                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6133       CreateBuiltins = true;
6134 
6135     if (IsLinkageLookup) {
6136       Previous.clear(LookupRedeclarationWithLinkage);
6137       Previous.setRedeclarationKind(ForExternalRedeclaration);
6138     }
6139 
6140     LookupName(Previous, S, CreateBuiltins);
6141   } else { // Something like "int foo::x;"
6142     LookupQualifiedName(Previous, DC);
6143 
6144     // C++ [dcl.meaning]p1:
6145     //   When the declarator-id is qualified, the declaration shall refer to a
6146     //  previously declared member of the class or namespace to which the
6147     //  qualifier refers (or, in the case of a namespace, of an element of the
6148     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6149     //  thereof; [...]
6150     //
6151     // Note that we already checked the context above, and that we do not have
6152     // enough information to make sure that Previous contains the declaration
6153     // we want to match. For example, given:
6154     //
6155     //   class X {
6156     //     void f();
6157     //     void f(float);
6158     //   };
6159     //
6160     //   void X::f(int) { } // ill-formed
6161     //
6162     // In this case, Previous will point to the overload set
6163     // containing the two f's declared in X, but neither of them
6164     // matches.
6165 
6166     // C++ [dcl.meaning]p1:
6167     //   [...] the member shall not merely have been introduced by a
6168     //   using-declaration in the scope of the class or namespace nominated by
6169     //   the nested-name-specifier of the declarator-id.
6170     RemoveUsingDecls(Previous);
6171   }
6172 
6173   if (Previous.isSingleResult() &&
6174       Previous.getFoundDecl()->isTemplateParameter()) {
6175     // Maybe we will complain about the shadowed template parameter.
6176     if (!D.isInvalidType())
6177       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6178                                       Previous.getFoundDecl());
6179 
6180     // Just pretend that we didn't see the previous declaration.
6181     Previous.clear();
6182   }
6183 
6184   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6185     // Forget that the previous declaration is the injected-class-name.
6186     Previous.clear();
6187 
6188   // In C++, the previous declaration we find might be a tag type
6189   // (class or enum). In this case, the new declaration will hide the
6190   // tag type. Note that this applies to functions, function templates, and
6191   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6192   if (Previous.isSingleTagDecl() &&
6193       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6194       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6195     Previous.clear();
6196 
6197   // Check that there are no default arguments other than in the parameters
6198   // of a function declaration (C++ only).
6199   if (getLangOpts().CPlusPlus)
6200     CheckExtraCXXDefaultArguments(D);
6201 
6202   NamedDecl *New;
6203 
6204   bool AddToScope = true;
6205   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6206     if (TemplateParamLists.size()) {
6207       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6208       return nullptr;
6209     }
6210 
6211     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6212   } else if (R->isFunctionType()) {
6213     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6214                                   TemplateParamLists,
6215                                   AddToScope);
6216   } else {
6217     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6218                                   AddToScope);
6219   }
6220 
6221   if (!New)
6222     return nullptr;
6223 
6224   // If this has an identifier and is not a function template specialization,
6225   // add it to the scope stack.
6226   if (New->getDeclName() && AddToScope)
6227     PushOnScopeChains(New, S);
6228 
6229   if (isInOpenMPDeclareTargetContext())
6230     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6231 
6232   return New;
6233 }
6234 
6235 /// Helper method to turn variable array types into constant array
6236 /// types in certain situations which would otherwise be errors (for
6237 /// GCC compatibility).
6238 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6239                                                     ASTContext &Context,
6240                                                     bool &SizeIsNegative,
6241                                                     llvm::APSInt &Oversized) {
6242   // This method tries to turn a variable array into a constant
6243   // array even when the size isn't an ICE.  This is necessary
6244   // for compatibility with code that depends on gcc's buggy
6245   // constant expression folding, like struct {char x[(int)(char*)2];}
6246   SizeIsNegative = false;
6247   Oversized = 0;
6248 
6249   if (T->isDependentType())
6250     return QualType();
6251 
6252   QualifierCollector Qs;
6253   const Type *Ty = Qs.strip(T);
6254 
6255   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6256     QualType Pointee = PTy->getPointeeType();
6257     QualType FixedType =
6258         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6259                                             Oversized);
6260     if (FixedType.isNull()) return FixedType;
6261     FixedType = Context.getPointerType(FixedType);
6262     return Qs.apply(Context, FixedType);
6263   }
6264   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6265     QualType Inner = PTy->getInnerType();
6266     QualType FixedType =
6267         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6268                                             Oversized);
6269     if (FixedType.isNull()) return FixedType;
6270     FixedType = Context.getParenType(FixedType);
6271     return Qs.apply(Context, FixedType);
6272   }
6273 
6274   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6275   if (!VLATy)
6276     return QualType();
6277 
6278   QualType ElemTy = VLATy->getElementType();
6279   if (ElemTy->isVariablyModifiedType()) {
6280     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6281                                                  SizeIsNegative, Oversized);
6282     if (ElemTy.isNull())
6283       return QualType();
6284   }
6285 
6286   Expr::EvalResult Result;
6287   if (!VLATy->getSizeExpr() ||
6288       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6289     return QualType();
6290 
6291   llvm::APSInt Res = Result.Val.getInt();
6292 
6293   // Check whether the array size is negative.
6294   if (Res.isSigned() && Res.isNegative()) {
6295     SizeIsNegative = true;
6296     return QualType();
6297   }
6298 
6299   // Check whether the array is too large to be addressed.
6300   unsigned ActiveSizeBits =
6301       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6302        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6303           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6304           : Res.getActiveBits();
6305   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6306     Oversized = Res;
6307     return QualType();
6308   }
6309 
6310   QualType FoldedArrayType = Context.getConstantArrayType(
6311       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6312   return Qs.apply(Context, FoldedArrayType);
6313 }
6314 
6315 static void
6316 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6317   SrcTL = SrcTL.getUnqualifiedLoc();
6318   DstTL = DstTL.getUnqualifiedLoc();
6319   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6320     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6321     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6322                                       DstPTL.getPointeeLoc());
6323     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6324     return;
6325   }
6326   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6327     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6328     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6329                                       DstPTL.getInnerLoc());
6330     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6331     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6332     return;
6333   }
6334   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6335   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6336   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6337   TypeLoc DstElemTL = DstATL.getElementLoc();
6338   if (VariableArrayTypeLoc SrcElemATL =
6339           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6340     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6341     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6342   } else {
6343     DstElemTL.initializeFullCopy(SrcElemTL);
6344   }
6345   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6346   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6347   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6348 }
6349 
6350 /// Helper method to turn variable array types into constant array
6351 /// types in certain situations which would otherwise be errors (for
6352 /// GCC compatibility).
6353 static TypeSourceInfo*
6354 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6355                                               ASTContext &Context,
6356                                               bool &SizeIsNegative,
6357                                               llvm::APSInt &Oversized) {
6358   QualType FixedTy
6359     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6360                                           SizeIsNegative, Oversized);
6361   if (FixedTy.isNull())
6362     return nullptr;
6363   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6364   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6365                                     FixedTInfo->getTypeLoc());
6366   return FixedTInfo;
6367 }
6368 
6369 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6370 /// true if we were successful.
6371 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6372                                            QualType &T, SourceLocation Loc,
6373                                            unsigned FailedFoldDiagID) {
6374   bool SizeIsNegative;
6375   llvm::APSInt Oversized;
6376   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6377       TInfo, Context, SizeIsNegative, Oversized);
6378   if (FixedTInfo) {
6379     Diag(Loc, diag::ext_vla_folded_to_constant);
6380     TInfo = FixedTInfo;
6381     T = FixedTInfo->getType();
6382     return true;
6383   }
6384 
6385   if (SizeIsNegative)
6386     Diag(Loc, diag::err_typecheck_negative_array_size);
6387   else if (Oversized.getBoolValue())
6388     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6389   else if (FailedFoldDiagID)
6390     Diag(Loc, FailedFoldDiagID);
6391   return false;
6392 }
6393 
6394 /// Register the given locally-scoped extern "C" declaration so
6395 /// that it can be found later for redeclarations. We include any extern "C"
6396 /// declaration that is not visible in the translation unit here, not just
6397 /// function-scope declarations.
6398 void
6399 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6400   if (!getLangOpts().CPlusPlus &&
6401       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6402     // Don't need to track declarations in the TU in C.
6403     return;
6404 
6405   // Note that we have a locally-scoped external with this name.
6406   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6407 }
6408 
6409 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6410   // FIXME: We can have multiple results via __attribute__((overloadable)).
6411   auto Result = Context.getExternCContextDecl()->lookup(Name);
6412   return Result.empty() ? nullptr : *Result.begin();
6413 }
6414 
6415 /// Diagnose function specifiers on a declaration of an identifier that
6416 /// does not identify a function.
6417 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6418   // FIXME: We should probably indicate the identifier in question to avoid
6419   // confusion for constructs like "virtual int a(), b;"
6420   if (DS.isVirtualSpecified())
6421     Diag(DS.getVirtualSpecLoc(),
6422          diag::err_virtual_non_function);
6423 
6424   if (DS.hasExplicitSpecifier())
6425     Diag(DS.getExplicitSpecLoc(),
6426          diag::err_explicit_non_function);
6427 
6428   if (DS.isNoreturnSpecified())
6429     Diag(DS.getNoreturnSpecLoc(),
6430          diag::err_noreturn_non_function);
6431 }
6432 
6433 NamedDecl*
6434 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6435                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6436   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6437   if (D.getCXXScopeSpec().isSet()) {
6438     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6439       << D.getCXXScopeSpec().getRange();
6440     D.setInvalidType();
6441     // Pretend we didn't see the scope specifier.
6442     DC = CurContext;
6443     Previous.clear();
6444   }
6445 
6446   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6447 
6448   if (D.getDeclSpec().isInlineSpecified())
6449     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6450         << getLangOpts().CPlusPlus17;
6451   if (D.getDeclSpec().hasConstexprSpecifier())
6452     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6453         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6454 
6455   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6456     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6457       Diag(D.getName().StartLocation,
6458            diag::err_deduction_guide_invalid_specifier)
6459           << "typedef";
6460     else
6461       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6462           << D.getName().getSourceRange();
6463     return nullptr;
6464   }
6465 
6466   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6467   if (!NewTD) return nullptr;
6468 
6469   // Handle attributes prior to checking for duplicates in MergeVarDecl
6470   ProcessDeclAttributes(S, NewTD, D);
6471 
6472   CheckTypedefForVariablyModifiedType(S, NewTD);
6473 
6474   bool Redeclaration = D.isRedeclaration();
6475   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6476   D.setRedeclaration(Redeclaration);
6477   return ND;
6478 }
6479 
6480 void
6481 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6482   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6483   // then it shall have block scope.
6484   // Note that variably modified types must be fixed before merging the decl so
6485   // that redeclarations will match.
6486   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6487   QualType T = TInfo->getType();
6488   if (T->isVariablyModifiedType()) {
6489     setFunctionHasBranchProtectedScope();
6490 
6491     if (S->getFnParent() == nullptr) {
6492       bool SizeIsNegative;
6493       llvm::APSInt Oversized;
6494       TypeSourceInfo *FixedTInfo =
6495         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6496                                                       SizeIsNegative,
6497                                                       Oversized);
6498       if (FixedTInfo) {
6499         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6500         NewTD->setTypeSourceInfo(FixedTInfo);
6501       } else {
6502         if (SizeIsNegative)
6503           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6504         else if (T->isVariableArrayType())
6505           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6506         else if (Oversized.getBoolValue())
6507           Diag(NewTD->getLocation(), diag::err_array_too_large)
6508             << toString(Oversized, 10);
6509         else
6510           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6511         NewTD->setInvalidDecl();
6512       }
6513     }
6514   }
6515 }
6516 
6517 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6518 /// declares a typedef-name, either using the 'typedef' type specifier or via
6519 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6520 NamedDecl*
6521 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6522                            LookupResult &Previous, bool &Redeclaration) {
6523 
6524   // Find the shadowed declaration before filtering for scope.
6525   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6526 
6527   // Merge the decl with the existing one if appropriate. If the decl is
6528   // in an outer scope, it isn't the same thing.
6529   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6530                        /*AllowInlineNamespace*/false);
6531   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6532   if (!Previous.empty()) {
6533     Redeclaration = true;
6534     MergeTypedefNameDecl(S, NewTD, Previous);
6535   } else {
6536     inferGslPointerAttribute(NewTD);
6537   }
6538 
6539   if (ShadowedDecl && !Redeclaration)
6540     CheckShadow(NewTD, ShadowedDecl, Previous);
6541 
6542   // If this is the C FILE type, notify the AST context.
6543   if (IdentifierInfo *II = NewTD->getIdentifier())
6544     if (!NewTD->isInvalidDecl() &&
6545         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6546       if (II->isStr("FILE"))
6547         Context.setFILEDecl(NewTD);
6548       else if (II->isStr("jmp_buf"))
6549         Context.setjmp_bufDecl(NewTD);
6550       else if (II->isStr("sigjmp_buf"))
6551         Context.setsigjmp_bufDecl(NewTD);
6552       else if (II->isStr("ucontext_t"))
6553         Context.setucontext_tDecl(NewTD);
6554     }
6555 
6556   return NewTD;
6557 }
6558 
6559 /// Determines whether the given declaration is an out-of-scope
6560 /// previous declaration.
6561 ///
6562 /// This routine should be invoked when name lookup has found a
6563 /// previous declaration (PrevDecl) that is not in the scope where a
6564 /// new declaration by the same name is being introduced. If the new
6565 /// declaration occurs in a local scope, previous declarations with
6566 /// linkage may still be considered previous declarations (C99
6567 /// 6.2.2p4-5, C++ [basic.link]p6).
6568 ///
6569 /// \param PrevDecl the previous declaration found by name
6570 /// lookup
6571 ///
6572 /// \param DC the context in which the new declaration is being
6573 /// declared.
6574 ///
6575 /// \returns true if PrevDecl is an out-of-scope previous declaration
6576 /// for a new delcaration with the same name.
6577 static bool
6578 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6579                                 ASTContext &Context) {
6580   if (!PrevDecl)
6581     return false;
6582 
6583   if (!PrevDecl->hasLinkage())
6584     return false;
6585 
6586   if (Context.getLangOpts().CPlusPlus) {
6587     // C++ [basic.link]p6:
6588     //   If there is a visible declaration of an entity with linkage
6589     //   having the same name and type, ignoring entities declared
6590     //   outside the innermost enclosing namespace scope, the block
6591     //   scope declaration declares that same entity and receives the
6592     //   linkage of the previous declaration.
6593     DeclContext *OuterContext = DC->getRedeclContext();
6594     if (!OuterContext->isFunctionOrMethod())
6595       // This rule only applies to block-scope declarations.
6596       return false;
6597 
6598     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6599     if (PrevOuterContext->isRecord())
6600       // We found a member function: ignore it.
6601       return false;
6602 
6603     // Find the innermost enclosing namespace for the new and
6604     // previous declarations.
6605     OuterContext = OuterContext->getEnclosingNamespaceContext();
6606     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6607 
6608     // The previous declaration is in a different namespace, so it
6609     // isn't the same function.
6610     if (!OuterContext->Equals(PrevOuterContext))
6611       return false;
6612   }
6613 
6614   return true;
6615 }
6616 
6617 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6618   CXXScopeSpec &SS = D.getCXXScopeSpec();
6619   if (!SS.isSet()) return;
6620   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6621 }
6622 
6623 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6624   QualType type = decl->getType();
6625   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6626   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6627     // Various kinds of declaration aren't allowed to be __autoreleasing.
6628     unsigned kind = -1U;
6629     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6630       if (var->hasAttr<BlocksAttr>())
6631         kind = 0; // __block
6632       else if (!var->hasLocalStorage())
6633         kind = 1; // global
6634     } else if (isa<ObjCIvarDecl>(decl)) {
6635       kind = 3; // ivar
6636     } else if (isa<FieldDecl>(decl)) {
6637       kind = 2; // field
6638     }
6639 
6640     if (kind != -1U) {
6641       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6642         << kind;
6643     }
6644   } else if (lifetime == Qualifiers::OCL_None) {
6645     // Try to infer lifetime.
6646     if (!type->isObjCLifetimeType())
6647       return false;
6648 
6649     lifetime = type->getObjCARCImplicitLifetime();
6650     type = Context.getLifetimeQualifiedType(type, lifetime);
6651     decl->setType(type);
6652   }
6653 
6654   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6655     // Thread-local variables cannot have lifetime.
6656     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6657         var->getTLSKind()) {
6658       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6659         << var->getType();
6660       return true;
6661     }
6662   }
6663 
6664   return false;
6665 }
6666 
6667 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6668   if (Decl->getType().hasAddressSpace())
6669     return;
6670   if (Decl->getType()->isDependentType())
6671     return;
6672   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6673     QualType Type = Var->getType();
6674     if (Type->isSamplerT() || Type->isVoidType())
6675       return;
6676     LangAS ImplAS = LangAS::opencl_private;
6677     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6678     // __opencl_c_program_scope_global_variables feature, the address space
6679     // for a variable at program scope or a static or extern variable inside
6680     // a function are inferred to be __global.
6681     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6682         Var->hasGlobalStorage())
6683       ImplAS = LangAS::opencl_global;
6684     // If the original type from a decayed type is an array type and that array
6685     // type has no address space yet, deduce it now.
6686     if (auto DT = dyn_cast<DecayedType>(Type)) {
6687       auto OrigTy = DT->getOriginalType();
6688       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6689         // Add the address space to the original array type and then propagate
6690         // that to the element type through `getAsArrayType`.
6691         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6692         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6693         // Re-generate the decayed type.
6694         Type = Context.getDecayedType(OrigTy);
6695       }
6696     }
6697     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6698     // Apply any qualifiers (including address space) from the array type to
6699     // the element type. This implements C99 6.7.3p8: "If the specification of
6700     // an array type includes any type qualifiers, the element type is so
6701     // qualified, not the array type."
6702     if (Type->isArrayType())
6703       Type = QualType(Context.getAsArrayType(Type), 0);
6704     Decl->setType(Type);
6705   }
6706 }
6707 
6708 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6709   // Ensure that an auto decl is deduced otherwise the checks below might cache
6710   // the wrong linkage.
6711   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6712 
6713   // 'weak' only applies to declarations with external linkage.
6714   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6715     if (!ND.isExternallyVisible()) {
6716       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6717       ND.dropAttr<WeakAttr>();
6718     }
6719   }
6720   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6721     if (ND.isExternallyVisible()) {
6722       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6723       ND.dropAttr<WeakRefAttr>();
6724       ND.dropAttr<AliasAttr>();
6725     }
6726   }
6727 
6728   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6729     if (VD->hasInit()) {
6730       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6731         assert(VD->isThisDeclarationADefinition() &&
6732                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6733         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6734         VD->dropAttr<AliasAttr>();
6735       }
6736     }
6737   }
6738 
6739   // 'selectany' only applies to externally visible variable declarations.
6740   // It does not apply to functions.
6741   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6742     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6743       S.Diag(Attr->getLocation(),
6744              diag::err_attribute_selectany_non_extern_data);
6745       ND.dropAttr<SelectAnyAttr>();
6746     }
6747   }
6748 
6749   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6750     auto *VD = dyn_cast<VarDecl>(&ND);
6751     bool IsAnonymousNS = false;
6752     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6753     if (VD) {
6754       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6755       while (NS && !IsAnonymousNS) {
6756         IsAnonymousNS = NS->isAnonymousNamespace();
6757         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6758       }
6759     }
6760     // dll attributes require external linkage. Static locals may have external
6761     // linkage but still cannot be explicitly imported or exported.
6762     // In Microsoft mode, a variable defined in anonymous namespace must have
6763     // external linkage in order to be exported.
6764     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6765     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6766         (!AnonNSInMicrosoftMode &&
6767          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6768       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6769         << &ND << Attr;
6770       ND.setInvalidDecl();
6771     }
6772   }
6773 
6774   // Check the attributes on the function type, if any.
6775   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6776     // Don't declare this variable in the second operand of the for-statement;
6777     // GCC miscompiles that by ending its lifetime before evaluating the
6778     // third operand. See gcc.gnu.org/PR86769.
6779     AttributedTypeLoc ATL;
6780     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6781          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6782          TL = ATL.getModifiedLoc()) {
6783       // The [[lifetimebound]] attribute can be applied to the implicit object
6784       // parameter of a non-static member function (other than a ctor or dtor)
6785       // by applying it to the function type.
6786       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6787         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6788         if (!MD || MD->isStatic()) {
6789           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6790               << !MD << A->getRange();
6791         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6792           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6793               << isa<CXXDestructorDecl>(MD) << A->getRange();
6794         }
6795       }
6796     }
6797   }
6798 }
6799 
6800 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6801                                            NamedDecl *NewDecl,
6802                                            bool IsSpecialization,
6803                                            bool IsDefinition) {
6804   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6805     return;
6806 
6807   bool IsTemplate = false;
6808   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6809     OldDecl = OldTD->getTemplatedDecl();
6810     IsTemplate = true;
6811     if (!IsSpecialization)
6812       IsDefinition = false;
6813   }
6814   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6815     NewDecl = NewTD->getTemplatedDecl();
6816     IsTemplate = true;
6817   }
6818 
6819   if (!OldDecl || !NewDecl)
6820     return;
6821 
6822   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6823   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6824   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6825   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6826 
6827   // dllimport and dllexport are inheritable attributes so we have to exclude
6828   // inherited attribute instances.
6829   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6830                     (NewExportAttr && !NewExportAttr->isInherited());
6831 
6832   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6833   // the only exception being explicit specializations.
6834   // Implicitly generated declarations are also excluded for now because there
6835   // is no other way to switch these to use dllimport or dllexport.
6836   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6837 
6838   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6839     // Allow with a warning for free functions and global variables.
6840     bool JustWarn = false;
6841     if (!OldDecl->isCXXClassMember()) {
6842       auto *VD = dyn_cast<VarDecl>(OldDecl);
6843       if (VD && !VD->getDescribedVarTemplate())
6844         JustWarn = true;
6845       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6846       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6847         JustWarn = true;
6848     }
6849 
6850     // We cannot change a declaration that's been used because IR has already
6851     // been emitted. Dllimported functions will still work though (modulo
6852     // address equality) as they can use the thunk.
6853     if (OldDecl->isUsed())
6854       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6855         JustWarn = false;
6856 
6857     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6858                                : diag::err_attribute_dll_redeclaration;
6859     S.Diag(NewDecl->getLocation(), DiagID)
6860         << NewDecl
6861         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6862     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6863     if (!JustWarn) {
6864       NewDecl->setInvalidDecl();
6865       return;
6866     }
6867   }
6868 
6869   // A redeclaration is not allowed to drop a dllimport attribute, the only
6870   // exceptions being inline function definitions (except for function
6871   // templates), local extern declarations, qualified friend declarations or
6872   // special MSVC extension: in the last case, the declaration is treated as if
6873   // it were marked dllexport.
6874   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6875   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6876   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6877     // Ignore static data because out-of-line definitions are diagnosed
6878     // separately.
6879     IsStaticDataMember = VD->isStaticDataMember();
6880     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6881                    VarDecl::DeclarationOnly;
6882   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6883     IsInline = FD->isInlined();
6884     IsQualifiedFriend = FD->getQualifier() &&
6885                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6886   }
6887 
6888   if (OldImportAttr && !HasNewAttr &&
6889       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6890       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6891     if (IsMicrosoftABI && IsDefinition) {
6892       S.Diag(NewDecl->getLocation(),
6893              diag::warn_redeclaration_without_import_attribute)
6894           << NewDecl;
6895       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6896       NewDecl->dropAttr<DLLImportAttr>();
6897       NewDecl->addAttr(
6898           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6899     } else {
6900       S.Diag(NewDecl->getLocation(),
6901              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6902           << NewDecl << OldImportAttr;
6903       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6904       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6905       OldDecl->dropAttr<DLLImportAttr>();
6906       NewDecl->dropAttr<DLLImportAttr>();
6907     }
6908   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6909     // In MinGW, seeing a function declared inline drops the dllimport
6910     // attribute.
6911     OldDecl->dropAttr<DLLImportAttr>();
6912     NewDecl->dropAttr<DLLImportAttr>();
6913     S.Diag(NewDecl->getLocation(),
6914            diag::warn_dllimport_dropped_from_inline_function)
6915         << NewDecl << OldImportAttr;
6916   }
6917 
6918   // A specialization of a class template member function is processed here
6919   // since it's a redeclaration. If the parent class is dllexport, the
6920   // specialization inherits that attribute. This doesn't happen automatically
6921   // since the parent class isn't instantiated until later.
6922   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6923     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6924         !NewImportAttr && !NewExportAttr) {
6925       if (const DLLExportAttr *ParentExportAttr =
6926               MD->getParent()->getAttr<DLLExportAttr>()) {
6927         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6928         NewAttr->setInherited(true);
6929         NewDecl->addAttr(NewAttr);
6930       }
6931     }
6932   }
6933 }
6934 
6935 /// Given that we are within the definition of the given function,
6936 /// will that definition behave like C99's 'inline', where the
6937 /// definition is discarded except for optimization purposes?
6938 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6939   // Try to avoid calling GetGVALinkageForFunction.
6940 
6941   // All cases of this require the 'inline' keyword.
6942   if (!FD->isInlined()) return false;
6943 
6944   // This is only possible in C++ with the gnu_inline attribute.
6945   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6946     return false;
6947 
6948   // Okay, go ahead and call the relatively-more-expensive function.
6949   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6950 }
6951 
6952 /// Determine whether a variable is extern "C" prior to attaching
6953 /// an initializer. We can't just call isExternC() here, because that
6954 /// will also compute and cache whether the declaration is externally
6955 /// visible, which might change when we attach the initializer.
6956 ///
6957 /// This can only be used if the declaration is known to not be a
6958 /// redeclaration of an internal linkage declaration.
6959 ///
6960 /// For instance:
6961 ///
6962 ///   auto x = []{};
6963 ///
6964 /// Attaching the initializer here makes this declaration not externally
6965 /// visible, because its type has internal linkage.
6966 ///
6967 /// FIXME: This is a hack.
6968 template<typename T>
6969 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6970   if (S.getLangOpts().CPlusPlus) {
6971     // In C++, the overloadable attribute negates the effects of extern "C".
6972     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6973       return false;
6974 
6975     // So do CUDA's host/device attributes.
6976     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6977                                  D->template hasAttr<CUDAHostAttr>()))
6978       return false;
6979   }
6980   return D->isExternC();
6981 }
6982 
6983 static bool shouldConsiderLinkage(const VarDecl *VD) {
6984   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6985   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6986       isa<OMPDeclareMapperDecl>(DC))
6987     return VD->hasExternalStorage();
6988   if (DC->isFileContext())
6989     return true;
6990   if (DC->isRecord())
6991     return false;
6992   if (isa<RequiresExprBodyDecl>(DC))
6993     return false;
6994   llvm_unreachable("Unexpected context");
6995 }
6996 
6997 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6998   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6999   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7000       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7001     return true;
7002   if (DC->isRecord())
7003     return false;
7004   llvm_unreachable("Unexpected context");
7005 }
7006 
7007 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7008                           ParsedAttr::Kind Kind) {
7009   // Check decl attributes on the DeclSpec.
7010   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7011     return true;
7012 
7013   // Walk the declarator structure, checking decl attributes that were in a type
7014   // position to the decl itself.
7015   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7016     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7017       return true;
7018   }
7019 
7020   // Finally, check attributes on the decl itself.
7021   return PD.getAttributes().hasAttribute(Kind) ||
7022          PD.getDeclarationAttributes().hasAttribute(Kind);
7023 }
7024 
7025 /// Adjust the \c DeclContext for a function or variable that might be a
7026 /// function-local external declaration.
7027 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7028   if (!DC->isFunctionOrMethod())
7029     return false;
7030 
7031   // If this is a local extern function or variable declared within a function
7032   // template, don't add it into the enclosing namespace scope until it is
7033   // instantiated; it might have a dependent type right now.
7034   if (DC->isDependentContext())
7035     return true;
7036 
7037   // C++11 [basic.link]p7:
7038   //   When a block scope declaration of an entity with linkage is not found to
7039   //   refer to some other declaration, then that entity is a member of the
7040   //   innermost enclosing namespace.
7041   //
7042   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7043   // semantically-enclosing namespace, not a lexically-enclosing one.
7044   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7045     DC = DC->getParent();
7046   return true;
7047 }
7048 
7049 /// Returns true if given declaration has external C language linkage.
7050 static bool isDeclExternC(const Decl *D) {
7051   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7052     return FD->isExternC();
7053   if (const auto *VD = dyn_cast<VarDecl>(D))
7054     return VD->isExternC();
7055 
7056   llvm_unreachable("Unknown type of decl!");
7057 }
7058 
7059 /// Returns true if there hasn't been any invalid type diagnosed.
7060 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7061   DeclContext *DC = NewVD->getDeclContext();
7062   QualType R = NewVD->getType();
7063 
7064   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7065   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7066   // argument.
7067   if (R->isImageType() || R->isPipeType()) {
7068     Se.Diag(NewVD->getLocation(),
7069             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7070         << R;
7071     NewVD->setInvalidDecl();
7072     return false;
7073   }
7074 
7075   // OpenCL v1.2 s6.9.r:
7076   // The event type cannot be used to declare a program scope variable.
7077   // OpenCL v2.0 s6.9.q:
7078   // The clk_event_t and reserve_id_t types cannot be declared in program
7079   // scope.
7080   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7081     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7082       Se.Diag(NewVD->getLocation(),
7083               diag::err_invalid_type_for_program_scope_var)
7084           << R;
7085       NewVD->setInvalidDecl();
7086       return false;
7087     }
7088   }
7089 
7090   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7091   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7092                                                Se.getLangOpts())) {
7093     QualType NR = R.getCanonicalType();
7094     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7095            NR->isReferenceType()) {
7096       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7097           NR->isFunctionReferenceType()) {
7098         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7099             << NR->isReferenceType();
7100         NewVD->setInvalidDecl();
7101         return false;
7102       }
7103       NR = NR->getPointeeType();
7104     }
7105   }
7106 
7107   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7108                                                Se.getLangOpts())) {
7109     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7110     // half array type (unless the cl_khr_fp16 extension is enabled).
7111     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7112       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7113       NewVD->setInvalidDecl();
7114       return false;
7115     }
7116   }
7117 
7118   // OpenCL v1.2 s6.9.r:
7119   // The event type cannot be used with the __local, __constant and __global
7120   // address space qualifiers.
7121   if (R->isEventT()) {
7122     if (R.getAddressSpace() != LangAS::opencl_private) {
7123       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7124       NewVD->setInvalidDecl();
7125       return false;
7126     }
7127   }
7128 
7129   if (R->isSamplerT()) {
7130     // OpenCL v1.2 s6.9.b p4:
7131     // The sampler type cannot be used with the __local and __global address
7132     // space qualifiers.
7133     if (R.getAddressSpace() == LangAS::opencl_local ||
7134         R.getAddressSpace() == LangAS::opencl_global) {
7135       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7136       NewVD->setInvalidDecl();
7137     }
7138 
7139     // OpenCL v1.2 s6.12.14.1:
7140     // A global sampler must be declared with either the constant address
7141     // space qualifier or with the const qualifier.
7142     if (DC->isTranslationUnit() &&
7143         !(R.getAddressSpace() == LangAS::opencl_constant ||
7144           R.isConstQualified())) {
7145       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7146       NewVD->setInvalidDecl();
7147     }
7148     if (NewVD->isInvalidDecl())
7149       return false;
7150   }
7151 
7152   return true;
7153 }
7154 
7155 template <typename AttrTy>
7156 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7157   const TypedefNameDecl *TND = TT->getDecl();
7158   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7159     AttrTy *Clone = Attribute->clone(S.Context);
7160     Clone->setInherited(true);
7161     D->addAttr(Clone);
7162   }
7163 }
7164 
7165 NamedDecl *Sema::ActOnVariableDeclarator(
7166     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7167     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7168     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7169   QualType R = TInfo->getType();
7170   DeclarationName Name = GetNameForDeclarator(D).getName();
7171 
7172   IdentifierInfo *II = Name.getAsIdentifierInfo();
7173 
7174   if (D.isDecompositionDeclarator()) {
7175     // Take the name of the first declarator as our name for diagnostic
7176     // purposes.
7177     auto &Decomp = D.getDecompositionDeclarator();
7178     if (!Decomp.bindings().empty()) {
7179       II = Decomp.bindings()[0].Name;
7180       Name = II;
7181     }
7182   } else if (!II) {
7183     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7184     return nullptr;
7185   }
7186 
7187 
7188   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7189   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7190 
7191   // dllimport globals without explicit storage class are treated as extern. We
7192   // have to change the storage class this early to get the right DeclContext.
7193   if (SC == SC_None && !DC->isRecord() &&
7194       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7195       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7196     SC = SC_Extern;
7197 
7198   DeclContext *OriginalDC = DC;
7199   bool IsLocalExternDecl = SC == SC_Extern &&
7200                            adjustContextForLocalExternDecl(DC);
7201 
7202   if (SCSpec == DeclSpec::SCS_mutable) {
7203     // mutable can only appear on non-static class members, so it's always
7204     // an error here
7205     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7206     D.setInvalidType();
7207     SC = SC_None;
7208   }
7209 
7210   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7211       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7212                               D.getDeclSpec().getStorageClassSpecLoc())) {
7213     // In C++11, the 'register' storage class specifier is deprecated.
7214     // Suppress the warning in system macros, it's used in macros in some
7215     // popular C system headers, such as in glibc's htonl() macro.
7216     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7217          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7218                                    : diag::warn_deprecated_register)
7219       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7220   }
7221 
7222   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7223 
7224   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7225     // C99 6.9p2: The storage-class specifiers auto and register shall not
7226     // appear in the declaration specifiers in an external declaration.
7227     // Global Register+Asm is a GNU extension we support.
7228     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7229       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7230       D.setInvalidType();
7231     }
7232   }
7233 
7234   // If this variable has a VLA type and an initializer, try to
7235   // fold to a constant-sized type. This is otherwise invalid.
7236   if (D.hasInitializer() && R->isVariableArrayType())
7237     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7238                                     /*DiagID=*/0);
7239 
7240   bool IsMemberSpecialization = false;
7241   bool IsVariableTemplateSpecialization = false;
7242   bool IsPartialSpecialization = false;
7243   bool IsVariableTemplate = false;
7244   VarDecl *NewVD = nullptr;
7245   VarTemplateDecl *NewTemplate = nullptr;
7246   TemplateParameterList *TemplateParams = nullptr;
7247   if (!getLangOpts().CPlusPlus) {
7248     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7249                             II, R, TInfo, SC);
7250 
7251     if (R->getContainedDeducedType())
7252       ParsingInitForAutoVars.insert(NewVD);
7253 
7254     if (D.isInvalidType())
7255       NewVD->setInvalidDecl();
7256 
7257     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7258         NewVD->hasLocalStorage())
7259       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7260                             NTCUC_AutoVar, NTCUK_Destruct);
7261   } else {
7262     bool Invalid = false;
7263 
7264     if (DC->isRecord() && !CurContext->isRecord()) {
7265       // This is an out-of-line definition of a static data member.
7266       switch (SC) {
7267       case SC_None:
7268         break;
7269       case SC_Static:
7270         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7271              diag::err_static_out_of_line)
7272           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7273         break;
7274       case SC_Auto:
7275       case SC_Register:
7276       case SC_Extern:
7277         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7278         // to names of variables declared in a block or to function parameters.
7279         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7280         // of class members
7281 
7282         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7283              diag::err_storage_class_for_static_member)
7284           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7285         break;
7286       case SC_PrivateExtern:
7287         llvm_unreachable("C storage class in c++!");
7288       }
7289     }
7290 
7291     if (SC == SC_Static && CurContext->isRecord()) {
7292       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7293         // Walk up the enclosing DeclContexts to check for any that are
7294         // incompatible with static data members.
7295         const DeclContext *FunctionOrMethod = nullptr;
7296         const CXXRecordDecl *AnonStruct = nullptr;
7297         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7298           if (Ctxt->isFunctionOrMethod()) {
7299             FunctionOrMethod = Ctxt;
7300             break;
7301           }
7302           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7303           if (ParentDecl && !ParentDecl->getDeclName()) {
7304             AnonStruct = ParentDecl;
7305             break;
7306           }
7307         }
7308         if (FunctionOrMethod) {
7309           // C++ [class.static.data]p5: A local class shall not have static data
7310           // members.
7311           Diag(D.getIdentifierLoc(),
7312                diag::err_static_data_member_not_allowed_in_local_class)
7313             << Name << RD->getDeclName() << RD->getTagKind();
7314         } else if (AnonStruct) {
7315           // C++ [class.static.data]p4: Unnamed classes and classes contained
7316           // directly or indirectly within unnamed classes shall not contain
7317           // static data members.
7318           Diag(D.getIdentifierLoc(),
7319                diag::err_static_data_member_not_allowed_in_anon_struct)
7320             << Name << AnonStruct->getTagKind();
7321           Invalid = true;
7322         } else if (RD->isUnion()) {
7323           // C++98 [class.union]p1: If a union contains a static data member,
7324           // the program is ill-formed. C++11 drops this restriction.
7325           Diag(D.getIdentifierLoc(),
7326                getLangOpts().CPlusPlus11
7327                  ? diag::warn_cxx98_compat_static_data_member_in_union
7328                  : diag::ext_static_data_member_in_union) << Name;
7329         }
7330       }
7331     }
7332 
7333     // Match up the template parameter lists with the scope specifier, then
7334     // determine whether we have a template or a template specialization.
7335     bool InvalidScope = false;
7336     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7337         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7338         D.getCXXScopeSpec(),
7339         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7340             ? D.getName().TemplateId
7341             : nullptr,
7342         TemplateParamLists,
7343         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7344     Invalid |= InvalidScope;
7345 
7346     if (TemplateParams) {
7347       if (!TemplateParams->size() &&
7348           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7349         // There is an extraneous 'template<>' for this variable. Complain
7350         // about it, but allow the declaration of the variable.
7351         Diag(TemplateParams->getTemplateLoc(),
7352              diag::err_template_variable_noparams)
7353           << II
7354           << SourceRange(TemplateParams->getTemplateLoc(),
7355                          TemplateParams->getRAngleLoc());
7356         TemplateParams = nullptr;
7357       } else {
7358         // Check that we can declare a template here.
7359         if (CheckTemplateDeclScope(S, TemplateParams))
7360           return nullptr;
7361 
7362         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7363           // This is an explicit specialization or a partial specialization.
7364           IsVariableTemplateSpecialization = true;
7365           IsPartialSpecialization = TemplateParams->size() > 0;
7366         } else { // if (TemplateParams->size() > 0)
7367           // This is a template declaration.
7368           IsVariableTemplate = true;
7369 
7370           // Only C++1y supports variable templates (N3651).
7371           Diag(D.getIdentifierLoc(),
7372                getLangOpts().CPlusPlus14
7373                    ? diag::warn_cxx11_compat_variable_template
7374                    : diag::ext_variable_template);
7375         }
7376       }
7377     } else {
7378       // Check that we can declare a member specialization here.
7379       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7380           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7381         return nullptr;
7382       assert((Invalid ||
7383               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7384              "should have a 'template<>' for this decl");
7385     }
7386 
7387     if (IsVariableTemplateSpecialization) {
7388       SourceLocation TemplateKWLoc =
7389           TemplateParamLists.size() > 0
7390               ? TemplateParamLists[0]->getTemplateLoc()
7391               : SourceLocation();
7392       DeclResult Res = ActOnVarTemplateSpecialization(
7393           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7394           IsPartialSpecialization);
7395       if (Res.isInvalid())
7396         return nullptr;
7397       NewVD = cast<VarDecl>(Res.get());
7398       AddToScope = false;
7399     } else if (D.isDecompositionDeclarator()) {
7400       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7401                                         D.getIdentifierLoc(), R, TInfo, SC,
7402                                         Bindings);
7403     } else
7404       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7405                               D.getIdentifierLoc(), II, R, TInfo, SC);
7406 
7407     // If this is supposed to be a variable template, create it as such.
7408     if (IsVariableTemplate) {
7409       NewTemplate =
7410           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7411                                   TemplateParams, NewVD);
7412       NewVD->setDescribedVarTemplate(NewTemplate);
7413     }
7414 
7415     // If this decl has an auto type in need of deduction, make a note of the
7416     // Decl so we can diagnose uses of it in its own initializer.
7417     if (R->getContainedDeducedType())
7418       ParsingInitForAutoVars.insert(NewVD);
7419 
7420     if (D.isInvalidType() || Invalid) {
7421       NewVD->setInvalidDecl();
7422       if (NewTemplate)
7423         NewTemplate->setInvalidDecl();
7424     }
7425 
7426     SetNestedNameSpecifier(*this, NewVD, D);
7427 
7428     // If we have any template parameter lists that don't directly belong to
7429     // the variable (matching the scope specifier), store them.
7430     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7431     if (TemplateParamLists.size() > VDTemplateParamLists)
7432       NewVD->setTemplateParameterListsInfo(
7433           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7434   }
7435 
7436   if (D.getDeclSpec().isInlineSpecified()) {
7437     if (!getLangOpts().CPlusPlus) {
7438       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7439           << 0;
7440     } else if (CurContext->isFunctionOrMethod()) {
7441       // 'inline' is not allowed on block scope variable declaration.
7442       Diag(D.getDeclSpec().getInlineSpecLoc(),
7443            diag::err_inline_declaration_block_scope) << Name
7444         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7445     } else {
7446       Diag(D.getDeclSpec().getInlineSpecLoc(),
7447            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7448                                      : diag::ext_inline_variable);
7449       NewVD->setInlineSpecified();
7450     }
7451   }
7452 
7453   // Set the lexical context. If the declarator has a C++ scope specifier, the
7454   // lexical context will be different from the semantic context.
7455   NewVD->setLexicalDeclContext(CurContext);
7456   if (NewTemplate)
7457     NewTemplate->setLexicalDeclContext(CurContext);
7458 
7459   if (IsLocalExternDecl) {
7460     if (D.isDecompositionDeclarator())
7461       for (auto *B : Bindings)
7462         B->setLocalExternDecl();
7463     else
7464       NewVD->setLocalExternDecl();
7465   }
7466 
7467   bool EmitTLSUnsupportedError = false;
7468   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7469     // C++11 [dcl.stc]p4:
7470     //   When thread_local is applied to a variable of block scope the
7471     //   storage-class-specifier static is implied if it does not appear
7472     //   explicitly.
7473     // Core issue: 'static' is not implied if the variable is declared
7474     //   'extern'.
7475     if (NewVD->hasLocalStorage() &&
7476         (SCSpec != DeclSpec::SCS_unspecified ||
7477          TSCS != DeclSpec::TSCS_thread_local ||
7478          !DC->isFunctionOrMethod()))
7479       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7480            diag::err_thread_non_global)
7481         << DeclSpec::getSpecifierName(TSCS);
7482     else if (!Context.getTargetInfo().isTLSSupported()) {
7483       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7484           getLangOpts().SYCLIsDevice) {
7485         // Postpone error emission until we've collected attributes required to
7486         // figure out whether it's a host or device variable and whether the
7487         // error should be ignored.
7488         EmitTLSUnsupportedError = true;
7489         // We still need to mark the variable as TLS so it shows up in AST with
7490         // proper storage class for other tools to use even if we're not going
7491         // to emit any code for it.
7492         NewVD->setTSCSpec(TSCS);
7493       } else
7494         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7495              diag::err_thread_unsupported);
7496     } else
7497       NewVD->setTSCSpec(TSCS);
7498   }
7499 
7500   switch (D.getDeclSpec().getConstexprSpecifier()) {
7501   case ConstexprSpecKind::Unspecified:
7502     break;
7503 
7504   case ConstexprSpecKind::Consteval:
7505     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7506          diag::err_constexpr_wrong_decl_kind)
7507         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7508     LLVM_FALLTHROUGH;
7509 
7510   case ConstexprSpecKind::Constexpr:
7511     NewVD->setConstexpr(true);
7512     // C++1z [dcl.spec.constexpr]p1:
7513     //   A static data member declared with the constexpr specifier is
7514     //   implicitly an inline variable.
7515     if (NewVD->isStaticDataMember() &&
7516         (getLangOpts().CPlusPlus17 ||
7517          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7518       NewVD->setImplicitlyInline();
7519     break;
7520 
7521   case ConstexprSpecKind::Constinit:
7522     if (!NewVD->hasGlobalStorage())
7523       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7524            diag::err_constinit_local_variable);
7525     else
7526       NewVD->addAttr(ConstInitAttr::Create(
7527           Context, D.getDeclSpec().getConstexprSpecLoc(),
7528           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7529     break;
7530   }
7531 
7532   // C99 6.7.4p3
7533   //   An inline definition of a function with external linkage shall
7534   //   not contain a definition of a modifiable object with static or
7535   //   thread storage duration...
7536   // We only apply this when the function is required to be defined
7537   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7538   // that a local variable with thread storage duration still has to
7539   // be marked 'static'.  Also note that it's possible to get these
7540   // semantics in C++ using __attribute__((gnu_inline)).
7541   if (SC == SC_Static && S->getFnParent() != nullptr &&
7542       !NewVD->getType().isConstQualified()) {
7543     FunctionDecl *CurFD = getCurFunctionDecl();
7544     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7545       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7546            diag::warn_static_local_in_extern_inline);
7547       MaybeSuggestAddingStaticToDecl(CurFD);
7548     }
7549   }
7550 
7551   if (D.getDeclSpec().isModulePrivateSpecified()) {
7552     if (IsVariableTemplateSpecialization)
7553       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7554           << (IsPartialSpecialization ? 1 : 0)
7555           << FixItHint::CreateRemoval(
7556                  D.getDeclSpec().getModulePrivateSpecLoc());
7557     else if (IsMemberSpecialization)
7558       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7559         << 2
7560         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7561     else if (NewVD->hasLocalStorage())
7562       Diag(NewVD->getLocation(), diag::err_module_private_local)
7563           << 0 << NewVD
7564           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7565           << FixItHint::CreateRemoval(
7566                  D.getDeclSpec().getModulePrivateSpecLoc());
7567     else {
7568       NewVD->setModulePrivate();
7569       if (NewTemplate)
7570         NewTemplate->setModulePrivate();
7571       for (auto *B : Bindings)
7572         B->setModulePrivate();
7573     }
7574   }
7575 
7576   if (getLangOpts().OpenCL) {
7577     deduceOpenCLAddressSpace(NewVD);
7578 
7579     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7580     if (TSC != TSCS_unspecified) {
7581       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7582            diag::err_opencl_unknown_type_specifier)
7583           << getLangOpts().getOpenCLVersionString()
7584           << DeclSpec::getSpecifierName(TSC) << 1;
7585       NewVD->setInvalidDecl();
7586     }
7587   }
7588 
7589   // Handle attributes prior to checking for duplicates in MergeVarDecl
7590   ProcessDeclAttributes(S, NewVD, D);
7591 
7592   // FIXME: This is probably the wrong location to be doing this and we should
7593   // probably be doing this for more attributes (especially for function
7594   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7595   // the code to copy attributes would be generated by TableGen.
7596   if (R->isFunctionPointerType())
7597     if (const auto *TT = R->getAs<TypedefType>())
7598       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7599 
7600   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7601       getLangOpts().SYCLIsDevice) {
7602     if (EmitTLSUnsupportedError &&
7603         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7604          (getLangOpts().OpenMPIsDevice &&
7605           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7606       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7607            diag::err_thread_unsupported);
7608 
7609     if (EmitTLSUnsupportedError &&
7610         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7611       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7612     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7613     // storage [duration]."
7614     if (SC == SC_None && S->getFnParent() != nullptr &&
7615         (NewVD->hasAttr<CUDASharedAttr>() ||
7616          NewVD->hasAttr<CUDAConstantAttr>())) {
7617       NewVD->setStorageClass(SC_Static);
7618     }
7619   }
7620 
7621   // Ensure that dllimport globals without explicit storage class are treated as
7622   // extern. The storage class is set above using parsed attributes. Now we can
7623   // check the VarDecl itself.
7624   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7625          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7626          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7627 
7628   // In auto-retain/release, infer strong retension for variables of
7629   // retainable type.
7630   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7631     NewVD->setInvalidDecl();
7632 
7633   // Handle GNU asm-label extension (encoded as an attribute).
7634   if (Expr *E = (Expr*)D.getAsmLabel()) {
7635     // The parser guarantees this is a string.
7636     StringLiteral *SE = cast<StringLiteral>(E);
7637     StringRef Label = SE->getString();
7638     if (S->getFnParent() != nullptr) {
7639       switch (SC) {
7640       case SC_None:
7641       case SC_Auto:
7642         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7643         break;
7644       case SC_Register:
7645         // Local Named register
7646         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7647             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7648           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7649         break;
7650       case SC_Static:
7651       case SC_Extern:
7652       case SC_PrivateExtern:
7653         break;
7654       }
7655     } else if (SC == SC_Register) {
7656       // Global Named register
7657       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7658         const auto &TI = Context.getTargetInfo();
7659         bool HasSizeMismatch;
7660 
7661         if (!TI.isValidGCCRegisterName(Label))
7662           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7663         else if (!TI.validateGlobalRegisterVariable(Label,
7664                                                     Context.getTypeSize(R),
7665                                                     HasSizeMismatch))
7666           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7667         else if (HasSizeMismatch)
7668           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7669       }
7670 
7671       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7672         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7673         NewVD->setInvalidDecl(true);
7674       }
7675     }
7676 
7677     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7678                                         /*IsLiteralLabel=*/true,
7679                                         SE->getStrTokenLoc(0)));
7680   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7681     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7682       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7683     if (I != ExtnameUndeclaredIdentifiers.end()) {
7684       if (isDeclExternC(NewVD)) {
7685         NewVD->addAttr(I->second);
7686         ExtnameUndeclaredIdentifiers.erase(I);
7687       } else
7688         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7689             << /*Variable*/1 << NewVD;
7690     }
7691   }
7692 
7693   // Find the shadowed declaration before filtering for scope.
7694   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7695                                 ? getShadowedDeclaration(NewVD, Previous)
7696                                 : nullptr;
7697 
7698   // Don't consider existing declarations that are in a different
7699   // scope and are out-of-semantic-context declarations (if the new
7700   // declaration has linkage).
7701   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7702                        D.getCXXScopeSpec().isNotEmpty() ||
7703                        IsMemberSpecialization ||
7704                        IsVariableTemplateSpecialization);
7705 
7706   // Check whether the previous declaration is in the same block scope. This
7707   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7708   if (getLangOpts().CPlusPlus &&
7709       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7710     NewVD->setPreviousDeclInSameBlockScope(
7711         Previous.isSingleResult() && !Previous.isShadowed() &&
7712         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7713 
7714   if (!getLangOpts().CPlusPlus) {
7715     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7716   } else {
7717     // If this is an explicit specialization of a static data member, check it.
7718     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7719         CheckMemberSpecialization(NewVD, Previous))
7720       NewVD->setInvalidDecl();
7721 
7722     // Merge the decl with the existing one if appropriate.
7723     if (!Previous.empty()) {
7724       if (Previous.isSingleResult() &&
7725           isa<FieldDecl>(Previous.getFoundDecl()) &&
7726           D.getCXXScopeSpec().isSet()) {
7727         // The user tried to define a non-static data member
7728         // out-of-line (C++ [dcl.meaning]p1).
7729         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7730           << D.getCXXScopeSpec().getRange();
7731         Previous.clear();
7732         NewVD->setInvalidDecl();
7733       }
7734     } else if (D.getCXXScopeSpec().isSet()) {
7735       // No previous declaration in the qualifying scope.
7736       Diag(D.getIdentifierLoc(), diag::err_no_member)
7737         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7738         << D.getCXXScopeSpec().getRange();
7739       NewVD->setInvalidDecl();
7740     }
7741 
7742     if (!IsVariableTemplateSpecialization)
7743       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7744 
7745     if (NewTemplate) {
7746       VarTemplateDecl *PrevVarTemplate =
7747           NewVD->getPreviousDecl()
7748               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7749               : nullptr;
7750 
7751       // Check the template parameter list of this declaration, possibly
7752       // merging in the template parameter list from the previous variable
7753       // template declaration.
7754       if (CheckTemplateParameterList(
7755               TemplateParams,
7756               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7757                               : nullptr,
7758               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7759                DC->isDependentContext())
7760                   ? TPC_ClassTemplateMember
7761                   : TPC_VarTemplate))
7762         NewVD->setInvalidDecl();
7763 
7764       // If we are providing an explicit specialization of a static variable
7765       // template, make a note of that.
7766       if (PrevVarTemplate &&
7767           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7768         PrevVarTemplate->setMemberSpecialization();
7769     }
7770   }
7771 
7772   // Diagnose shadowed variables iff this isn't a redeclaration.
7773   if (ShadowedDecl && !D.isRedeclaration())
7774     CheckShadow(NewVD, ShadowedDecl, Previous);
7775 
7776   ProcessPragmaWeak(S, NewVD);
7777 
7778   // If this is the first declaration of an extern C variable, update
7779   // the map of such variables.
7780   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7781       isIncompleteDeclExternC(*this, NewVD))
7782     RegisterLocallyScopedExternCDecl(NewVD, S);
7783 
7784   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7785     MangleNumberingContext *MCtx;
7786     Decl *ManglingContextDecl;
7787     std::tie(MCtx, ManglingContextDecl) =
7788         getCurrentMangleNumberContext(NewVD->getDeclContext());
7789     if (MCtx) {
7790       Context.setManglingNumber(
7791           NewVD, MCtx->getManglingNumber(
7792                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7793       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7794     }
7795   }
7796 
7797   // Special handling of variable named 'main'.
7798   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7799       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7800       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7801 
7802     // C++ [basic.start.main]p3
7803     // A program that declares a variable main at global scope is ill-formed.
7804     if (getLangOpts().CPlusPlus)
7805       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7806 
7807     // In C, and external-linkage variable named main results in undefined
7808     // behavior.
7809     else if (NewVD->hasExternalFormalLinkage())
7810       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7811   }
7812 
7813   if (D.isRedeclaration() && !Previous.empty()) {
7814     NamedDecl *Prev = Previous.getRepresentativeDecl();
7815     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7816                                    D.isFunctionDefinition());
7817   }
7818 
7819   if (NewTemplate) {
7820     if (NewVD->isInvalidDecl())
7821       NewTemplate->setInvalidDecl();
7822     ActOnDocumentableDecl(NewTemplate);
7823     return NewTemplate;
7824   }
7825 
7826   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7827     CompleteMemberSpecialization(NewVD, Previous);
7828 
7829   return NewVD;
7830 }
7831 
7832 /// Enum describing the %select options in diag::warn_decl_shadow.
7833 enum ShadowedDeclKind {
7834   SDK_Local,
7835   SDK_Global,
7836   SDK_StaticMember,
7837   SDK_Field,
7838   SDK_Typedef,
7839   SDK_Using,
7840   SDK_StructuredBinding
7841 };
7842 
7843 /// Determine what kind of declaration we're shadowing.
7844 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7845                                                 const DeclContext *OldDC) {
7846   if (isa<TypeAliasDecl>(ShadowedDecl))
7847     return SDK_Using;
7848   else if (isa<TypedefDecl>(ShadowedDecl))
7849     return SDK_Typedef;
7850   else if (isa<BindingDecl>(ShadowedDecl))
7851     return SDK_StructuredBinding;
7852   else if (isa<RecordDecl>(OldDC))
7853     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7854 
7855   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7856 }
7857 
7858 /// Return the location of the capture if the given lambda captures the given
7859 /// variable \p VD, or an invalid source location otherwise.
7860 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7861                                          const VarDecl *VD) {
7862   for (const Capture &Capture : LSI->Captures) {
7863     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7864       return Capture.getLocation();
7865   }
7866   return SourceLocation();
7867 }
7868 
7869 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7870                                      const LookupResult &R) {
7871   // Only diagnose if we're shadowing an unambiguous field or variable.
7872   if (R.getResultKind() != LookupResult::Found)
7873     return false;
7874 
7875   // Return false if warning is ignored.
7876   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7877 }
7878 
7879 /// Return the declaration shadowed by the given variable \p D, or null
7880 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7881 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7882                                         const LookupResult &R) {
7883   if (!shouldWarnIfShadowedDecl(Diags, R))
7884     return nullptr;
7885 
7886   // Don't diagnose declarations at file scope.
7887   if (D->hasGlobalStorage())
7888     return nullptr;
7889 
7890   NamedDecl *ShadowedDecl = R.getFoundDecl();
7891   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7892                                                             : nullptr;
7893 }
7894 
7895 /// Return the declaration shadowed by the given typedef \p D, or null
7896 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7897 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7898                                         const LookupResult &R) {
7899   // Don't warn if typedef declaration is part of a class
7900   if (D->getDeclContext()->isRecord())
7901     return nullptr;
7902 
7903   if (!shouldWarnIfShadowedDecl(Diags, R))
7904     return nullptr;
7905 
7906   NamedDecl *ShadowedDecl = R.getFoundDecl();
7907   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7908 }
7909 
7910 /// Return the declaration shadowed by the given variable \p D, or null
7911 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7912 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7913                                         const LookupResult &R) {
7914   if (!shouldWarnIfShadowedDecl(Diags, R))
7915     return nullptr;
7916 
7917   NamedDecl *ShadowedDecl = R.getFoundDecl();
7918   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7919                                                             : nullptr;
7920 }
7921 
7922 /// Diagnose variable or built-in function shadowing.  Implements
7923 /// -Wshadow.
7924 ///
7925 /// This method is called whenever a VarDecl is added to a "useful"
7926 /// scope.
7927 ///
7928 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7929 /// \param R the lookup of the name
7930 ///
7931 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7932                        const LookupResult &R) {
7933   DeclContext *NewDC = D->getDeclContext();
7934 
7935   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7936     // Fields are not shadowed by variables in C++ static methods.
7937     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7938       if (MD->isStatic())
7939         return;
7940 
7941     // Fields shadowed by constructor parameters are a special case. Usually
7942     // the constructor initializes the field with the parameter.
7943     if (isa<CXXConstructorDecl>(NewDC))
7944       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7945         // Remember that this was shadowed so we can either warn about its
7946         // modification or its existence depending on warning settings.
7947         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7948         return;
7949       }
7950   }
7951 
7952   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7953     if (shadowedVar->isExternC()) {
7954       // For shadowing external vars, make sure that we point to the global
7955       // declaration, not a locally scoped extern declaration.
7956       for (auto I : shadowedVar->redecls())
7957         if (I->isFileVarDecl()) {
7958           ShadowedDecl = I;
7959           break;
7960         }
7961     }
7962 
7963   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7964 
7965   unsigned WarningDiag = diag::warn_decl_shadow;
7966   SourceLocation CaptureLoc;
7967   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7968       isa<CXXMethodDecl>(NewDC)) {
7969     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7970       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7971         if (RD->getLambdaCaptureDefault() == LCD_None) {
7972           // Try to avoid warnings for lambdas with an explicit capture list.
7973           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7974           // Warn only when the lambda captures the shadowed decl explicitly.
7975           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7976           if (CaptureLoc.isInvalid())
7977             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7978         } else {
7979           // Remember that this was shadowed so we can avoid the warning if the
7980           // shadowed decl isn't captured and the warning settings allow it.
7981           cast<LambdaScopeInfo>(getCurFunction())
7982               ->ShadowingDecls.push_back(
7983                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7984           return;
7985         }
7986       }
7987 
7988       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7989         // A variable can't shadow a local variable in an enclosing scope, if
7990         // they are separated by a non-capturing declaration context.
7991         for (DeclContext *ParentDC = NewDC;
7992              ParentDC && !ParentDC->Equals(OldDC);
7993              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7994           // Only block literals, captured statements, and lambda expressions
7995           // can capture; other scopes don't.
7996           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7997               !isLambdaCallOperator(ParentDC)) {
7998             return;
7999           }
8000         }
8001       }
8002     }
8003   }
8004 
8005   // Only warn about certain kinds of shadowing for class members.
8006   if (NewDC && NewDC->isRecord()) {
8007     // In particular, don't warn about shadowing non-class members.
8008     if (!OldDC->isRecord())
8009       return;
8010 
8011     // TODO: should we warn about static data members shadowing
8012     // static data members from base classes?
8013 
8014     // TODO: don't diagnose for inaccessible shadowed members.
8015     // This is hard to do perfectly because we might friend the
8016     // shadowing context, but that's just a false negative.
8017   }
8018 
8019 
8020   DeclarationName Name = R.getLookupName();
8021 
8022   // Emit warning and note.
8023   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8024   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8025   if (!CaptureLoc.isInvalid())
8026     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8027         << Name << /*explicitly*/ 1;
8028   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8029 }
8030 
8031 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8032 /// when these variables are captured by the lambda.
8033 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8034   for (const auto &Shadow : LSI->ShadowingDecls) {
8035     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8036     // Try to avoid the warning when the shadowed decl isn't captured.
8037     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8038     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8039     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8040                                        ? diag::warn_decl_shadow_uncaptured_local
8041                                        : diag::warn_decl_shadow)
8042         << Shadow.VD->getDeclName()
8043         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8044     if (!CaptureLoc.isInvalid())
8045       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8046           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8047     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8048   }
8049 }
8050 
8051 /// Check -Wshadow without the advantage of a previous lookup.
8052 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8053   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8054     return;
8055 
8056   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8057                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8058   LookupName(R, S);
8059   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8060     CheckShadow(D, ShadowedDecl, R);
8061 }
8062 
8063 /// Check if 'E', which is an expression that is about to be modified, refers
8064 /// to a constructor parameter that shadows a field.
8065 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8066   // Quickly ignore expressions that can't be shadowing ctor parameters.
8067   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8068     return;
8069   E = E->IgnoreParenImpCasts();
8070   auto *DRE = dyn_cast<DeclRefExpr>(E);
8071   if (!DRE)
8072     return;
8073   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8074   auto I = ShadowingDecls.find(D);
8075   if (I == ShadowingDecls.end())
8076     return;
8077   const NamedDecl *ShadowedDecl = I->second;
8078   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8079   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8080   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8081   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8082 
8083   // Avoid issuing multiple warnings about the same decl.
8084   ShadowingDecls.erase(I);
8085 }
8086 
8087 /// Check for conflict between this global or extern "C" declaration and
8088 /// previous global or extern "C" declarations. This is only used in C++.
8089 template<typename T>
8090 static bool checkGlobalOrExternCConflict(
8091     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8092   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8093   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8094 
8095   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8096     // The common case: this global doesn't conflict with any extern "C"
8097     // declaration.
8098     return false;
8099   }
8100 
8101   if (Prev) {
8102     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8103       // Both the old and new declarations have C language linkage. This is a
8104       // redeclaration.
8105       Previous.clear();
8106       Previous.addDecl(Prev);
8107       return true;
8108     }
8109 
8110     // This is a global, non-extern "C" declaration, and there is a previous
8111     // non-global extern "C" declaration. Diagnose if this is a variable
8112     // declaration.
8113     if (!isa<VarDecl>(ND))
8114       return false;
8115   } else {
8116     // The declaration is extern "C". Check for any declaration in the
8117     // translation unit which might conflict.
8118     if (IsGlobal) {
8119       // We have already performed the lookup into the translation unit.
8120       IsGlobal = false;
8121       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8122            I != E; ++I) {
8123         if (isa<VarDecl>(*I)) {
8124           Prev = *I;
8125           break;
8126         }
8127       }
8128     } else {
8129       DeclContext::lookup_result R =
8130           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8131       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8132            I != E; ++I) {
8133         if (isa<VarDecl>(*I)) {
8134           Prev = *I;
8135           break;
8136         }
8137         // FIXME: If we have any other entity with this name in global scope,
8138         // the declaration is ill-formed, but that is a defect: it breaks the
8139         // 'stat' hack, for instance. Only variables can have mangled name
8140         // clashes with extern "C" declarations, so only they deserve a
8141         // diagnostic.
8142       }
8143     }
8144 
8145     if (!Prev)
8146       return false;
8147   }
8148 
8149   // Use the first declaration's location to ensure we point at something which
8150   // is lexically inside an extern "C" linkage-spec.
8151   assert(Prev && "should have found a previous declaration to diagnose");
8152   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8153     Prev = FD->getFirstDecl();
8154   else
8155     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8156 
8157   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8158     << IsGlobal << ND;
8159   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8160     << IsGlobal;
8161   return false;
8162 }
8163 
8164 /// Apply special rules for handling extern "C" declarations. Returns \c true
8165 /// if we have found that this is a redeclaration of some prior entity.
8166 ///
8167 /// Per C++ [dcl.link]p6:
8168 ///   Two declarations [for a function or variable] with C language linkage
8169 ///   with the same name that appear in different scopes refer to the same
8170 ///   [entity]. An entity with C language linkage shall not be declared with
8171 ///   the same name as an entity in global scope.
8172 template<typename T>
8173 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8174                                                   LookupResult &Previous) {
8175   if (!S.getLangOpts().CPlusPlus) {
8176     // In C, when declaring a global variable, look for a corresponding 'extern'
8177     // variable declared in function scope. We don't need this in C++, because
8178     // we find local extern decls in the surrounding file-scope DeclContext.
8179     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8180       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8181         Previous.clear();
8182         Previous.addDecl(Prev);
8183         return true;
8184       }
8185     }
8186     return false;
8187   }
8188 
8189   // A declaration in the translation unit can conflict with an extern "C"
8190   // declaration.
8191   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8192     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8193 
8194   // An extern "C" declaration can conflict with a declaration in the
8195   // translation unit or can be a redeclaration of an extern "C" declaration
8196   // in another scope.
8197   if (isIncompleteDeclExternC(S,ND))
8198     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8199 
8200   // Neither global nor extern "C": nothing to do.
8201   return false;
8202 }
8203 
8204 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8205   // If the decl is already known invalid, don't check it.
8206   if (NewVD->isInvalidDecl())
8207     return;
8208 
8209   QualType T = NewVD->getType();
8210 
8211   // Defer checking an 'auto' type until its initializer is attached.
8212   if (T->isUndeducedType())
8213     return;
8214 
8215   if (NewVD->hasAttrs())
8216     CheckAlignasUnderalignment(NewVD);
8217 
8218   if (T->isObjCObjectType()) {
8219     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8220       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8221     T = Context.getObjCObjectPointerType(T);
8222     NewVD->setType(T);
8223   }
8224 
8225   // Emit an error if an address space was applied to decl with local storage.
8226   // This includes arrays of objects with address space qualifiers, but not
8227   // automatic variables that point to other address spaces.
8228   // ISO/IEC TR 18037 S5.1.2
8229   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8230       T.getAddressSpace() != LangAS::Default) {
8231     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8232     NewVD->setInvalidDecl();
8233     return;
8234   }
8235 
8236   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8237   // scope.
8238   if (getLangOpts().OpenCLVersion == 120 &&
8239       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8240                                             getLangOpts()) &&
8241       NewVD->isStaticLocal()) {
8242     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8243     NewVD->setInvalidDecl();
8244     return;
8245   }
8246 
8247   if (getLangOpts().OpenCL) {
8248     if (!diagnoseOpenCLTypes(*this, NewVD))
8249       return;
8250 
8251     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8252     if (NewVD->hasAttr<BlocksAttr>()) {
8253       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8254       return;
8255     }
8256 
8257     if (T->isBlockPointerType()) {
8258       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8259       // can't use 'extern' storage class.
8260       if (!T.isConstQualified()) {
8261         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8262             << 0 /*const*/;
8263         NewVD->setInvalidDecl();
8264         return;
8265       }
8266       if (NewVD->hasExternalStorage()) {
8267         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8268         NewVD->setInvalidDecl();
8269         return;
8270       }
8271     }
8272 
8273     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8274     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8275         NewVD->hasExternalStorage()) {
8276       if (!T->isSamplerT() && !T->isDependentType() &&
8277           !(T.getAddressSpace() == LangAS::opencl_constant ||
8278             (T.getAddressSpace() == LangAS::opencl_global &&
8279              getOpenCLOptions().areProgramScopeVariablesSupported(
8280                  getLangOpts())))) {
8281         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8282         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8283           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8284               << Scope << "global or constant";
8285         else
8286           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8287               << Scope << "constant";
8288         NewVD->setInvalidDecl();
8289         return;
8290       }
8291     } else {
8292       if (T.getAddressSpace() == LangAS::opencl_global) {
8293         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8294             << 1 /*is any function*/ << "global";
8295         NewVD->setInvalidDecl();
8296         return;
8297       }
8298       if (T.getAddressSpace() == LangAS::opencl_constant ||
8299           T.getAddressSpace() == LangAS::opencl_local) {
8300         FunctionDecl *FD = getCurFunctionDecl();
8301         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8302         // in functions.
8303         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8304           if (T.getAddressSpace() == LangAS::opencl_constant)
8305             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8306                 << 0 /*non-kernel only*/ << "constant";
8307           else
8308             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8309                 << 0 /*non-kernel only*/ << "local";
8310           NewVD->setInvalidDecl();
8311           return;
8312         }
8313         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8314         // in the outermost scope of a kernel function.
8315         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8316           if (!getCurScope()->isFunctionScope()) {
8317             if (T.getAddressSpace() == LangAS::opencl_constant)
8318               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8319                   << "constant";
8320             else
8321               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8322                   << "local";
8323             NewVD->setInvalidDecl();
8324             return;
8325           }
8326         }
8327       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8328                  // If we are parsing a template we didn't deduce an addr
8329                  // space yet.
8330                  T.getAddressSpace() != LangAS::Default) {
8331         // Do not allow other address spaces on automatic variable.
8332         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8333         NewVD->setInvalidDecl();
8334         return;
8335       }
8336     }
8337   }
8338 
8339   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8340       && !NewVD->hasAttr<BlocksAttr>()) {
8341     if (getLangOpts().getGC() != LangOptions::NonGC)
8342       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8343     else {
8344       assert(!getLangOpts().ObjCAutoRefCount);
8345       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8346     }
8347   }
8348 
8349   bool isVM = T->isVariablyModifiedType();
8350   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8351       NewVD->hasAttr<BlocksAttr>())
8352     setFunctionHasBranchProtectedScope();
8353 
8354   if ((isVM && NewVD->hasLinkage()) ||
8355       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8356     bool SizeIsNegative;
8357     llvm::APSInt Oversized;
8358     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8359         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8360     QualType FixedT;
8361     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8362       FixedT = FixedTInfo->getType();
8363     else if (FixedTInfo) {
8364       // Type and type-as-written are canonically different. We need to fix up
8365       // both types separately.
8366       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8367                                                    Oversized);
8368     }
8369     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8370       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8371       // FIXME: This won't give the correct result for
8372       // int a[10][n];
8373       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8374 
8375       if (NewVD->isFileVarDecl())
8376         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8377         << SizeRange;
8378       else if (NewVD->isStaticLocal())
8379         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8380         << SizeRange;
8381       else
8382         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8383         << SizeRange;
8384       NewVD->setInvalidDecl();
8385       return;
8386     }
8387 
8388     if (!FixedTInfo) {
8389       if (NewVD->isFileVarDecl())
8390         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8391       else
8392         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8393       NewVD->setInvalidDecl();
8394       return;
8395     }
8396 
8397     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8398     NewVD->setType(FixedT);
8399     NewVD->setTypeSourceInfo(FixedTInfo);
8400   }
8401 
8402   if (T->isVoidType()) {
8403     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8404     //                    of objects and functions.
8405     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8406       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8407         << T;
8408       NewVD->setInvalidDecl();
8409       return;
8410     }
8411   }
8412 
8413   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8414     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8415     NewVD->setInvalidDecl();
8416     return;
8417   }
8418 
8419   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8420     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8421     NewVD->setInvalidDecl();
8422     return;
8423   }
8424 
8425   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8426     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8427     NewVD->setInvalidDecl();
8428     return;
8429   }
8430 
8431   if (NewVD->isConstexpr() && !T->isDependentType() &&
8432       RequireLiteralType(NewVD->getLocation(), T,
8433                          diag::err_constexpr_var_non_literal)) {
8434     NewVD->setInvalidDecl();
8435     return;
8436   }
8437 
8438   // PPC MMA non-pointer types are not allowed as non-local variable types.
8439   if (Context.getTargetInfo().getTriple().isPPC64() &&
8440       !NewVD->isLocalVarDecl() &&
8441       CheckPPCMMAType(T, NewVD->getLocation())) {
8442     NewVD->setInvalidDecl();
8443     return;
8444   }
8445 }
8446 
8447 /// Perform semantic checking on a newly-created variable
8448 /// declaration.
8449 ///
8450 /// This routine performs all of the type-checking required for a
8451 /// variable declaration once it has been built. It is used both to
8452 /// check variables after they have been parsed and their declarators
8453 /// have been translated into a declaration, and to check variables
8454 /// that have been instantiated from a template.
8455 ///
8456 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8457 ///
8458 /// Returns true if the variable declaration is a redeclaration.
8459 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8460   CheckVariableDeclarationType(NewVD);
8461 
8462   // If the decl is already known invalid, don't check it.
8463   if (NewVD->isInvalidDecl())
8464     return false;
8465 
8466   // If we did not find anything by this name, look for a non-visible
8467   // extern "C" declaration with the same name.
8468   if (Previous.empty() &&
8469       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8470     Previous.setShadowed();
8471 
8472   if (!Previous.empty()) {
8473     MergeVarDecl(NewVD, Previous);
8474     return true;
8475   }
8476   return false;
8477 }
8478 
8479 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8480 /// and if so, check that it's a valid override and remember it.
8481 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8482   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8483 
8484   // Look for methods in base classes that this method might override.
8485   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8486                      /*DetectVirtual=*/false);
8487   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8488     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8489     DeclarationName Name = MD->getDeclName();
8490 
8491     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8492       // We really want to find the base class destructor here.
8493       QualType T = Context.getTypeDeclType(BaseRecord);
8494       CanQualType CT = Context.getCanonicalType(T);
8495       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8496     }
8497 
8498     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8499       CXXMethodDecl *BaseMD =
8500           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8501       if (!BaseMD || !BaseMD->isVirtual() ||
8502           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8503                      /*ConsiderCudaAttrs=*/true,
8504                      // C++2a [class.virtual]p2 does not consider requires
8505                      // clauses when overriding.
8506                      /*ConsiderRequiresClauses=*/false))
8507         continue;
8508 
8509       if (Overridden.insert(BaseMD).second) {
8510         MD->addOverriddenMethod(BaseMD);
8511         CheckOverridingFunctionReturnType(MD, BaseMD);
8512         CheckOverridingFunctionAttributes(MD, BaseMD);
8513         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8514         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8515       }
8516 
8517       // A method can only override one function from each base class. We
8518       // don't track indirectly overridden methods from bases of bases.
8519       return true;
8520     }
8521 
8522     return false;
8523   };
8524 
8525   DC->lookupInBases(VisitBase, Paths);
8526   return !Overridden.empty();
8527 }
8528 
8529 namespace {
8530   // Struct for holding all of the extra arguments needed by
8531   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8532   struct ActOnFDArgs {
8533     Scope *S;
8534     Declarator &D;
8535     MultiTemplateParamsArg TemplateParamLists;
8536     bool AddToScope;
8537   };
8538 } // end anonymous namespace
8539 
8540 namespace {
8541 
8542 // Callback to only accept typo corrections that have a non-zero edit distance.
8543 // Also only accept corrections that have the same parent decl.
8544 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8545  public:
8546   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8547                             CXXRecordDecl *Parent)
8548       : Context(Context), OriginalFD(TypoFD),
8549         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8550 
8551   bool ValidateCandidate(const TypoCorrection &candidate) override {
8552     if (candidate.getEditDistance() == 0)
8553       return false;
8554 
8555     SmallVector<unsigned, 1> MismatchedParams;
8556     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8557                                           CDeclEnd = candidate.end();
8558          CDecl != CDeclEnd; ++CDecl) {
8559       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8560 
8561       if (FD && !FD->hasBody() &&
8562           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8563         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8564           CXXRecordDecl *Parent = MD->getParent();
8565           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8566             return true;
8567         } else if (!ExpectedParent) {
8568           return true;
8569         }
8570       }
8571     }
8572 
8573     return false;
8574   }
8575 
8576   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8577     return std::make_unique<DifferentNameValidatorCCC>(*this);
8578   }
8579 
8580  private:
8581   ASTContext &Context;
8582   FunctionDecl *OriginalFD;
8583   CXXRecordDecl *ExpectedParent;
8584 };
8585 
8586 } // end anonymous namespace
8587 
8588 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8589   TypoCorrectedFunctionDefinitions.insert(F);
8590 }
8591 
8592 /// Generate diagnostics for an invalid function redeclaration.
8593 ///
8594 /// This routine handles generating the diagnostic messages for an invalid
8595 /// function redeclaration, including finding possible similar declarations
8596 /// or performing typo correction if there are no previous declarations with
8597 /// the same name.
8598 ///
8599 /// Returns a NamedDecl iff typo correction was performed and substituting in
8600 /// the new declaration name does not cause new errors.
8601 static NamedDecl *DiagnoseInvalidRedeclaration(
8602     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8603     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8604   DeclarationName Name = NewFD->getDeclName();
8605   DeclContext *NewDC = NewFD->getDeclContext();
8606   SmallVector<unsigned, 1> MismatchedParams;
8607   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8608   TypoCorrection Correction;
8609   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8610   unsigned DiagMsg =
8611     IsLocalFriend ? diag::err_no_matching_local_friend :
8612     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8613     diag::err_member_decl_does_not_match;
8614   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8615                     IsLocalFriend ? Sema::LookupLocalFriendName
8616                                   : Sema::LookupOrdinaryName,
8617                     Sema::ForVisibleRedeclaration);
8618 
8619   NewFD->setInvalidDecl();
8620   if (IsLocalFriend)
8621     SemaRef.LookupName(Prev, S);
8622   else
8623     SemaRef.LookupQualifiedName(Prev, NewDC);
8624   assert(!Prev.isAmbiguous() &&
8625          "Cannot have an ambiguity in previous-declaration lookup");
8626   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8627   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8628                                 MD ? MD->getParent() : nullptr);
8629   if (!Prev.empty()) {
8630     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8631          Func != FuncEnd; ++Func) {
8632       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8633       if (FD &&
8634           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8635         // Add 1 to the index so that 0 can mean the mismatch didn't
8636         // involve a parameter
8637         unsigned ParamNum =
8638             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8639         NearMatches.push_back(std::make_pair(FD, ParamNum));
8640       }
8641     }
8642   // If the qualified name lookup yielded nothing, try typo correction
8643   } else if ((Correction = SemaRef.CorrectTypo(
8644                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8645                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8646                   IsLocalFriend ? nullptr : NewDC))) {
8647     // Set up everything for the call to ActOnFunctionDeclarator
8648     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8649                               ExtraArgs.D.getIdentifierLoc());
8650     Previous.clear();
8651     Previous.setLookupName(Correction.getCorrection());
8652     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8653                                     CDeclEnd = Correction.end();
8654          CDecl != CDeclEnd; ++CDecl) {
8655       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8656       if (FD && !FD->hasBody() &&
8657           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8658         Previous.addDecl(FD);
8659       }
8660     }
8661     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8662 
8663     NamedDecl *Result;
8664     // Retry building the function declaration with the new previous
8665     // declarations, and with errors suppressed.
8666     {
8667       // Trap errors.
8668       Sema::SFINAETrap Trap(SemaRef);
8669 
8670       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8671       // pieces need to verify the typo-corrected C++ declaration and hopefully
8672       // eliminate the need for the parameter pack ExtraArgs.
8673       Result = SemaRef.ActOnFunctionDeclarator(
8674           ExtraArgs.S, ExtraArgs.D,
8675           Correction.getCorrectionDecl()->getDeclContext(),
8676           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8677           ExtraArgs.AddToScope);
8678 
8679       if (Trap.hasErrorOccurred())
8680         Result = nullptr;
8681     }
8682 
8683     if (Result) {
8684       // Determine which correction we picked.
8685       Decl *Canonical = Result->getCanonicalDecl();
8686       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8687            I != E; ++I)
8688         if ((*I)->getCanonicalDecl() == Canonical)
8689           Correction.setCorrectionDecl(*I);
8690 
8691       // Let Sema know about the correction.
8692       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8693       SemaRef.diagnoseTypo(
8694           Correction,
8695           SemaRef.PDiag(IsLocalFriend
8696                           ? diag::err_no_matching_local_friend_suggest
8697                           : diag::err_member_decl_does_not_match_suggest)
8698             << Name << NewDC << IsDefinition);
8699       return Result;
8700     }
8701 
8702     // Pretend the typo correction never occurred
8703     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8704                               ExtraArgs.D.getIdentifierLoc());
8705     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8706     Previous.clear();
8707     Previous.setLookupName(Name);
8708   }
8709 
8710   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8711       << Name << NewDC << IsDefinition << NewFD->getLocation();
8712 
8713   bool NewFDisConst = false;
8714   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8715     NewFDisConst = NewMD->isConst();
8716 
8717   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8718        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8719        NearMatch != NearMatchEnd; ++NearMatch) {
8720     FunctionDecl *FD = NearMatch->first;
8721     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8722     bool FDisConst = MD && MD->isConst();
8723     bool IsMember = MD || !IsLocalFriend;
8724 
8725     // FIXME: These notes are poorly worded for the local friend case.
8726     if (unsigned Idx = NearMatch->second) {
8727       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8728       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8729       if (Loc.isInvalid()) Loc = FD->getLocation();
8730       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8731                                  : diag::note_local_decl_close_param_match)
8732         << Idx << FDParam->getType()
8733         << NewFD->getParamDecl(Idx - 1)->getType();
8734     } else if (FDisConst != NewFDisConst) {
8735       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8736           << NewFDisConst << FD->getSourceRange().getEnd()
8737           << (NewFDisConst
8738                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8739                                                  .getConstQualifierLoc())
8740                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8741                                                    .getRParenLoc()
8742                                                    .getLocWithOffset(1),
8743                                                " const"));
8744     } else
8745       SemaRef.Diag(FD->getLocation(),
8746                    IsMember ? diag::note_member_def_close_match
8747                             : diag::note_local_decl_close_match);
8748   }
8749   return nullptr;
8750 }
8751 
8752 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8753   switch (D.getDeclSpec().getStorageClassSpec()) {
8754   default: llvm_unreachable("Unknown storage class!");
8755   case DeclSpec::SCS_auto:
8756   case DeclSpec::SCS_register:
8757   case DeclSpec::SCS_mutable:
8758     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8759                  diag::err_typecheck_sclass_func);
8760     D.getMutableDeclSpec().ClearStorageClassSpecs();
8761     D.setInvalidType();
8762     break;
8763   case DeclSpec::SCS_unspecified: break;
8764   case DeclSpec::SCS_extern:
8765     if (D.getDeclSpec().isExternInLinkageSpec())
8766       return SC_None;
8767     return SC_Extern;
8768   case DeclSpec::SCS_static: {
8769     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8770       // C99 6.7.1p5:
8771       //   The declaration of an identifier for a function that has
8772       //   block scope shall have no explicit storage-class specifier
8773       //   other than extern
8774       // See also (C++ [dcl.stc]p4).
8775       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8776                    diag::err_static_block_func);
8777       break;
8778     } else
8779       return SC_Static;
8780   }
8781   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8782   }
8783 
8784   // No explicit storage class has already been returned
8785   return SC_None;
8786 }
8787 
8788 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8789                                            DeclContext *DC, QualType &R,
8790                                            TypeSourceInfo *TInfo,
8791                                            StorageClass SC,
8792                                            bool &IsVirtualOkay) {
8793   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8794   DeclarationName Name = NameInfo.getName();
8795 
8796   FunctionDecl *NewFD = nullptr;
8797   bool isInline = D.getDeclSpec().isInlineSpecified();
8798 
8799   if (!SemaRef.getLangOpts().CPlusPlus) {
8800     // Determine whether the function was written with a prototype. This is
8801     // true when:
8802     //   - there is a prototype in the declarator, or
8803     //   - the type R of the function is some kind of typedef or other non-
8804     //     attributed reference to a type name (which eventually refers to a
8805     //     function type). Note, we can't always look at the adjusted type to
8806     //     check this case because attributes may cause a non-function
8807     //     declarator to still have a function type. e.g.,
8808     //       typedef void func(int a);
8809     //       __attribute__((noreturn)) func other_func; // This has a prototype
8810     bool HasPrototype =
8811         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8812         (D.getDeclSpec().isTypeRep() &&
8813          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8814         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8815     assert(
8816         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8817         "Strict prototypes are required");
8818 
8819     NewFD = FunctionDecl::Create(
8820         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8821         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8822         ConstexprSpecKind::Unspecified,
8823         /*TrailingRequiresClause=*/nullptr);
8824     if (D.isInvalidType())
8825       NewFD->setInvalidDecl();
8826 
8827     return NewFD;
8828   }
8829 
8830   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8831 
8832   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8833   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8834     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8835                  diag::err_constexpr_wrong_decl_kind)
8836         << static_cast<int>(ConstexprKind);
8837     ConstexprKind = ConstexprSpecKind::Unspecified;
8838     D.getMutableDeclSpec().ClearConstexprSpec();
8839   }
8840   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8841 
8842   // Check that the return type is not an abstract class type.
8843   // For record types, this is done by the AbstractClassUsageDiagnoser once
8844   // the class has been completely parsed.
8845   if (!DC->isRecord() &&
8846       SemaRef.RequireNonAbstractType(
8847           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8848           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8849     D.setInvalidType();
8850 
8851   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8852     // This is a C++ constructor declaration.
8853     assert(DC->isRecord() &&
8854            "Constructors can only be declared in a member context");
8855 
8856     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8857     return CXXConstructorDecl::Create(
8858         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8859         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8860         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8861         InheritedConstructor(), TrailingRequiresClause);
8862 
8863   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8864     // This is a C++ destructor declaration.
8865     if (DC->isRecord()) {
8866       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8867       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8868       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8869           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8870           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8871           /*isImplicitlyDeclared=*/false, ConstexprKind,
8872           TrailingRequiresClause);
8873       // User defined destructors start as not selected if the class definition is still
8874       // not done.
8875       if (Record->isBeingDefined())
8876         NewDD->setIneligibleOrNotSelected(true);
8877 
8878       // If the destructor needs an implicit exception specification, set it
8879       // now. FIXME: It'd be nice to be able to create the right type to start
8880       // with, but the type needs to reference the destructor declaration.
8881       if (SemaRef.getLangOpts().CPlusPlus11)
8882         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8883 
8884       IsVirtualOkay = true;
8885       return NewDD;
8886 
8887     } else {
8888       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8889       D.setInvalidType();
8890 
8891       // Create a FunctionDecl to satisfy the function definition parsing
8892       // code path.
8893       return FunctionDecl::Create(
8894           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8895           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8896           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8897     }
8898 
8899   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8900     if (!DC->isRecord()) {
8901       SemaRef.Diag(D.getIdentifierLoc(),
8902            diag::err_conv_function_not_member);
8903       return nullptr;
8904     }
8905 
8906     SemaRef.CheckConversionDeclarator(D, R, SC);
8907     if (D.isInvalidType())
8908       return nullptr;
8909 
8910     IsVirtualOkay = true;
8911     return CXXConversionDecl::Create(
8912         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8913         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8914         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8915         TrailingRequiresClause);
8916 
8917   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8918     if (TrailingRequiresClause)
8919       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8920                    diag::err_trailing_requires_clause_on_deduction_guide)
8921           << TrailingRequiresClause->getSourceRange();
8922     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8923 
8924     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8925                                          ExplicitSpecifier, NameInfo, R, TInfo,
8926                                          D.getEndLoc());
8927   } else if (DC->isRecord()) {
8928     // If the name of the function is the same as the name of the record,
8929     // then this must be an invalid constructor that has a return type.
8930     // (The parser checks for a return type and makes the declarator a
8931     // constructor if it has no return type).
8932     if (Name.getAsIdentifierInfo() &&
8933         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8934       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8935         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8936         << SourceRange(D.getIdentifierLoc());
8937       return nullptr;
8938     }
8939 
8940     // This is a C++ method declaration.
8941     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8942         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8943         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8944         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8945     IsVirtualOkay = !Ret->isStatic();
8946     return Ret;
8947   } else {
8948     bool isFriend =
8949         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8950     if (!isFriend && SemaRef.CurContext->isRecord())
8951       return nullptr;
8952 
8953     // Determine whether the function was written with a
8954     // prototype. This true when:
8955     //   - we're in C++ (where every function has a prototype),
8956     return FunctionDecl::Create(
8957         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8958         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8959         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8960   }
8961 }
8962 
8963 enum OpenCLParamType {
8964   ValidKernelParam,
8965   PtrPtrKernelParam,
8966   PtrKernelParam,
8967   InvalidAddrSpacePtrKernelParam,
8968   InvalidKernelParam,
8969   RecordKernelParam
8970 };
8971 
8972 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8973   // Size dependent types are just typedefs to normal integer types
8974   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8975   // integers other than by their names.
8976   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8977 
8978   // Remove typedefs one by one until we reach a typedef
8979   // for a size dependent type.
8980   QualType DesugaredTy = Ty;
8981   do {
8982     ArrayRef<StringRef> Names(SizeTypeNames);
8983     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8984     if (Names.end() != Match)
8985       return true;
8986 
8987     Ty = DesugaredTy;
8988     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8989   } while (DesugaredTy != Ty);
8990 
8991   return false;
8992 }
8993 
8994 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8995   if (PT->isDependentType())
8996     return InvalidKernelParam;
8997 
8998   if (PT->isPointerType() || PT->isReferenceType()) {
8999     QualType PointeeType = PT->getPointeeType();
9000     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9001         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9002         PointeeType.getAddressSpace() == LangAS::Default)
9003       return InvalidAddrSpacePtrKernelParam;
9004 
9005     if (PointeeType->isPointerType()) {
9006       // This is a pointer to pointer parameter.
9007       // Recursively check inner type.
9008       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9009       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9010           ParamKind == InvalidKernelParam)
9011         return ParamKind;
9012 
9013       return PtrPtrKernelParam;
9014     }
9015 
9016     // C++ for OpenCL v1.0 s2.4:
9017     // Moreover the types used in parameters of the kernel functions must be:
9018     // Standard layout types for pointer parameters. The same applies to
9019     // reference if an implementation supports them in kernel parameters.
9020     if (S.getLangOpts().OpenCLCPlusPlus &&
9021         !S.getOpenCLOptions().isAvailableOption(
9022             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9023         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9024         !PointeeType->isStandardLayoutType())
9025       return InvalidKernelParam;
9026 
9027     return PtrKernelParam;
9028   }
9029 
9030   // OpenCL v1.2 s6.9.k:
9031   // Arguments to kernel functions in a program cannot be declared with the
9032   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9033   // uintptr_t or a struct and/or union that contain fields declared to be one
9034   // of these built-in scalar types.
9035   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9036     return InvalidKernelParam;
9037 
9038   if (PT->isImageType())
9039     return PtrKernelParam;
9040 
9041   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9042     return InvalidKernelParam;
9043 
9044   // OpenCL extension spec v1.2 s9.5:
9045   // This extension adds support for half scalar and vector types as built-in
9046   // types that can be used for arithmetic operations, conversions etc.
9047   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9048       PT->isHalfType())
9049     return InvalidKernelParam;
9050 
9051   // Look into an array argument to check if it has a forbidden type.
9052   if (PT->isArrayType()) {
9053     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9054     // Call ourself to check an underlying type of an array. Since the
9055     // getPointeeOrArrayElementType returns an innermost type which is not an
9056     // array, this recursive call only happens once.
9057     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9058   }
9059 
9060   // C++ for OpenCL v1.0 s2.4:
9061   // Moreover the types used in parameters of the kernel functions must be:
9062   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9063   // types) for parameters passed by value;
9064   if (S.getLangOpts().OpenCLCPlusPlus &&
9065       !S.getOpenCLOptions().isAvailableOption(
9066           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9067       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9068     return InvalidKernelParam;
9069 
9070   if (PT->isRecordType())
9071     return RecordKernelParam;
9072 
9073   return ValidKernelParam;
9074 }
9075 
9076 static void checkIsValidOpenCLKernelParameter(
9077   Sema &S,
9078   Declarator &D,
9079   ParmVarDecl *Param,
9080   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9081   QualType PT = Param->getType();
9082 
9083   // Cache the valid types we encounter to avoid rechecking structs that are
9084   // used again
9085   if (ValidTypes.count(PT.getTypePtr()))
9086     return;
9087 
9088   switch (getOpenCLKernelParameterType(S, PT)) {
9089   case PtrPtrKernelParam:
9090     // OpenCL v3.0 s6.11.a:
9091     // A kernel function argument cannot be declared as a pointer to a pointer
9092     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9093     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9094       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9095       D.setInvalidType();
9096       return;
9097     }
9098 
9099     ValidTypes.insert(PT.getTypePtr());
9100     return;
9101 
9102   case InvalidAddrSpacePtrKernelParam:
9103     // OpenCL v1.0 s6.5:
9104     // __kernel function arguments declared to be a pointer of a type can point
9105     // to one of the following address spaces only : __global, __local or
9106     // __constant.
9107     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9108     D.setInvalidType();
9109     return;
9110 
9111     // OpenCL v1.2 s6.9.k:
9112     // Arguments to kernel functions in a program cannot be declared with the
9113     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9114     // uintptr_t or a struct and/or union that contain fields declared to be
9115     // one of these built-in scalar types.
9116 
9117   case InvalidKernelParam:
9118     // OpenCL v1.2 s6.8 n:
9119     // A kernel function argument cannot be declared
9120     // of event_t type.
9121     // Do not diagnose half type since it is diagnosed as invalid argument
9122     // type for any function elsewhere.
9123     if (!PT->isHalfType()) {
9124       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9125 
9126       // Explain what typedefs are involved.
9127       const TypedefType *Typedef = nullptr;
9128       while ((Typedef = PT->getAs<TypedefType>())) {
9129         SourceLocation Loc = Typedef->getDecl()->getLocation();
9130         // SourceLocation may be invalid for a built-in type.
9131         if (Loc.isValid())
9132           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9133         PT = Typedef->desugar();
9134       }
9135     }
9136 
9137     D.setInvalidType();
9138     return;
9139 
9140   case PtrKernelParam:
9141   case ValidKernelParam:
9142     ValidTypes.insert(PT.getTypePtr());
9143     return;
9144 
9145   case RecordKernelParam:
9146     break;
9147   }
9148 
9149   // Track nested structs we will inspect
9150   SmallVector<const Decl *, 4> VisitStack;
9151 
9152   // Track where we are in the nested structs. Items will migrate from
9153   // VisitStack to HistoryStack as we do the DFS for bad field.
9154   SmallVector<const FieldDecl *, 4> HistoryStack;
9155   HistoryStack.push_back(nullptr);
9156 
9157   // At this point we already handled everything except of a RecordType or
9158   // an ArrayType of a RecordType.
9159   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9160   const RecordType *RecTy =
9161       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9162   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9163 
9164   VisitStack.push_back(RecTy->getDecl());
9165   assert(VisitStack.back() && "First decl null?");
9166 
9167   do {
9168     const Decl *Next = VisitStack.pop_back_val();
9169     if (!Next) {
9170       assert(!HistoryStack.empty());
9171       // Found a marker, we have gone up a level
9172       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9173         ValidTypes.insert(Hist->getType().getTypePtr());
9174 
9175       continue;
9176     }
9177 
9178     // Adds everything except the original parameter declaration (which is not a
9179     // field itself) to the history stack.
9180     const RecordDecl *RD;
9181     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9182       HistoryStack.push_back(Field);
9183 
9184       QualType FieldTy = Field->getType();
9185       // Other field types (known to be valid or invalid) are handled while we
9186       // walk around RecordDecl::fields().
9187       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9188              "Unexpected type.");
9189       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9190 
9191       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9192     } else {
9193       RD = cast<RecordDecl>(Next);
9194     }
9195 
9196     // Add a null marker so we know when we've gone back up a level
9197     VisitStack.push_back(nullptr);
9198 
9199     for (const auto *FD : RD->fields()) {
9200       QualType QT = FD->getType();
9201 
9202       if (ValidTypes.count(QT.getTypePtr()))
9203         continue;
9204 
9205       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9206       if (ParamType == ValidKernelParam)
9207         continue;
9208 
9209       if (ParamType == RecordKernelParam) {
9210         VisitStack.push_back(FD);
9211         continue;
9212       }
9213 
9214       // OpenCL v1.2 s6.9.p:
9215       // Arguments to kernel functions that are declared to be a struct or union
9216       // do not allow OpenCL objects to be passed as elements of the struct or
9217       // union.
9218       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9219           ParamType == InvalidAddrSpacePtrKernelParam) {
9220         S.Diag(Param->getLocation(),
9221                diag::err_record_with_pointers_kernel_param)
9222           << PT->isUnionType()
9223           << PT;
9224       } else {
9225         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9226       }
9227 
9228       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9229           << OrigRecDecl->getDeclName();
9230 
9231       // We have an error, now let's go back up through history and show where
9232       // the offending field came from
9233       for (ArrayRef<const FieldDecl *>::const_iterator
9234                I = HistoryStack.begin() + 1,
9235                E = HistoryStack.end();
9236            I != E; ++I) {
9237         const FieldDecl *OuterField = *I;
9238         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9239           << OuterField->getType();
9240       }
9241 
9242       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9243         << QT->isPointerType()
9244         << QT;
9245       D.setInvalidType();
9246       return;
9247     }
9248   } while (!VisitStack.empty());
9249 }
9250 
9251 /// Find the DeclContext in which a tag is implicitly declared if we see an
9252 /// elaborated type specifier in the specified context, and lookup finds
9253 /// nothing.
9254 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9255   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9256     DC = DC->getParent();
9257   return DC;
9258 }
9259 
9260 /// Find the Scope in which a tag is implicitly declared if we see an
9261 /// elaborated type specifier in the specified context, and lookup finds
9262 /// nothing.
9263 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9264   while (S->isClassScope() ||
9265          (LangOpts.CPlusPlus &&
9266           S->isFunctionPrototypeScope()) ||
9267          ((S->getFlags() & Scope::DeclScope) == 0) ||
9268          (S->getEntity() && S->getEntity()->isTransparentContext()))
9269     S = S->getParent();
9270   return S;
9271 }
9272 
9273 /// Determine whether a declaration matches a known function in namespace std.
9274 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9275                          unsigned BuiltinID) {
9276   switch (BuiltinID) {
9277   case Builtin::BI__GetExceptionInfo:
9278     // No type checking whatsoever.
9279     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9280 
9281   case Builtin::BIaddressof:
9282   case Builtin::BI__addressof:
9283   case Builtin::BIforward:
9284   case Builtin::BImove:
9285   case Builtin::BImove_if_noexcept:
9286   case Builtin::BIas_const: {
9287     // Ensure that we don't treat the algorithm
9288     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9289     // as the builtin std::move.
9290     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9291     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9292   }
9293 
9294   default:
9295     return false;
9296   }
9297 }
9298 
9299 NamedDecl*
9300 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9301                               TypeSourceInfo *TInfo, LookupResult &Previous,
9302                               MultiTemplateParamsArg TemplateParamListsRef,
9303                               bool &AddToScope) {
9304   QualType R = TInfo->getType();
9305 
9306   assert(R->isFunctionType());
9307   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9308     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9309 
9310   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9311   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9312   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9313     if (!TemplateParamLists.empty() &&
9314         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9315       TemplateParamLists.back() = Invented;
9316     else
9317       TemplateParamLists.push_back(Invented);
9318   }
9319 
9320   // TODO: consider using NameInfo for diagnostic.
9321   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9322   DeclarationName Name = NameInfo.getName();
9323   StorageClass SC = getFunctionStorageClass(*this, D);
9324 
9325   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9326     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9327          diag::err_invalid_thread)
9328       << DeclSpec::getSpecifierName(TSCS);
9329 
9330   if (D.isFirstDeclarationOfMember())
9331     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9332                            D.getIdentifierLoc());
9333 
9334   bool isFriend = false;
9335   FunctionTemplateDecl *FunctionTemplate = nullptr;
9336   bool isMemberSpecialization = false;
9337   bool isFunctionTemplateSpecialization = false;
9338 
9339   bool isDependentClassScopeExplicitSpecialization = false;
9340   bool HasExplicitTemplateArgs = false;
9341   TemplateArgumentListInfo TemplateArgs;
9342 
9343   bool isVirtualOkay = false;
9344 
9345   DeclContext *OriginalDC = DC;
9346   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9347 
9348   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9349                                               isVirtualOkay);
9350   if (!NewFD) return nullptr;
9351 
9352   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9353     NewFD->setTopLevelDeclInObjCContainer();
9354 
9355   // Set the lexical context. If this is a function-scope declaration, or has a
9356   // C++ scope specifier, or is the object of a friend declaration, the lexical
9357   // context will be different from the semantic context.
9358   NewFD->setLexicalDeclContext(CurContext);
9359 
9360   if (IsLocalExternDecl)
9361     NewFD->setLocalExternDecl();
9362 
9363   if (getLangOpts().CPlusPlus) {
9364     bool isInline = D.getDeclSpec().isInlineSpecified();
9365     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9366     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9367     isFriend = D.getDeclSpec().isFriendSpecified();
9368     if (isFriend && !isInline && D.isFunctionDefinition()) {
9369       // C++ [class.friend]p5
9370       //   A function can be defined in a friend declaration of a
9371       //   class . . . . Such a function is implicitly inline.
9372       NewFD->setImplicitlyInline();
9373     }
9374 
9375     // If this is a method defined in an __interface, and is not a constructor
9376     // or an overloaded operator, then set the pure flag (isVirtual will already
9377     // return true).
9378     if (const CXXRecordDecl *Parent =
9379           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9380       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9381         NewFD->setPure(true);
9382 
9383       // C++ [class.union]p2
9384       //   A union can have member functions, but not virtual functions.
9385       if (isVirtual && Parent->isUnion()) {
9386         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9387         NewFD->setInvalidDecl();
9388       }
9389       if ((Parent->isClass() || Parent->isStruct()) &&
9390           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9391           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9392           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9393         if (auto *Def = Parent->getDefinition())
9394           Def->setInitMethod(true);
9395       }
9396     }
9397 
9398     SetNestedNameSpecifier(*this, NewFD, D);
9399     isMemberSpecialization = false;
9400     isFunctionTemplateSpecialization = false;
9401     if (D.isInvalidType())
9402       NewFD->setInvalidDecl();
9403 
9404     // Match up the template parameter lists with the scope specifier, then
9405     // determine whether we have a template or a template specialization.
9406     bool Invalid = false;
9407     TemplateParameterList *TemplateParams =
9408         MatchTemplateParametersToScopeSpecifier(
9409             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9410             D.getCXXScopeSpec(),
9411             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9412                 ? D.getName().TemplateId
9413                 : nullptr,
9414             TemplateParamLists, isFriend, isMemberSpecialization,
9415             Invalid);
9416     if (TemplateParams) {
9417       // Check that we can declare a template here.
9418       if (CheckTemplateDeclScope(S, TemplateParams))
9419         NewFD->setInvalidDecl();
9420 
9421       if (TemplateParams->size() > 0) {
9422         // This is a function template
9423 
9424         // A destructor cannot be a template.
9425         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9426           Diag(NewFD->getLocation(), diag::err_destructor_template);
9427           NewFD->setInvalidDecl();
9428         }
9429 
9430         // If we're adding a template to a dependent context, we may need to
9431         // rebuilding some of the types used within the template parameter list,
9432         // now that we know what the current instantiation is.
9433         if (DC->isDependentContext()) {
9434           ContextRAII SavedContext(*this, DC);
9435           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9436             Invalid = true;
9437         }
9438 
9439         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9440                                                         NewFD->getLocation(),
9441                                                         Name, TemplateParams,
9442                                                         NewFD);
9443         FunctionTemplate->setLexicalDeclContext(CurContext);
9444         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9445 
9446         // For source fidelity, store the other template param lists.
9447         if (TemplateParamLists.size() > 1) {
9448           NewFD->setTemplateParameterListsInfo(Context,
9449               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9450                   .drop_back(1));
9451         }
9452       } else {
9453         // This is a function template specialization.
9454         isFunctionTemplateSpecialization = true;
9455         // For source fidelity, store all the template param lists.
9456         if (TemplateParamLists.size() > 0)
9457           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9458 
9459         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9460         if (isFriend) {
9461           // We want to remove the "template<>", found here.
9462           SourceRange RemoveRange = TemplateParams->getSourceRange();
9463 
9464           // If we remove the template<> and the name is not a
9465           // template-id, we're actually silently creating a problem:
9466           // the friend declaration will refer to an untemplated decl,
9467           // and clearly the user wants a template specialization.  So
9468           // we need to insert '<>' after the name.
9469           SourceLocation InsertLoc;
9470           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9471             InsertLoc = D.getName().getSourceRange().getEnd();
9472             InsertLoc = getLocForEndOfToken(InsertLoc);
9473           }
9474 
9475           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9476             << Name << RemoveRange
9477             << FixItHint::CreateRemoval(RemoveRange)
9478             << FixItHint::CreateInsertion(InsertLoc, "<>");
9479           Invalid = true;
9480         }
9481       }
9482     } else {
9483       // Check that we can declare a template here.
9484       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9485           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9486         NewFD->setInvalidDecl();
9487 
9488       // All template param lists were matched against the scope specifier:
9489       // this is NOT (an explicit specialization of) a template.
9490       if (TemplateParamLists.size() > 0)
9491         // For source fidelity, store all the template param lists.
9492         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9493     }
9494 
9495     if (Invalid) {
9496       NewFD->setInvalidDecl();
9497       if (FunctionTemplate)
9498         FunctionTemplate->setInvalidDecl();
9499     }
9500 
9501     // C++ [dcl.fct.spec]p5:
9502     //   The virtual specifier shall only be used in declarations of
9503     //   nonstatic class member functions that appear within a
9504     //   member-specification of a class declaration; see 10.3.
9505     //
9506     if (isVirtual && !NewFD->isInvalidDecl()) {
9507       if (!isVirtualOkay) {
9508         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9509              diag::err_virtual_non_function);
9510       } else if (!CurContext->isRecord()) {
9511         // 'virtual' was specified outside of the class.
9512         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9513              diag::err_virtual_out_of_class)
9514           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9515       } else if (NewFD->getDescribedFunctionTemplate()) {
9516         // C++ [temp.mem]p3:
9517         //  A member function template shall not be virtual.
9518         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9519              diag::err_virtual_member_function_template)
9520           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9521       } else {
9522         // Okay: Add virtual to the method.
9523         NewFD->setVirtualAsWritten(true);
9524       }
9525 
9526       if (getLangOpts().CPlusPlus14 &&
9527           NewFD->getReturnType()->isUndeducedType())
9528         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9529     }
9530 
9531     if (getLangOpts().CPlusPlus14 &&
9532         (NewFD->isDependentContext() ||
9533          (isFriend && CurContext->isDependentContext())) &&
9534         NewFD->getReturnType()->isUndeducedType()) {
9535       // If the function template is referenced directly (for instance, as a
9536       // member of the current instantiation), pretend it has a dependent type.
9537       // This is not really justified by the standard, but is the only sane
9538       // thing to do.
9539       // FIXME: For a friend function, we have not marked the function as being
9540       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9541       const FunctionProtoType *FPT =
9542           NewFD->getType()->castAs<FunctionProtoType>();
9543       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9544       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9545                                              FPT->getExtProtoInfo()));
9546     }
9547 
9548     // C++ [dcl.fct.spec]p3:
9549     //  The inline specifier shall not appear on a block scope function
9550     //  declaration.
9551     if (isInline && !NewFD->isInvalidDecl()) {
9552       if (CurContext->isFunctionOrMethod()) {
9553         // 'inline' is not allowed on block scope function declaration.
9554         Diag(D.getDeclSpec().getInlineSpecLoc(),
9555              diag::err_inline_declaration_block_scope) << Name
9556           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9557       }
9558     }
9559 
9560     // C++ [dcl.fct.spec]p6:
9561     //  The explicit specifier shall be used only in the declaration of a
9562     //  constructor or conversion function within its class definition;
9563     //  see 12.3.1 and 12.3.2.
9564     if (hasExplicit && !NewFD->isInvalidDecl() &&
9565         !isa<CXXDeductionGuideDecl>(NewFD)) {
9566       if (!CurContext->isRecord()) {
9567         // 'explicit' was specified outside of the class.
9568         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9569              diag::err_explicit_out_of_class)
9570             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9571       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9572                  !isa<CXXConversionDecl>(NewFD)) {
9573         // 'explicit' was specified on a function that wasn't a constructor
9574         // or conversion function.
9575         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9576              diag::err_explicit_non_ctor_or_conv_function)
9577             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9578       }
9579     }
9580 
9581     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9582     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9583       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9584       // are implicitly inline.
9585       NewFD->setImplicitlyInline();
9586 
9587       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9588       // be either constructors or to return a literal type. Therefore,
9589       // destructors cannot be declared constexpr.
9590       if (isa<CXXDestructorDecl>(NewFD) &&
9591           (!getLangOpts().CPlusPlus20 ||
9592            ConstexprKind == ConstexprSpecKind::Consteval)) {
9593         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9594             << static_cast<int>(ConstexprKind);
9595         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9596                                     ? ConstexprSpecKind::Unspecified
9597                                     : ConstexprSpecKind::Constexpr);
9598       }
9599       // C++20 [dcl.constexpr]p2: An allocation function, or a
9600       // deallocation function shall not be declared with the consteval
9601       // specifier.
9602       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9603           (NewFD->getOverloadedOperator() == OO_New ||
9604            NewFD->getOverloadedOperator() == OO_Array_New ||
9605            NewFD->getOverloadedOperator() == OO_Delete ||
9606            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9607         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9608              diag::err_invalid_consteval_decl_kind)
9609             << NewFD;
9610         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9611       }
9612     }
9613 
9614     // If __module_private__ was specified, mark the function accordingly.
9615     if (D.getDeclSpec().isModulePrivateSpecified()) {
9616       if (isFunctionTemplateSpecialization) {
9617         SourceLocation ModulePrivateLoc
9618           = D.getDeclSpec().getModulePrivateSpecLoc();
9619         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9620           << 0
9621           << FixItHint::CreateRemoval(ModulePrivateLoc);
9622       } else {
9623         NewFD->setModulePrivate();
9624         if (FunctionTemplate)
9625           FunctionTemplate->setModulePrivate();
9626       }
9627     }
9628 
9629     if (isFriend) {
9630       if (FunctionTemplate) {
9631         FunctionTemplate->setObjectOfFriendDecl();
9632         FunctionTemplate->setAccess(AS_public);
9633       }
9634       NewFD->setObjectOfFriendDecl();
9635       NewFD->setAccess(AS_public);
9636     }
9637 
9638     // If a function is defined as defaulted or deleted, mark it as such now.
9639     // We'll do the relevant checks on defaulted / deleted functions later.
9640     switch (D.getFunctionDefinitionKind()) {
9641     case FunctionDefinitionKind::Declaration:
9642     case FunctionDefinitionKind::Definition:
9643       break;
9644 
9645     case FunctionDefinitionKind::Defaulted:
9646       NewFD->setDefaulted();
9647       break;
9648 
9649     case FunctionDefinitionKind::Deleted:
9650       NewFD->setDeletedAsWritten();
9651       break;
9652     }
9653 
9654     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9655         D.isFunctionDefinition()) {
9656       // C++ [class.mfct]p2:
9657       //   A member function may be defined (8.4) in its class definition, in
9658       //   which case it is an inline member function (7.1.2)
9659       NewFD->setImplicitlyInline();
9660     }
9661 
9662     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9663         !CurContext->isRecord()) {
9664       // C++ [class.static]p1:
9665       //   A data or function member of a class may be declared static
9666       //   in a class definition, in which case it is a static member of
9667       //   the class.
9668 
9669       // Complain about the 'static' specifier if it's on an out-of-line
9670       // member function definition.
9671 
9672       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9673       // member function template declaration and class member template
9674       // declaration (MSVC versions before 2015), warn about this.
9675       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9676            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9677              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9678            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9679            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9680         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9681     }
9682 
9683     // C++11 [except.spec]p15:
9684     //   A deallocation function with no exception-specification is treated
9685     //   as if it were specified with noexcept(true).
9686     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9687     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9688          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9689         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9690       NewFD->setType(Context.getFunctionType(
9691           FPT->getReturnType(), FPT->getParamTypes(),
9692           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9693   }
9694 
9695   // Filter out previous declarations that don't match the scope.
9696   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9697                        D.getCXXScopeSpec().isNotEmpty() ||
9698                        isMemberSpecialization ||
9699                        isFunctionTemplateSpecialization);
9700 
9701   // Handle GNU asm-label extension (encoded as an attribute).
9702   if (Expr *E = (Expr*) D.getAsmLabel()) {
9703     // The parser guarantees this is a string.
9704     StringLiteral *SE = cast<StringLiteral>(E);
9705     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9706                                         /*IsLiteralLabel=*/true,
9707                                         SE->getStrTokenLoc(0)));
9708   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9709     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9710       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9711     if (I != ExtnameUndeclaredIdentifiers.end()) {
9712       if (isDeclExternC(NewFD)) {
9713         NewFD->addAttr(I->second);
9714         ExtnameUndeclaredIdentifiers.erase(I);
9715       } else
9716         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9717             << /*Variable*/0 << NewFD;
9718     }
9719   }
9720 
9721   // Copy the parameter declarations from the declarator D to the function
9722   // declaration NewFD, if they are available.  First scavenge them into Params.
9723   SmallVector<ParmVarDecl*, 16> Params;
9724   unsigned FTIIdx;
9725   if (D.isFunctionDeclarator(FTIIdx)) {
9726     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9727 
9728     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9729     // function that takes no arguments, not a function that takes a
9730     // single void argument.
9731     // We let through "const void" here because Sema::GetTypeForDeclarator
9732     // already checks for that case.
9733     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9734       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9735         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9736         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9737         Param->setDeclContext(NewFD);
9738         Params.push_back(Param);
9739 
9740         if (Param->isInvalidDecl())
9741           NewFD->setInvalidDecl();
9742       }
9743     }
9744 
9745     if (!getLangOpts().CPlusPlus) {
9746       // In C, find all the tag declarations from the prototype and move them
9747       // into the function DeclContext. Remove them from the surrounding tag
9748       // injection context of the function, which is typically but not always
9749       // the TU.
9750       DeclContext *PrototypeTagContext =
9751           getTagInjectionContext(NewFD->getLexicalDeclContext());
9752       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9753         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9754 
9755         // We don't want to reparent enumerators. Look at their parent enum
9756         // instead.
9757         if (!TD) {
9758           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9759             TD = cast<EnumDecl>(ECD->getDeclContext());
9760         }
9761         if (!TD)
9762           continue;
9763         DeclContext *TagDC = TD->getLexicalDeclContext();
9764         if (!TagDC->containsDecl(TD))
9765           continue;
9766         TagDC->removeDecl(TD);
9767         TD->setDeclContext(NewFD);
9768         NewFD->addDecl(TD);
9769 
9770         // Preserve the lexical DeclContext if it is not the surrounding tag
9771         // injection context of the FD. In this example, the semantic context of
9772         // E will be f and the lexical context will be S, while both the
9773         // semantic and lexical contexts of S will be f:
9774         //   void f(struct S { enum E { a } f; } s);
9775         if (TagDC != PrototypeTagContext)
9776           TD->setLexicalDeclContext(TagDC);
9777       }
9778     }
9779   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9780     // When we're declaring a function with a typedef, typeof, etc as in the
9781     // following example, we'll need to synthesize (unnamed)
9782     // parameters for use in the declaration.
9783     //
9784     // @code
9785     // typedef void fn(int);
9786     // fn f;
9787     // @endcode
9788 
9789     // Synthesize a parameter for each argument type.
9790     for (const auto &AI : FT->param_types()) {
9791       ParmVarDecl *Param =
9792           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9793       Param->setScopeInfo(0, Params.size());
9794       Params.push_back(Param);
9795     }
9796   } else {
9797     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9798            "Should not need args for typedef of non-prototype fn");
9799   }
9800 
9801   // Finally, we know we have the right number of parameters, install them.
9802   NewFD->setParams(Params);
9803 
9804   if (D.getDeclSpec().isNoreturnSpecified())
9805     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9806                                            D.getDeclSpec().getNoreturnSpecLoc(),
9807                                            AttributeCommonInfo::AS_Keyword));
9808 
9809   // Functions returning a variably modified type violate C99 6.7.5.2p2
9810   // because all functions have linkage.
9811   if (!NewFD->isInvalidDecl() &&
9812       NewFD->getReturnType()->isVariablyModifiedType()) {
9813     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9814     NewFD->setInvalidDecl();
9815   }
9816 
9817   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9818   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9819       !NewFD->hasAttr<SectionAttr>())
9820     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9821         Context, PragmaClangTextSection.SectionName,
9822         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9823 
9824   // Apply an implicit SectionAttr if #pragma code_seg is active.
9825   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9826       !NewFD->hasAttr<SectionAttr>()) {
9827     NewFD->addAttr(SectionAttr::CreateImplicit(
9828         Context, CodeSegStack.CurrentValue->getString(),
9829         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9830         SectionAttr::Declspec_allocate));
9831     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9832                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9833                          ASTContext::PSF_Read,
9834                      NewFD))
9835       NewFD->dropAttr<SectionAttr>();
9836   }
9837 
9838   // Apply an implicit CodeSegAttr from class declspec or
9839   // apply an implicit SectionAttr from #pragma code_seg if active.
9840   if (!NewFD->hasAttr<CodeSegAttr>()) {
9841     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9842                                                                  D.isFunctionDefinition())) {
9843       NewFD->addAttr(SAttr);
9844     }
9845   }
9846 
9847   // Handle attributes.
9848   ProcessDeclAttributes(S, NewFD, D);
9849 
9850   if (getLangOpts().OpenCL) {
9851     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9852     // type declaration will generate a compilation error.
9853     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9854     if (AddressSpace != LangAS::Default) {
9855       Diag(NewFD->getLocation(),
9856            diag::err_opencl_return_value_with_address_space);
9857       NewFD->setInvalidDecl();
9858     }
9859   }
9860 
9861   if (!getLangOpts().CPlusPlus) {
9862     // Perform semantic checking on the function declaration.
9863     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9864       CheckMain(NewFD, D.getDeclSpec());
9865 
9866     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9867       CheckMSVCRTEntryPoint(NewFD);
9868 
9869     if (!NewFD->isInvalidDecl())
9870       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9871                                                   isMemberSpecialization,
9872                                                   D.isFunctionDefinition()));
9873     else if (!Previous.empty())
9874       // Recover gracefully from an invalid redeclaration.
9875       D.setRedeclaration(true);
9876     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9877             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9878            "previous declaration set still overloaded");
9879 
9880     // Diagnose no-prototype function declarations with calling conventions that
9881     // don't support variadic calls. Only do this in C and do it after merging
9882     // possibly prototyped redeclarations.
9883     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9884     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9885       CallingConv CC = FT->getExtInfo().getCC();
9886       if (!supportsVariadicCall(CC)) {
9887         // Windows system headers sometimes accidentally use stdcall without
9888         // (void) parameters, so we relax this to a warning.
9889         int DiagID =
9890             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9891         Diag(NewFD->getLocation(), DiagID)
9892             << FunctionType::getNameForCallConv(CC);
9893       }
9894     }
9895 
9896    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9897        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9898      checkNonTrivialCUnion(NewFD->getReturnType(),
9899                            NewFD->getReturnTypeSourceRange().getBegin(),
9900                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9901   } else {
9902     // C++11 [replacement.functions]p3:
9903     //  The program's definitions shall not be specified as inline.
9904     //
9905     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9906     //
9907     // Suppress the diagnostic if the function is __attribute__((used)), since
9908     // that forces an external definition to be emitted.
9909     if (D.getDeclSpec().isInlineSpecified() &&
9910         NewFD->isReplaceableGlobalAllocationFunction() &&
9911         !NewFD->hasAttr<UsedAttr>())
9912       Diag(D.getDeclSpec().getInlineSpecLoc(),
9913            diag::ext_operator_new_delete_declared_inline)
9914         << NewFD->getDeclName();
9915 
9916     // If the declarator is a template-id, translate the parser's template
9917     // argument list into our AST format.
9918     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9919       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9920       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9921       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9922       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9923                                          TemplateId->NumArgs);
9924       translateTemplateArguments(TemplateArgsPtr,
9925                                  TemplateArgs);
9926 
9927       HasExplicitTemplateArgs = true;
9928 
9929       if (NewFD->isInvalidDecl()) {
9930         HasExplicitTemplateArgs = false;
9931       } else if (FunctionTemplate) {
9932         // Function template with explicit template arguments.
9933         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9934           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9935 
9936         HasExplicitTemplateArgs = false;
9937       } else {
9938         assert((isFunctionTemplateSpecialization ||
9939                 D.getDeclSpec().isFriendSpecified()) &&
9940                "should have a 'template<>' for this decl");
9941         // "friend void foo<>(int);" is an implicit specialization decl.
9942         isFunctionTemplateSpecialization = true;
9943       }
9944     } else if (isFriend && isFunctionTemplateSpecialization) {
9945       // This combination is only possible in a recovery case;  the user
9946       // wrote something like:
9947       //   template <> friend void foo(int);
9948       // which we're recovering from as if the user had written:
9949       //   friend void foo<>(int);
9950       // Go ahead and fake up a template id.
9951       HasExplicitTemplateArgs = true;
9952       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9953       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9954     }
9955 
9956     // We do not add HD attributes to specializations here because
9957     // they may have different constexpr-ness compared to their
9958     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9959     // may end up with different effective targets. Instead, a
9960     // specialization inherits its target attributes from its template
9961     // in the CheckFunctionTemplateSpecialization() call below.
9962     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9963       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9964 
9965     // If it's a friend (and only if it's a friend), it's possible
9966     // that either the specialized function type or the specialized
9967     // template is dependent, and therefore matching will fail.  In
9968     // this case, don't check the specialization yet.
9969     if (isFunctionTemplateSpecialization && isFriend &&
9970         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9971          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9972              TemplateArgs.arguments()))) {
9973       assert(HasExplicitTemplateArgs &&
9974              "friend function specialization without template args");
9975       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9976                                                        Previous))
9977         NewFD->setInvalidDecl();
9978     } else if (isFunctionTemplateSpecialization) {
9979       if (CurContext->isDependentContext() && CurContext->isRecord()
9980           && !isFriend) {
9981         isDependentClassScopeExplicitSpecialization = true;
9982       } else if (!NewFD->isInvalidDecl() &&
9983                  CheckFunctionTemplateSpecialization(
9984                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9985                      Previous))
9986         NewFD->setInvalidDecl();
9987 
9988       // C++ [dcl.stc]p1:
9989       //   A storage-class-specifier shall not be specified in an explicit
9990       //   specialization (14.7.3)
9991       FunctionTemplateSpecializationInfo *Info =
9992           NewFD->getTemplateSpecializationInfo();
9993       if (Info && SC != SC_None) {
9994         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9995           Diag(NewFD->getLocation(),
9996                diag::err_explicit_specialization_inconsistent_storage_class)
9997             << SC
9998             << FixItHint::CreateRemoval(
9999                                       D.getDeclSpec().getStorageClassSpecLoc());
10000 
10001         else
10002           Diag(NewFD->getLocation(),
10003                diag::ext_explicit_specialization_storage_class)
10004             << FixItHint::CreateRemoval(
10005                                       D.getDeclSpec().getStorageClassSpecLoc());
10006       }
10007     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10008       if (CheckMemberSpecialization(NewFD, Previous))
10009           NewFD->setInvalidDecl();
10010     }
10011 
10012     // Perform semantic checking on the function declaration.
10013     if (!isDependentClassScopeExplicitSpecialization) {
10014       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10015         CheckMain(NewFD, D.getDeclSpec());
10016 
10017       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10018         CheckMSVCRTEntryPoint(NewFD);
10019 
10020       if (!NewFD->isInvalidDecl())
10021         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10022                                                     isMemberSpecialization,
10023                                                     D.isFunctionDefinition()));
10024       else if (!Previous.empty())
10025         // Recover gracefully from an invalid redeclaration.
10026         D.setRedeclaration(true);
10027     }
10028 
10029     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10030             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10031            "previous declaration set still overloaded");
10032 
10033     NamedDecl *PrincipalDecl = (FunctionTemplate
10034                                 ? cast<NamedDecl>(FunctionTemplate)
10035                                 : NewFD);
10036 
10037     if (isFriend && NewFD->getPreviousDecl()) {
10038       AccessSpecifier Access = AS_public;
10039       if (!NewFD->isInvalidDecl())
10040         Access = NewFD->getPreviousDecl()->getAccess();
10041 
10042       NewFD->setAccess(Access);
10043       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10044     }
10045 
10046     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10047         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10048       PrincipalDecl->setNonMemberOperator();
10049 
10050     // If we have a function template, check the template parameter
10051     // list. This will check and merge default template arguments.
10052     if (FunctionTemplate) {
10053       FunctionTemplateDecl *PrevTemplate =
10054                                      FunctionTemplate->getPreviousDecl();
10055       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10056                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10057                                     : nullptr,
10058                             D.getDeclSpec().isFriendSpecified()
10059                               ? (D.isFunctionDefinition()
10060                                    ? TPC_FriendFunctionTemplateDefinition
10061                                    : TPC_FriendFunctionTemplate)
10062                               : (D.getCXXScopeSpec().isSet() &&
10063                                  DC && DC->isRecord() &&
10064                                  DC->isDependentContext())
10065                                   ? TPC_ClassTemplateMember
10066                                   : TPC_FunctionTemplate);
10067     }
10068 
10069     if (NewFD->isInvalidDecl()) {
10070       // Ignore all the rest of this.
10071     } else if (!D.isRedeclaration()) {
10072       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10073                                        AddToScope };
10074       // Fake up an access specifier if it's supposed to be a class member.
10075       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10076         NewFD->setAccess(AS_public);
10077 
10078       // Qualified decls generally require a previous declaration.
10079       if (D.getCXXScopeSpec().isSet()) {
10080         // ...with the major exception of templated-scope or
10081         // dependent-scope friend declarations.
10082 
10083         // TODO: we currently also suppress this check in dependent
10084         // contexts because (1) the parameter depth will be off when
10085         // matching friend templates and (2) we might actually be
10086         // selecting a friend based on a dependent factor.  But there
10087         // are situations where these conditions don't apply and we
10088         // can actually do this check immediately.
10089         //
10090         // Unless the scope is dependent, it's always an error if qualified
10091         // redeclaration lookup found nothing at all. Diagnose that now;
10092         // nothing will diagnose that error later.
10093         if (isFriend &&
10094             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10095              (!Previous.empty() && CurContext->isDependentContext()))) {
10096           // ignore these
10097         } else if (NewFD->isCPUDispatchMultiVersion() ||
10098                    NewFD->isCPUSpecificMultiVersion()) {
10099           // ignore this, we allow the redeclaration behavior here to create new
10100           // versions of the function.
10101         } else {
10102           // The user tried to provide an out-of-line definition for a
10103           // function that is a member of a class or namespace, but there
10104           // was no such member function declared (C++ [class.mfct]p2,
10105           // C++ [namespace.memdef]p2). For example:
10106           //
10107           // class X {
10108           //   void f() const;
10109           // };
10110           //
10111           // void X::f() { } // ill-formed
10112           //
10113           // Complain about this problem, and attempt to suggest close
10114           // matches (e.g., those that differ only in cv-qualifiers and
10115           // whether the parameter types are references).
10116 
10117           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10118                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10119             AddToScope = ExtraArgs.AddToScope;
10120             return Result;
10121           }
10122         }
10123 
10124         // Unqualified local friend declarations are required to resolve
10125         // to something.
10126       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10127         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10128                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10129           AddToScope = ExtraArgs.AddToScope;
10130           return Result;
10131         }
10132       }
10133     } else if (!D.isFunctionDefinition() &&
10134                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10135                !isFriend && !isFunctionTemplateSpecialization &&
10136                !isMemberSpecialization) {
10137       // An out-of-line member function declaration must also be a
10138       // definition (C++ [class.mfct]p2).
10139       // Note that this is not the case for explicit specializations of
10140       // function templates or member functions of class templates, per
10141       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10142       // extension for compatibility with old SWIG code which likes to
10143       // generate them.
10144       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10145         << D.getCXXScopeSpec().getRange();
10146     }
10147   }
10148 
10149   // If this is the first declaration of a library builtin function, add
10150   // attributes as appropriate.
10151   if (!D.isRedeclaration()) {
10152     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10153       if (unsigned BuiltinID = II->getBuiltinID()) {
10154         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10155         if (!InStdNamespace &&
10156             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10157           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10158             // Validate the type matches unless this builtin is specified as
10159             // matching regardless of its declared type.
10160             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10161               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10162             } else {
10163               ASTContext::GetBuiltinTypeError Error;
10164               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10165               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10166 
10167               if (!Error && !BuiltinType.isNull() &&
10168                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10169                       NewFD->getType(), BuiltinType))
10170                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10171             }
10172           }
10173         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10174                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10175           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10176         }
10177       }
10178     }
10179   }
10180 
10181   ProcessPragmaWeak(S, NewFD);
10182   checkAttributesAfterMerging(*this, *NewFD);
10183 
10184   AddKnownFunctionAttributes(NewFD);
10185 
10186   if (NewFD->hasAttr<OverloadableAttr>() &&
10187       !NewFD->getType()->getAs<FunctionProtoType>()) {
10188     Diag(NewFD->getLocation(),
10189          diag::err_attribute_overloadable_no_prototype)
10190       << NewFD;
10191 
10192     // Turn this into a variadic function with no parameters.
10193     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10194     FunctionProtoType::ExtProtoInfo EPI(
10195         Context.getDefaultCallingConvention(true, false));
10196     EPI.Variadic = true;
10197     EPI.ExtInfo = FT->getExtInfo();
10198 
10199     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10200     NewFD->setType(R);
10201   }
10202 
10203   // If there's a #pragma GCC visibility in scope, and this isn't a class
10204   // member, set the visibility of this function.
10205   if (!DC->isRecord() && NewFD->isExternallyVisible())
10206     AddPushedVisibilityAttribute(NewFD);
10207 
10208   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10209   // marking the function.
10210   AddCFAuditedAttribute(NewFD);
10211 
10212   // If this is a function definition, check if we have to apply any
10213   // attributes (i.e. optnone and no_builtin) due to a pragma.
10214   if (D.isFunctionDefinition()) {
10215     AddRangeBasedOptnone(NewFD);
10216     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10217     AddSectionMSAllocText(NewFD);
10218     ModifyFnAttributesMSPragmaOptimize(NewFD);
10219   }
10220 
10221   // If this is the first declaration of an extern C variable, update
10222   // the map of such variables.
10223   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10224       isIncompleteDeclExternC(*this, NewFD))
10225     RegisterLocallyScopedExternCDecl(NewFD, S);
10226 
10227   // Set this FunctionDecl's range up to the right paren.
10228   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10229 
10230   if (D.isRedeclaration() && !Previous.empty()) {
10231     NamedDecl *Prev = Previous.getRepresentativeDecl();
10232     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10233                                    isMemberSpecialization ||
10234                                        isFunctionTemplateSpecialization,
10235                                    D.isFunctionDefinition());
10236   }
10237 
10238   if (getLangOpts().CUDA) {
10239     IdentifierInfo *II = NewFD->getIdentifier();
10240     if (II && II->isStr(getCudaConfigureFuncName()) &&
10241         !NewFD->isInvalidDecl() &&
10242         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10243       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10244         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10245             << getCudaConfigureFuncName();
10246       Context.setcudaConfigureCallDecl(NewFD);
10247     }
10248 
10249     // Variadic functions, other than a *declaration* of printf, are not allowed
10250     // in device-side CUDA code, unless someone passed
10251     // -fcuda-allow-variadic-functions.
10252     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10253         (NewFD->hasAttr<CUDADeviceAttr>() ||
10254          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10255         !(II && II->isStr("printf") && NewFD->isExternC() &&
10256           !D.isFunctionDefinition())) {
10257       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10258     }
10259   }
10260 
10261   MarkUnusedFileScopedDecl(NewFD);
10262 
10263 
10264 
10265   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10266     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10267     if (SC == SC_Static) {
10268       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10269       D.setInvalidType();
10270     }
10271 
10272     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10273     if (!NewFD->getReturnType()->isVoidType()) {
10274       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10275       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10276           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10277                                 : FixItHint());
10278       D.setInvalidType();
10279     }
10280 
10281     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10282     for (auto Param : NewFD->parameters())
10283       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10284 
10285     if (getLangOpts().OpenCLCPlusPlus) {
10286       if (DC->isRecord()) {
10287         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10288         D.setInvalidType();
10289       }
10290       if (FunctionTemplate) {
10291         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10292         D.setInvalidType();
10293       }
10294     }
10295   }
10296 
10297   if (getLangOpts().CPlusPlus) {
10298     if (FunctionTemplate) {
10299       if (NewFD->isInvalidDecl())
10300         FunctionTemplate->setInvalidDecl();
10301       return FunctionTemplate;
10302     }
10303 
10304     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10305       CompleteMemberSpecialization(NewFD, Previous);
10306   }
10307 
10308   for (const ParmVarDecl *Param : NewFD->parameters()) {
10309     QualType PT = Param->getType();
10310 
10311     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10312     // types.
10313     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10314       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10315         QualType ElemTy = PipeTy->getElementType();
10316           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10317             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10318             D.setInvalidType();
10319           }
10320       }
10321     }
10322   }
10323 
10324   // Here we have an function template explicit specialization at class scope.
10325   // The actual specialization will be postponed to template instatiation
10326   // time via the ClassScopeFunctionSpecializationDecl node.
10327   if (isDependentClassScopeExplicitSpecialization) {
10328     ClassScopeFunctionSpecializationDecl *NewSpec =
10329                          ClassScopeFunctionSpecializationDecl::Create(
10330                                 Context, CurContext, NewFD->getLocation(),
10331                                 cast<CXXMethodDecl>(NewFD),
10332                                 HasExplicitTemplateArgs, TemplateArgs);
10333     CurContext->addDecl(NewSpec);
10334     AddToScope = false;
10335   }
10336 
10337   // Diagnose availability attributes. Availability cannot be used on functions
10338   // that are run during load/unload.
10339   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10340     if (NewFD->hasAttr<ConstructorAttr>()) {
10341       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10342           << 1;
10343       NewFD->dropAttr<AvailabilityAttr>();
10344     }
10345     if (NewFD->hasAttr<DestructorAttr>()) {
10346       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10347           << 2;
10348       NewFD->dropAttr<AvailabilityAttr>();
10349     }
10350   }
10351 
10352   // Diagnose no_builtin attribute on function declaration that are not a
10353   // definition.
10354   // FIXME: We should really be doing this in
10355   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10356   // the FunctionDecl and at this point of the code
10357   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10358   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10359   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10360     switch (D.getFunctionDefinitionKind()) {
10361     case FunctionDefinitionKind::Defaulted:
10362     case FunctionDefinitionKind::Deleted:
10363       Diag(NBA->getLocation(),
10364            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10365           << NBA->getSpelling();
10366       break;
10367     case FunctionDefinitionKind::Declaration:
10368       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10369           << NBA->getSpelling();
10370       break;
10371     case FunctionDefinitionKind::Definition:
10372       break;
10373     }
10374 
10375   return NewFD;
10376 }
10377 
10378 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10379 /// when __declspec(code_seg) "is applied to a class, all member functions of
10380 /// the class and nested classes -- this includes compiler-generated special
10381 /// member functions -- are put in the specified segment."
10382 /// The actual behavior is a little more complicated. The Microsoft compiler
10383 /// won't check outer classes if there is an active value from #pragma code_seg.
10384 /// The CodeSeg is always applied from the direct parent but only from outer
10385 /// classes when the #pragma code_seg stack is empty. See:
10386 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10387 /// available since MS has removed the page.
10388 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10389   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10390   if (!Method)
10391     return nullptr;
10392   const CXXRecordDecl *Parent = Method->getParent();
10393   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10394     Attr *NewAttr = SAttr->clone(S.getASTContext());
10395     NewAttr->setImplicit(true);
10396     return NewAttr;
10397   }
10398 
10399   // The Microsoft compiler won't check outer classes for the CodeSeg
10400   // when the #pragma code_seg stack is active.
10401   if (S.CodeSegStack.CurrentValue)
10402    return nullptr;
10403 
10404   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10405     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10406       Attr *NewAttr = SAttr->clone(S.getASTContext());
10407       NewAttr->setImplicit(true);
10408       return NewAttr;
10409     }
10410   }
10411   return nullptr;
10412 }
10413 
10414 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10415 /// containing class. Otherwise it will return implicit SectionAttr if the
10416 /// function is a definition and there is an active value on CodeSegStack
10417 /// (from the current #pragma code-seg value).
10418 ///
10419 /// \param FD Function being declared.
10420 /// \param IsDefinition Whether it is a definition or just a declarartion.
10421 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10422 ///          nullptr if no attribute should be added.
10423 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10424                                                        bool IsDefinition) {
10425   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10426     return A;
10427   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10428       CodeSegStack.CurrentValue)
10429     return SectionAttr::CreateImplicit(
10430         getASTContext(), CodeSegStack.CurrentValue->getString(),
10431         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10432         SectionAttr::Declspec_allocate);
10433   return nullptr;
10434 }
10435 
10436 /// Determines if we can perform a correct type check for \p D as a
10437 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10438 /// best-effort check.
10439 ///
10440 /// \param NewD The new declaration.
10441 /// \param OldD The old declaration.
10442 /// \param NewT The portion of the type of the new declaration to check.
10443 /// \param OldT The portion of the type of the old declaration to check.
10444 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10445                                           QualType NewT, QualType OldT) {
10446   if (!NewD->getLexicalDeclContext()->isDependentContext())
10447     return true;
10448 
10449   // For dependently-typed local extern declarations and friends, we can't
10450   // perform a correct type check in general until instantiation:
10451   //
10452   //   int f();
10453   //   template<typename T> void g() { T f(); }
10454   //
10455   // (valid if g() is only instantiated with T = int).
10456   if (NewT->isDependentType() &&
10457       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10458     return false;
10459 
10460   // Similarly, if the previous declaration was a dependent local extern
10461   // declaration, we don't really know its type yet.
10462   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10463     return false;
10464 
10465   return true;
10466 }
10467 
10468 /// Checks if the new declaration declared in dependent context must be
10469 /// put in the same redeclaration chain as the specified declaration.
10470 ///
10471 /// \param D Declaration that is checked.
10472 /// \param PrevDecl Previous declaration found with proper lookup method for the
10473 ///                 same declaration name.
10474 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10475 ///          belongs to.
10476 ///
10477 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10478   if (!D->getLexicalDeclContext()->isDependentContext())
10479     return true;
10480 
10481   // Don't chain dependent friend function definitions until instantiation, to
10482   // permit cases like
10483   //
10484   //   void func();
10485   //   template<typename T> class C1 { friend void func() {} };
10486   //   template<typename T> class C2 { friend void func() {} };
10487   //
10488   // ... which is valid if only one of C1 and C2 is ever instantiated.
10489   //
10490   // FIXME: This need only apply to function definitions. For now, we proxy
10491   // this by checking for a file-scope function. We do not want this to apply
10492   // to friend declarations nominating member functions, because that gets in
10493   // the way of access checks.
10494   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10495     return false;
10496 
10497   auto *VD = dyn_cast<ValueDecl>(D);
10498   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10499   return !VD || !PrevVD ||
10500          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10501                                         PrevVD->getType());
10502 }
10503 
10504 /// Check the target attribute of the function for MultiVersion
10505 /// validity.
10506 ///
10507 /// Returns true if there was an error, false otherwise.
10508 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10509   const auto *TA = FD->getAttr<TargetAttr>();
10510   assert(TA && "MultiVersion Candidate requires a target attribute");
10511   ParsedTargetAttr ParseInfo = TA->parse();
10512   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10513   enum ErrType { Feature = 0, Architecture = 1 };
10514 
10515   if (!ParseInfo.Architecture.empty() &&
10516       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10517     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10518         << Architecture << ParseInfo.Architecture;
10519     return true;
10520   }
10521 
10522   for (const auto &Feat : ParseInfo.Features) {
10523     auto BareFeat = StringRef{Feat}.substr(1);
10524     if (Feat[0] == '-') {
10525       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10526           << Feature << ("no-" + BareFeat).str();
10527       return true;
10528     }
10529 
10530     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10531         !TargetInfo.isValidFeatureName(BareFeat)) {
10532       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10533           << Feature << BareFeat;
10534       return true;
10535     }
10536   }
10537   return false;
10538 }
10539 
10540 // Provide a white-list of attributes that are allowed to be combined with
10541 // multiversion functions.
10542 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10543                                            MultiVersionKind MVKind) {
10544   // Note: this list/diagnosis must match the list in
10545   // checkMultiversionAttributesAllSame.
10546   switch (Kind) {
10547   default:
10548     return false;
10549   case attr::Used:
10550     return MVKind == MultiVersionKind::Target;
10551   case attr::NonNull:
10552   case attr::NoThrow:
10553     return true;
10554   }
10555 }
10556 
10557 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10558                                                  const FunctionDecl *FD,
10559                                                  const FunctionDecl *CausedFD,
10560                                                  MultiVersionKind MVKind) {
10561   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10562     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10563         << static_cast<unsigned>(MVKind) << A;
10564     if (CausedFD)
10565       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10566     return true;
10567   };
10568 
10569   for (const Attr *A : FD->attrs()) {
10570     switch (A->getKind()) {
10571     case attr::CPUDispatch:
10572     case attr::CPUSpecific:
10573       if (MVKind != MultiVersionKind::CPUDispatch &&
10574           MVKind != MultiVersionKind::CPUSpecific)
10575         return Diagnose(S, A);
10576       break;
10577     case attr::Target:
10578       if (MVKind != MultiVersionKind::Target)
10579         return Diagnose(S, A);
10580       break;
10581     case attr::TargetClones:
10582       if (MVKind != MultiVersionKind::TargetClones)
10583         return Diagnose(S, A);
10584       break;
10585     default:
10586       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10587         return Diagnose(S, A);
10588       break;
10589     }
10590   }
10591   return false;
10592 }
10593 
10594 bool Sema::areMultiversionVariantFunctionsCompatible(
10595     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10596     const PartialDiagnostic &NoProtoDiagID,
10597     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10598     const PartialDiagnosticAt &NoSupportDiagIDAt,
10599     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10600     bool ConstexprSupported, bool CLinkageMayDiffer) {
10601   enum DoesntSupport {
10602     FuncTemplates = 0,
10603     VirtFuncs = 1,
10604     DeducedReturn = 2,
10605     Constructors = 3,
10606     Destructors = 4,
10607     DeletedFuncs = 5,
10608     DefaultedFuncs = 6,
10609     ConstexprFuncs = 7,
10610     ConstevalFuncs = 8,
10611     Lambda = 9,
10612   };
10613   enum Different {
10614     CallingConv = 0,
10615     ReturnType = 1,
10616     ConstexprSpec = 2,
10617     InlineSpec = 3,
10618     Linkage = 4,
10619     LanguageLinkage = 5,
10620   };
10621 
10622   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10623       !OldFD->getType()->getAs<FunctionProtoType>()) {
10624     Diag(OldFD->getLocation(), NoProtoDiagID);
10625     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10626     return true;
10627   }
10628 
10629   if (NoProtoDiagID.getDiagID() != 0 &&
10630       !NewFD->getType()->getAs<FunctionProtoType>())
10631     return Diag(NewFD->getLocation(), NoProtoDiagID);
10632 
10633   if (!TemplatesSupported &&
10634       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10635     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10636            << FuncTemplates;
10637 
10638   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10639     if (NewCXXFD->isVirtual())
10640       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10641              << VirtFuncs;
10642 
10643     if (isa<CXXConstructorDecl>(NewCXXFD))
10644       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10645              << Constructors;
10646 
10647     if (isa<CXXDestructorDecl>(NewCXXFD))
10648       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10649              << Destructors;
10650   }
10651 
10652   if (NewFD->isDeleted())
10653     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10654            << DeletedFuncs;
10655 
10656   if (NewFD->isDefaulted())
10657     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10658            << DefaultedFuncs;
10659 
10660   if (!ConstexprSupported && NewFD->isConstexpr())
10661     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10662            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10663 
10664   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10665   const auto *NewType = cast<FunctionType>(NewQType);
10666   QualType NewReturnType = NewType->getReturnType();
10667 
10668   if (NewReturnType->isUndeducedType())
10669     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10670            << DeducedReturn;
10671 
10672   // Ensure the return type is identical.
10673   if (OldFD) {
10674     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10675     const auto *OldType = cast<FunctionType>(OldQType);
10676     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10677     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10678 
10679     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10680       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10681 
10682     QualType OldReturnType = OldType->getReturnType();
10683 
10684     if (OldReturnType != NewReturnType)
10685       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10686 
10687     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10688       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10689 
10690     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10691       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10692 
10693     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10694       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10695 
10696     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10697       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10698 
10699     if (CheckEquivalentExceptionSpec(
10700             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10701             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10702       return true;
10703   }
10704   return false;
10705 }
10706 
10707 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10708                                              const FunctionDecl *NewFD,
10709                                              bool CausesMV,
10710                                              MultiVersionKind MVKind) {
10711   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10712     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10713     if (OldFD)
10714       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10715     return true;
10716   }
10717 
10718   bool IsCPUSpecificCPUDispatchMVKind =
10719       MVKind == MultiVersionKind::CPUDispatch ||
10720       MVKind == MultiVersionKind::CPUSpecific;
10721 
10722   if (CausesMV && OldFD &&
10723       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10724     return true;
10725 
10726   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10727     return true;
10728 
10729   // Only allow transition to MultiVersion if it hasn't been used.
10730   if (OldFD && CausesMV && OldFD->isUsed(false))
10731     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10732 
10733   return S.areMultiversionVariantFunctionsCompatible(
10734       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10735       PartialDiagnosticAt(NewFD->getLocation(),
10736                           S.PDiag(diag::note_multiversioning_caused_here)),
10737       PartialDiagnosticAt(NewFD->getLocation(),
10738                           S.PDiag(diag::err_multiversion_doesnt_support)
10739                               << static_cast<unsigned>(MVKind)),
10740       PartialDiagnosticAt(NewFD->getLocation(),
10741                           S.PDiag(diag::err_multiversion_diff)),
10742       /*TemplatesSupported=*/false,
10743       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10744       /*CLinkageMayDiffer=*/false);
10745 }
10746 
10747 /// Check the validity of a multiversion function declaration that is the
10748 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10749 ///
10750 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10751 ///
10752 /// Returns true if there was an error, false otherwise.
10753 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10754                                            MultiVersionKind MVKind,
10755                                            const TargetAttr *TA) {
10756   assert(MVKind != MultiVersionKind::None &&
10757          "Function lacks multiversion attribute");
10758 
10759   // Target only causes MV if it is default, otherwise this is a normal
10760   // function.
10761   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10762     return false;
10763 
10764   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10765     FD->setInvalidDecl();
10766     return true;
10767   }
10768 
10769   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10770     FD->setInvalidDecl();
10771     return true;
10772   }
10773 
10774   FD->setIsMultiVersion();
10775   return false;
10776 }
10777 
10778 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10779   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10780     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10781       return true;
10782   }
10783 
10784   return false;
10785 }
10786 
10787 static bool CheckTargetCausesMultiVersioning(
10788     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10789     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10790   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10791   ParsedTargetAttr NewParsed = NewTA->parse();
10792   // Sort order doesn't matter, it just needs to be consistent.
10793   llvm::sort(NewParsed.Features);
10794 
10795   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10796   // to change, this is a simple redeclaration.
10797   if (!NewTA->isDefaultVersion() &&
10798       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10799     return false;
10800 
10801   // Otherwise, this decl causes MultiVersioning.
10802   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10803                                        MultiVersionKind::Target)) {
10804     NewFD->setInvalidDecl();
10805     return true;
10806   }
10807 
10808   if (CheckMultiVersionValue(S, NewFD)) {
10809     NewFD->setInvalidDecl();
10810     return true;
10811   }
10812 
10813   // If this is 'default', permit the forward declaration.
10814   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10815     Redeclaration = true;
10816     OldDecl = OldFD;
10817     OldFD->setIsMultiVersion();
10818     NewFD->setIsMultiVersion();
10819     return false;
10820   }
10821 
10822   if (CheckMultiVersionValue(S, OldFD)) {
10823     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10824     NewFD->setInvalidDecl();
10825     return true;
10826   }
10827 
10828   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10829 
10830   if (OldParsed == NewParsed) {
10831     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10832     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10833     NewFD->setInvalidDecl();
10834     return true;
10835   }
10836 
10837   for (const auto *FD : OldFD->redecls()) {
10838     const auto *CurTA = FD->getAttr<TargetAttr>();
10839     // We allow forward declarations before ANY multiversioning attributes, but
10840     // nothing after the fact.
10841     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10842         (!CurTA || CurTA->isInherited())) {
10843       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10844           << 0;
10845       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10846       NewFD->setInvalidDecl();
10847       return true;
10848     }
10849   }
10850 
10851   OldFD->setIsMultiVersion();
10852   NewFD->setIsMultiVersion();
10853   Redeclaration = false;
10854   OldDecl = nullptr;
10855   Previous.clear();
10856   return false;
10857 }
10858 
10859 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10860                                         MultiVersionKind New) {
10861   if (Old == New || Old == MultiVersionKind::None ||
10862       New == MultiVersionKind::None)
10863     return true;
10864 
10865   return (Old == MultiVersionKind::CPUDispatch &&
10866           New == MultiVersionKind::CPUSpecific) ||
10867          (Old == MultiVersionKind::CPUSpecific &&
10868           New == MultiVersionKind::CPUDispatch);
10869 }
10870 
10871 /// Check the validity of a new function declaration being added to an existing
10872 /// multiversioned declaration collection.
10873 static bool CheckMultiVersionAdditionalDecl(
10874     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10875     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10876     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10877     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10878     LookupResult &Previous) {
10879 
10880   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10881   // Disallow mixing of multiversioning types.
10882   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10883     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10884     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10885     NewFD->setInvalidDecl();
10886     return true;
10887   }
10888 
10889   ParsedTargetAttr NewParsed;
10890   if (NewTA) {
10891     NewParsed = NewTA->parse();
10892     llvm::sort(NewParsed.Features);
10893   }
10894 
10895   bool UseMemberUsingDeclRules =
10896       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10897 
10898   bool MayNeedOverloadableChecks =
10899       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10900 
10901   // Next, check ALL non-overloads to see if this is a redeclaration of a
10902   // previous member of the MultiVersion set.
10903   for (NamedDecl *ND : Previous) {
10904     FunctionDecl *CurFD = ND->getAsFunction();
10905     if (!CurFD)
10906       continue;
10907     if (MayNeedOverloadableChecks &&
10908         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10909       continue;
10910 
10911     switch (NewMVKind) {
10912     case MultiVersionKind::None:
10913       assert(OldMVKind == MultiVersionKind::TargetClones &&
10914              "Only target_clones can be omitted in subsequent declarations");
10915       break;
10916     case MultiVersionKind::Target: {
10917       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10918       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10919         NewFD->setIsMultiVersion();
10920         Redeclaration = true;
10921         OldDecl = ND;
10922         return false;
10923       }
10924 
10925       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10926       if (CurParsed == NewParsed) {
10927         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10928         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10929         NewFD->setInvalidDecl();
10930         return true;
10931       }
10932       break;
10933     }
10934     case MultiVersionKind::TargetClones: {
10935       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10936       Redeclaration = true;
10937       OldDecl = CurFD;
10938       NewFD->setIsMultiVersion();
10939 
10940       if (CurClones && NewClones &&
10941           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10942            !std::equal(CurClones->featuresStrs_begin(),
10943                        CurClones->featuresStrs_end(),
10944                        NewClones->featuresStrs_begin()))) {
10945         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10946         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10947         NewFD->setInvalidDecl();
10948         return true;
10949       }
10950 
10951       return false;
10952     }
10953     case MultiVersionKind::CPUSpecific:
10954     case MultiVersionKind::CPUDispatch: {
10955       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10956       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10957       // Handle CPUDispatch/CPUSpecific versions.
10958       // Only 1 CPUDispatch function is allowed, this will make it go through
10959       // the redeclaration errors.
10960       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10961           CurFD->hasAttr<CPUDispatchAttr>()) {
10962         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10963             std::equal(
10964                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10965                 NewCPUDisp->cpus_begin(),
10966                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10967                   return Cur->getName() == New->getName();
10968                 })) {
10969           NewFD->setIsMultiVersion();
10970           Redeclaration = true;
10971           OldDecl = ND;
10972           return false;
10973         }
10974 
10975         // If the declarations don't match, this is an error condition.
10976         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10977         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10978         NewFD->setInvalidDecl();
10979         return true;
10980       }
10981       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10982         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10983             std::equal(
10984                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10985                 NewCPUSpec->cpus_begin(),
10986                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10987                   return Cur->getName() == New->getName();
10988                 })) {
10989           NewFD->setIsMultiVersion();
10990           Redeclaration = true;
10991           OldDecl = ND;
10992           return false;
10993         }
10994 
10995         // Only 1 version of CPUSpecific is allowed for each CPU.
10996         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10997           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10998             if (CurII == NewII) {
10999               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11000                   << NewII;
11001               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11002               NewFD->setInvalidDecl();
11003               return true;
11004             }
11005           }
11006         }
11007       }
11008       break;
11009     }
11010     }
11011   }
11012 
11013   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11014   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11015   // handled in the attribute adding step.
11016   if (NewMVKind == MultiVersionKind::Target &&
11017       CheckMultiVersionValue(S, NewFD)) {
11018     NewFD->setInvalidDecl();
11019     return true;
11020   }
11021 
11022   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11023                                        !OldFD->isMultiVersion(), NewMVKind)) {
11024     NewFD->setInvalidDecl();
11025     return true;
11026   }
11027 
11028   // Permit forward declarations in the case where these two are compatible.
11029   if (!OldFD->isMultiVersion()) {
11030     OldFD->setIsMultiVersion();
11031     NewFD->setIsMultiVersion();
11032     Redeclaration = true;
11033     OldDecl = OldFD;
11034     return false;
11035   }
11036 
11037   NewFD->setIsMultiVersion();
11038   Redeclaration = false;
11039   OldDecl = nullptr;
11040   Previous.clear();
11041   return false;
11042 }
11043 
11044 /// Check the validity of a mulitversion function declaration.
11045 /// Also sets the multiversion'ness' of the function itself.
11046 ///
11047 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11048 ///
11049 /// Returns true if there was an error, false otherwise.
11050 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11051                                       bool &Redeclaration, NamedDecl *&OldDecl,
11052                                       LookupResult &Previous) {
11053   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11054   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11055   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11056   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11057   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11058 
11059   // Main isn't allowed to become a multiversion function, however it IS
11060   // permitted to have 'main' be marked with the 'target' optimization hint.
11061   if (NewFD->isMain()) {
11062     if (MVKind != MultiVersionKind::None &&
11063         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11064       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11065       NewFD->setInvalidDecl();
11066       return true;
11067     }
11068     return false;
11069   }
11070 
11071   if (!OldDecl || !OldDecl->getAsFunction() ||
11072       OldDecl->getDeclContext()->getRedeclContext() !=
11073           NewFD->getDeclContext()->getRedeclContext()) {
11074     // If there's no previous declaration, AND this isn't attempting to cause
11075     // multiversioning, this isn't an error condition.
11076     if (MVKind == MultiVersionKind::None)
11077       return false;
11078     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11079   }
11080 
11081   FunctionDecl *OldFD = OldDecl->getAsFunction();
11082 
11083   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11084     return false;
11085 
11086   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11087   // for target_clones.
11088   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11089       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11090     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11091         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11092     NewFD->setInvalidDecl();
11093     return true;
11094   }
11095 
11096   if (!OldFD->isMultiVersion()) {
11097     switch (MVKind) {
11098     case MultiVersionKind::Target:
11099       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11100                                               Redeclaration, OldDecl, Previous);
11101     case MultiVersionKind::TargetClones:
11102       if (OldFD->isUsed(false)) {
11103         NewFD->setInvalidDecl();
11104         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11105       }
11106       OldFD->setIsMultiVersion();
11107       break;
11108     case MultiVersionKind::CPUDispatch:
11109     case MultiVersionKind::CPUSpecific:
11110     case MultiVersionKind::None:
11111       break;
11112     }
11113   }
11114 
11115   // At this point, we have a multiversion function decl (in OldFD) AND an
11116   // appropriate attribute in the current function decl.  Resolve that these are
11117   // still compatible with previous declarations.
11118   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11119                                          NewCPUDisp, NewCPUSpec, NewClones,
11120                                          Redeclaration, OldDecl, Previous);
11121 }
11122 
11123 /// Perform semantic checking of a new function declaration.
11124 ///
11125 /// Performs semantic analysis of the new function declaration
11126 /// NewFD. This routine performs all semantic checking that does not
11127 /// require the actual declarator involved in the declaration, and is
11128 /// used both for the declaration of functions as they are parsed
11129 /// (called via ActOnDeclarator) and for the declaration of functions
11130 /// that have been instantiated via C++ template instantiation (called
11131 /// via InstantiateDecl).
11132 ///
11133 /// \param IsMemberSpecialization whether this new function declaration is
11134 /// a member specialization (that replaces any definition provided by the
11135 /// previous declaration).
11136 ///
11137 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11138 ///
11139 /// \returns true if the function declaration is a redeclaration.
11140 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11141                                     LookupResult &Previous,
11142                                     bool IsMemberSpecialization,
11143                                     bool DeclIsDefn) {
11144   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11145          "Variably modified return types are not handled here");
11146 
11147   // Determine whether the type of this function should be merged with
11148   // a previous visible declaration. This never happens for functions in C++,
11149   // and always happens in C if the previous declaration was visible.
11150   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11151                                !Previous.isShadowed();
11152 
11153   bool Redeclaration = false;
11154   NamedDecl *OldDecl = nullptr;
11155   bool MayNeedOverloadableChecks = false;
11156 
11157   // Merge or overload the declaration with an existing declaration of
11158   // the same name, if appropriate.
11159   if (!Previous.empty()) {
11160     // Determine whether NewFD is an overload of PrevDecl or
11161     // a declaration that requires merging. If it's an overload,
11162     // there's no more work to do here; we'll just add the new
11163     // function to the scope.
11164     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11165       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11166       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11167         Redeclaration = true;
11168         OldDecl = Candidate;
11169       }
11170     } else {
11171       MayNeedOverloadableChecks = true;
11172       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11173                             /*NewIsUsingDecl*/ false)) {
11174       case Ovl_Match:
11175         Redeclaration = true;
11176         break;
11177 
11178       case Ovl_NonFunction:
11179         Redeclaration = true;
11180         break;
11181 
11182       case Ovl_Overload:
11183         Redeclaration = false;
11184         break;
11185       }
11186     }
11187   }
11188 
11189   // Check for a previous extern "C" declaration with this name.
11190   if (!Redeclaration &&
11191       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11192     if (!Previous.empty()) {
11193       // This is an extern "C" declaration with the same name as a previous
11194       // declaration, and thus redeclares that entity...
11195       Redeclaration = true;
11196       OldDecl = Previous.getFoundDecl();
11197       MergeTypeWithPrevious = false;
11198 
11199       // ... except in the presence of __attribute__((overloadable)).
11200       if (OldDecl->hasAttr<OverloadableAttr>() ||
11201           NewFD->hasAttr<OverloadableAttr>()) {
11202         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11203           MayNeedOverloadableChecks = true;
11204           Redeclaration = false;
11205           OldDecl = nullptr;
11206         }
11207       }
11208     }
11209   }
11210 
11211   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11212     return Redeclaration;
11213 
11214   // PPC MMA non-pointer types are not allowed as function return types.
11215   if (Context.getTargetInfo().getTriple().isPPC64() &&
11216       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11217     NewFD->setInvalidDecl();
11218   }
11219 
11220   // C++11 [dcl.constexpr]p8:
11221   //   A constexpr specifier for a non-static member function that is not
11222   //   a constructor declares that member function to be const.
11223   //
11224   // This needs to be delayed until we know whether this is an out-of-line
11225   // definition of a static member function.
11226   //
11227   // This rule is not present in C++1y, so we produce a backwards
11228   // compatibility warning whenever it happens in C++11.
11229   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11230   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11231       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11232       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11233     CXXMethodDecl *OldMD = nullptr;
11234     if (OldDecl)
11235       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11236     if (!OldMD || !OldMD->isStatic()) {
11237       const FunctionProtoType *FPT =
11238         MD->getType()->castAs<FunctionProtoType>();
11239       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11240       EPI.TypeQuals.addConst();
11241       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11242                                           FPT->getParamTypes(), EPI));
11243 
11244       // Warn that we did this, if we're not performing template instantiation.
11245       // In that case, we'll have warned already when the template was defined.
11246       if (!inTemplateInstantiation()) {
11247         SourceLocation AddConstLoc;
11248         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11249                 .IgnoreParens().getAs<FunctionTypeLoc>())
11250           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11251 
11252         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11253           << FixItHint::CreateInsertion(AddConstLoc, " const");
11254       }
11255     }
11256   }
11257 
11258   if (Redeclaration) {
11259     // NewFD and OldDecl represent declarations that need to be
11260     // merged.
11261     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11262                           DeclIsDefn)) {
11263       NewFD->setInvalidDecl();
11264       return Redeclaration;
11265     }
11266 
11267     Previous.clear();
11268     Previous.addDecl(OldDecl);
11269 
11270     if (FunctionTemplateDecl *OldTemplateDecl =
11271             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11272       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11273       FunctionTemplateDecl *NewTemplateDecl
11274         = NewFD->getDescribedFunctionTemplate();
11275       assert(NewTemplateDecl && "Template/non-template mismatch");
11276 
11277       // The call to MergeFunctionDecl above may have created some state in
11278       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11279       // can add it as a redeclaration.
11280       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11281 
11282       NewFD->setPreviousDeclaration(OldFD);
11283       if (NewFD->isCXXClassMember()) {
11284         NewFD->setAccess(OldTemplateDecl->getAccess());
11285         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11286       }
11287 
11288       // If this is an explicit specialization of a member that is a function
11289       // template, mark it as a member specialization.
11290       if (IsMemberSpecialization &&
11291           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11292         NewTemplateDecl->setMemberSpecialization();
11293         assert(OldTemplateDecl->isMemberSpecialization());
11294         // Explicit specializations of a member template do not inherit deleted
11295         // status from the parent member template that they are specializing.
11296         if (OldFD->isDeleted()) {
11297           // FIXME: This assert will not hold in the presence of modules.
11298           assert(OldFD->getCanonicalDecl() == OldFD);
11299           // FIXME: We need an update record for this AST mutation.
11300           OldFD->setDeletedAsWritten(false);
11301         }
11302       }
11303 
11304     } else {
11305       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11306         auto *OldFD = cast<FunctionDecl>(OldDecl);
11307         // This needs to happen first so that 'inline' propagates.
11308         NewFD->setPreviousDeclaration(OldFD);
11309         if (NewFD->isCXXClassMember())
11310           NewFD->setAccess(OldFD->getAccess());
11311       }
11312     }
11313   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11314              !NewFD->getAttr<OverloadableAttr>()) {
11315     assert((Previous.empty() ||
11316             llvm::any_of(Previous,
11317                          [](const NamedDecl *ND) {
11318                            return ND->hasAttr<OverloadableAttr>();
11319                          })) &&
11320            "Non-redecls shouldn't happen without overloadable present");
11321 
11322     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11323       const auto *FD = dyn_cast<FunctionDecl>(ND);
11324       return FD && !FD->hasAttr<OverloadableAttr>();
11325     });
11326 
11327     if (OtherUnmarkedIter != Previous.end()) {
11328       Diag(NewFD->getLocation(),
11329            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11330       Diag((*OtherUnmarkedIter)->getLocation(),
11331            diag::note_attribute_overloadable_prev_overload)
11332           << false;
11333 
11334       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11335     }
11336   }
11337 
11338   if (LangOpts.OpenMP)
11339     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11340 
11341   // Semantic checking for this function declaration (in isolation).
11342 
11343   if (getLangOpts().CPlusPlus) {
11344     // C++-specific checks.
11345     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11346       CheckConstructor(Constructor);
11347     } else if (CXXDestructorDecl *Destructor =
11348                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11349       CXXRecordDecl *Record = Destructor->getParent();
11350       QualType ClassType = Context.getTypeDeclType(Record);
11351 
11352       // FIXME: Shouldn't we be able to perform this check even when the class
11353       // type is dependent? Both gcc and edg can handle that.
11354       if (!ClassType->isDependentType()) {
11355         DeclarationName Name
11356           = Context.DeclarationNames.getCXXDestructorName(
11357                                         Context.getCanonicalType(ClassType));
11358         if (NewFD->getDeclName() != Name) {
11359           Diag(NewFD->getLocation(), diag::err_destructor_name);
11360           NewFD->setInvalidDecl();
11361           return Redeclaration;
11362         }
11363       }
11364     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11365       if (auto *TD = Guide->getDescribedFunctionTemplate())
11366         CheckDeductionGuideTemplate(TD);
11367 
11368       // A deduction guide is not on the list of entities that can be
11369       // explicitly specialized.
11370       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11371         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11372             << /*explicit specialization*/ 1;
11373     }
11374 
11375     // Find any virtual functions that this function overrides.
11376     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11377       if (!Method->isFunctionTemplateSpecialization() &&
11378           !Method->getDescribedFunctionTemplate() &&
11379           Method->isCanonicalDecl()) {
11380         AddOverriddenMethods(Method->getParent(), Method);
11381       }
11382       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11383         // C++2a [class.virtual]p6
11384         // A virtual method shall not have a requires-clause.
11385         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11386              diag::err_constrained_virtual_method);
11387 
11388       if (Method->isStatic())
11389         checkThisInStaticMemberFunctionType(Method);
11390     }
11391 
11392     // C++20: dcl.decl.general p4:
11393     // The optional requires-clause ([temp.pre]) in an init-declarator or
11394     // member-declarator shall be present only if the declarator declares a
11395     // templated function ([dcl.fct]).
11396     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11397       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11398         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11399     }
11400 
11401     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11402       ActOnConversionDeclarator(Conversion);
11403 
11404     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11405     if (NewFD->isOverloadedOperator() &&
11406         CheckOverloadedOperatorDeclaration(NewFD)) {
11407       NewFD->setInvalidDecl();
11408       return Redeclaration;
11409     }
11410 
11411     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11412     if (NewFD->getLiteralIdentifier() &&
11413         CheckLiteralOperatorDeclaration(NewFD)) {
11414       NewFD->setInvalidDecl();
11415       return Redeclaration;
11416     }
11417 
11418     // In C++, check default arguments now that we have merged decls. Unless
11419     // the lexical context is the class, because in this case this is done
11420     // during delayed parsing anyway.
11421     if (!CurContext->isRecord())
11422       CheckCXXDefaultArguments(NewFD);
11423 
11424     // If this function is declared as being extern "C", then check to see if
11425     // the function returns a UDT (class, struct, or union type) that is not C
11426     // compatible, and if it does, warn the user.
11427     // But, issue any diagnostic on the first declaration only.
11428     if (Previous.empty() && NewFD->isExternC()) {
11429       QualType R = NewFD->getReturnType();
11430       if (R->isIncompleteType() && !R->isVoidType())
11431         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11432             << NewFD << R;
11433       else if (!R.isPODType(Context) && !R->isVoidType() &&
11434                !R->isObjCObjectPointerType())
11435         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11436     }
11437 
11438     // C++1z [dcl.fct]p6:
11439     //   [...] whether the function has a non-throwing exception-specification
11440     //   [is] part of the function type
11441     //
11442     // This results in an ABI break between C++14 and C++17 for functions whose
11443     // declared type includes an exception-specification in a parameter or
11444     // return type. (Exception specifications on the function itself are OK in
11445     // most cases, and exception specifications are not permitted in most other
11446     // contexts where they could make it into a mangling.)
11447     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11448       auto HasNoexcept = [&](QualType T) -> bool {
11449         // Strip off declarator chunks that could be between us and a function
11450         // type. We don't need to look far, exception specifications are very
11451         // restricted prior to C++17.
11452         if (auto *RT = T->getAs<ReferenceType>())
11453           T = RT->getPointeeType();
11454         else if (T->isAnyPointerType())
11455           T = T->getPointeeType();
11456         else if (auto *MPT = T->getAs<MemberPointerType>())
11457           T = MPT->getPointeeType();
11458         if (auto *FPT = T->getAs<FunctionProtoType>())
11459           if (FPT->isNothrow())
11460             return true;
11461         return false;
11462       };
11463 
11464       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11465       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11466       for (QualType T : FPT->param_types())
11467         AnyNoexcept |= HasNoexcept(T);
11468       if (AnyNoexcept)
11469         Diag(NewFD->getLocation(),
11470              diag::warn_cxx17_compat_exception_spec_in_signature)
11471             << NewFD;
11472     }
11473 
11474     if (!Redeclaration && LangOpts.CUDA)
11475       checkCUDATargetOverload(NewFD, Previous);
11476   }
11477   return Redeclaration;
11478 }
11479 
11480 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11481   // C++11 [basic.start.main]p3:
11482   //   A program that [...] declares main to be inline, static or
11483   //   constexpr is ill-formed.
11484   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11485   //   appear in a declaration of main.
11486   // static main is not an error under C99, but we should warn about it.
11487   // We accept _Noreturn main as an extension.
11488   if (FD->getStorageClass() == SC_Static)
11489     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11490          ? diag::err_static_main : diag::warn_static_main)
11491       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11492   if (FD->isInlineSpecified())
11493     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11494       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11495   if (DS.isNoreturnSpecified()) {
11496     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11497     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11498     Diag(NoreturnLoc, diag::ext_noreturn_main);
11499     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11500       << FixItHint::CreateRemoval(NoreturnRange);
11501   }
11502   if (FD->isConstexpr()) {
11503     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11504         << FD->isConsteval()
11505         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11506     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11507   }
11508 
11509   if (getLangOpts().OpenCL) {
11510     Diag(FD->getLocation(), diag::err_opencl_no_main)
11511         << FD->hasAttr<OpenCLKernelAttr>();
11512     FD->setInvalidDecl();
11513     return;
11514   }
11515 
11516   // Functions named main in hlsl are default entries, but don't have specific
11517   // signatures they are required to conform to.
11518   if (getLangOpts().HLSL)
11519     return;
11520 
11521   QualType T = FD->getType();
11522   assert(T->isFunctionType() && "function decl is not of function type");
11523   const FunctionType* FT = T->castAs<FunctionType>();
11524 
11525   // Set default calling convention for main()
11526   if (FT->getCallConv() != CC_C) {
11527     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11528     FD->setType(QualType(FT, 0));
11529     T = Context.getCanonicalType(FD->getType());
11530   }
11531 
11532   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11533     // In C with GNU extensions we allow main() to have non-integer return
11534     // type, but we should warn about the extension, and we disable the
11535     // implicit-return-zero rule.
11536 
11537     // GCC in C mode accepts qualified 'int'.
11538     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11539       FD->setHasImplicitReturnZero(true);
11540     else {
11541       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11542       SourceRange RTRange = FD->getReturnTypeSourceRange();
11543       if (RTRange.isValid())
11544         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11545             << FixItHint::CreateReplacement(RTRange, "int");
11546     }
11547   } else {
11548     // In C and C++, main magically returns 0 if you fall off the end;
11549     // set the flag which tells us that.
11550     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11551 
11552     // All the standards say that main() should return 'int'.
11553     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11554       FD->setHasImplicitReturnZero(true);
11555     else {
11556       // Otherwise, this is just a flat-out error.
11557       SourceRange RTRange = FD->getReturnTypeSourceRange();
11558       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11559           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11560                                 : FixItHint());
11561       FD->setInvalidDecl(true);
11562     }
11563   }
11564 
11565   // Treat protoless main() as nullary.
11566   if (isa<FunctionNoProtoType>(FT)) return;
11567 
11568   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11569   unsigned nparams = FTP->getNumParams();
11570   assert(FD->getNumParams() == nparams);
11571 
11572   bool HasExtraParameters = (nparams > 3);
11573 
11574   if (FTP->isVariadic()) {
11575     Diag(FD->getLocation(), diag::ext_variadic_main);
11576     // FIXME: if we had information about the location of the ellipsis, we
11577     // could add a FixIt hint to remove it as a parameter.
11578   }
11579 
11580   // Darwin passes an undocumented fourth argument of type char**.  If
11581   // other platforms start sprouting these, the logic below will start
11582   // getting shifty.
11583   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11584     HasExtraParameters = false;
11585 
11586   if (HasExtraParameters) {
11587     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11588     FD->setInvalidDecl(true);
11589     nparams = 3;
11590   }
11591 
11592   // FIXME: a lot of the following diagnostics would be improved
11593   // if we had some location information about types.
11594 
11595   QualType CharPP =
11596     Context.getPointerType(Context.getPointerType(Context.CharTy));
11597   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11598 
11599   for (unsigned i = 0; i < nparams; ++i) {
11600     QualType AT = FTP->getParamType(i);
11601 
11602     bool mismatch = true;
11603 
11604     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11605       mismatch = false;
11606     else if (Expected[i] == CharPP) {
11607       // As an extension, the following forms are okay:
11608       //   char const **
11609       //   char const * const *
11610       //   char * const *
11611 
11612       QualifierCollector qs;
11613       const PointerType* PT;
11614       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11615           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11616           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11617                               Context.CharTy)) {
11618         qs.removeConst();
11619         mismatch = !qs.empty();
11620       }
11621     }
11622 
11623     if (mismatch) {
11624       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11625       // TODO: suggest replacing given type with expected type
11626       FD->setInvalidDecl(true);
11627     }
11628   }
11629 
11630   if (nparams == 1 && !FD->isInvalidDecl()) {
11631     Diag(FD->getLocation(), diag::warn_main_one_arg);
11632   }
11633 
11634   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11635     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11636     FD->setInvalidDecl();
11637   }
11638 }
11639 
11640 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11641 
11642   // Default calling convention for main and wmain is __cdecl
11643   if (FD->getName() == "main" || FD->getName() == "wmain")
11644     return false;
11645 
11646   // Default calling convention for MinGW is __cdecl
11647   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11648   if (T.isWindowsGNUEnvironment())
11649     return false;
11650 
11651   // Default calling convention for WinMain, wWinMain and DllMain
11652   // is __stdcall on 32 bit Windows
11653   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11654     return true;
11655 
11656   return false;
11657 }
11658 
11659 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11660   QualType T = FD->getType();
11661   assert(T->isFunctionType() && "function decl is not of function type");
11662   const FunctionType *FT = T->castAs<FunctionType>();
11663 
11664   // Set an implicit return of 'zero' if the function can return some integral,
11665   // enumeration, pointer or nullptr type.
11666   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11667       FT->getReturnType()->isAnyPointerType() ||
11668       FT->getReturnType()->isNullPtrType())
11669     // DllMain is exempt because a return value of zero means it failed.
11670     if (FD->getName() != "DllMain")
11671       FD->setHasImplicitReturnZero(true);
11672 
11673   // Explicity specified calling conventions are applied to MSVC entry points
11674   if (!hasExplicitCallingConv(T)) {
11675     if (isDefaultStdCall(FD, *this)) {
11676       if (FT->getCallConv() != CC_X86StdCall) {
11677         FT = Context.adjustFunctionType(
11678             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11679         FD->setType(QualType(FT, 0));
11680       }
11681     } else if (FT->getCallConv() != CC_C) {
11682       FT = Context.adjustFunctionType(FT,
11683                                       FT->getExtInfo().withCallingConv(CC_C));
11684       FD->setType(QualType(FT, 0));
11685     }
11686   }
11687 
11688   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11689     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11690     FD->setInvalidDecl();
11691   }
11692 }
11693 
11694 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11695   // FIXME: Need strict checking.  In C89, we need to check for
11696   // any assignment, increment, decrement, function-calls, or
11697   // commas outside of a sizeof.  In C99, it's the same list,
11698   // except that the aforementioned are allowed in unevaluated
11699   // expressions.  Everything else falls under the
11700   // "may accept other forms of constant expressions" exception.
11701   //
11702   // Regular C++ code will not end up here (exceptions: language extensions,
11703   // OpenCL C++ etc), so the constant expression rules there don't matter.
11704   if (Init->isValueDependent()) {
11705     assert(Init->containsErrors() &&
11706            "Dependent code should only occur in error-recovery path.");
11707     return true;
11708   }
11709   const Expr *Culprit;
11710   if (Init->isConstantInitializer(Context, false, &Culprit))
11711     return false;
11712   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11713     << Culprit->getSourceRange();
11714   return true;
11715 }
11716 
11717 namespace {
11718   // Visits an initialization expression to see if OrigDecl is evaluated in
11719   // its own initialization and throws a warning if it does.
11720   class SelfReferenceChecker
11721       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11722     Sema &S;
11723     Decl *OrigDecl;
11724     bool isRecordType;
11725     bool isPODType;
11726     bool isReferenceType;
11727 
11728     bool isInitList;
11729     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11730 
11731   public:
11732     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11733 
11734     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11735                                                     S(S), OrigDecl(OrigDecl) {
11736       isPODType = false;
11737       isRecordType = false;
11738       isReferenceType = false;
11739       isInitList = false;
11740       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11741         isPODType = VD->getType().isPODType(S.Context);
11742         isRecordType = VD->getType()->isRecordType();
11743         isReferenceType = VD->getType()->isReferenceType();
11744       }
11745     }
11746 
11747     // For most expressions, just call the visitor.  For initializer lists,
11748     // track the index of the field being initialized since fields are
11749     // initialized in order allowing use of previously initialized fields.
11750     void CheckExpr(Expr *E) {
11751       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11752       if (!InitList) {
11753         Visit(E);
11754         return;
11755       }
11756 
11757       // Track and increment the index here.
11758       isInitList = true;
11759       InitFieldIndex.push_back(0);
11760       for (auto Child : InitList->children()) {
11761         CheckExpr(cast<Expr>(Child));
11762         ++InitFieldIndex.back();
11763       }
11764       InitFieldIndex.pop_back();
11765     }
11766 
11767     // Returns true if MemberExpr is checked and no further checking is needed.
11768     // Returns false if additional checking is required.
11769     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11770       llvm::SmallVector<FieldDecl*, 4> Fields;
11771       Expr *Base = E;
11772       bool ReferenceField = false;
11773 
11774       // Get the field members used.
11775       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11776         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11777         if (!FD)
11778           return false;
11779         Fields.push_back(FD);
11780         if (FD->getType()->isReferenceType())
11781           ReferenceField = true;
11782         Base = ME->getBase()->IgnoreParenImpCasts();
11783       }
11784 
11785       // Keep checking only if the base Decl is the same.
11786       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11787       if (!DRE || DRE->getDecl() != OrigDecl)
11788         return false;
11789 
11790       // A reference field can be bound to an unininitialized field.
11791       if (CheckReference && !ReferenceField)
11792         return true;
11793 
11794       // Convert FieldDecls to their index number.
11795       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11796       for (const FieldDecl *I : llvm::reverse(Fields))
11797         UsedFieldIndex.push_back(I->getFieldIndex());
11798 
11799       // See if a warning is needed by checking the first difference in index
11800       // numbers.  If field being used has index less than the field being
11801       // initialized, then the use is safe.
11802       for (auto UsedIter = UsedFieldIndex.begin(),
11803                 UsedEnd = UsedFieldIndex.end(),
11804                 OrigIter = InitFieldIndex.begin(),
11805                 OrigEnd = InitFieldIndex.end();
11806            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11807         if (*UsedIter < *OrigIter)
11808           return true;
11809         if (*UsedIter > *OrigIter)
11810           break;
11811       }
11812 
11813       // TODO: Add a different warning which will print the field names.
11814       HandleDeclRefExpr(DRE);
11815       return true;
11816     }
11817 
11818     // For most expressions, the cast is directly above the DeclRefExpr.
11819     // For conditional operators, the cast can be outside the conditional
11820     // operator if both expressions are DeclRefExpr's.
11821     void HandleValue(Expr *E) {
11822       E = E->IgnoreParens();
11823       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11824         HandleDeclRefExpr(DRE);
11825         return;
11826       }
11827 
11828       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11829         Visit(CO->getCond());
11830         HandleValue(CO->getTrueExpr());
11831         HandleValue(CO->getFalseExpr());
11832         return;
11833       }
11834 
11835       if (BinaryConditionalOperator *BCO =
11836               dyn_cast<BinaryConditionalOperator>(E)) {
11837         Visit(BCO->getCond());
11838         HandleValue(BCO->getFalseExpr());
11839         return;
11840       }
11841 
11842       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11843         HandleValue(OVE->getSourceExpr());
11844         return;
11845       }
11846 
11847       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11848         if (BO->getOpcode() == BO_Comma) {
11849           Visit(BO->getLHS());
11850           HandleValue(BO->getRHS());
11851           return;
11852         }
11853       }
11854 
11855       if (isa<MemberExpr>(E)) {
11856         if (isInitList) {
11857           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11858                                       false /*CheckReference*/))
11859             return;
11860         }
11861 
11862         Expr *Base = E->IgnoreParenImpCasts();
11863         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11864           // Check for static member variables and don't warn on them.
11865           if (!isa<FieldDecl>(ME->getMemberDecl()))
11866             return;
11867           Base = ME->getBase()->IgnoreParenImpCasts();
11868         }
11869         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11870           HandleDeclRefExpr(DRE);
11871         return;
11872       }
11873 
11874       Visit(E);
11875     }
11876 
11877     // Reference types not handled in HandleValue are handled here since all
11878     // uses of references are bad, not just r-value uses.
11879     void VisitDeclRefExpr(DeclRefExpr *E) {
11880       if (isReferenceType)
11881         HandleDeclRefExpr(E);
11882     }
11883 
11884     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11885       if (E->getCastKind() == CK_LValueToRValue) {
11886         HandleValue(E->getSubExpr());
11887         return;
11888       }
11889 
11890       Inherited::VisitImplicitCastExpr(E);
11891     }
11892 
11893     void VisitMemberExpr(MemberExpr *E) {
11894       if (isInitList) {
11895         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11896           return;
11897       }
11898 
11899       // Don't warn on arrays since they can be treated as pointers.
11900       if (E->getType()->canDecayToPointerType()) return;
11901 
11902       // Warn when a non-static method call is followed by non-static member
11903       // field accesses, which is followed by a DeclRefExpr.
11904       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11905       bool Warn = (MD && !MD->isStatic());
11906       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11907       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11908         if (!isa<FieldDecl>(ME->getMemberDecl()))
11909           Warn = false;
11910         Base = ME->getBase()->IgnoreParenImpCasts();
11911       }
11912 
11913       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11914         if (Warn)
11915           HandleDeclRefExpr(DRE);
11916         return;
11917       }
11918 
11919       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11920       // Visit that expression.
11921       Visit(Base);
11922     }
11923 
11924     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11925       Expr *Callee = E->getCallee();
11926 
11927       if (isa<UnresolvedLookupExpr>(Callee))
11928         return Inherited::VisitCXXOperatorCallExpr(E);
11929 
11930       Visit(Callee);
11931       for (auto Arg: E->arguments())
11932         HandleValue(Arg->IgnoreParenImpCasts());
11933     }
11934 
11935     void VisitUnaryOperator(UnaryOperator *E) {
11936       // For POD record types, addresses of its own members are well-defined.
11937       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11938           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11939         if (!isPODType)
11940           HandleValue(E->getSubExpr());
11941         return;
11942       }
11943 
11944       if (E->isIncrementDecrementOp()) {
11945         HandleValue(E->getSubExpr());
11946         return;
11947       }
11948 
11949       Inherited::VisitUnaryOperator(E);
11950     }
11951 
11952     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11953 
11954     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11955       if (E->getConstructor()->isCopyConstructor()) {
11956         Expr *ArgExpr = E->getArg(0);
11957         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11958           if (ILE->getNumInits() == 1)
11959             ArgExpr = ILE->getInit(0);
11960         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11961           if (ICE->getCastKind() == CK_NoOp)
11962             ArgExpr = ICE->getSubExpr();
11963         HandleValue(ArgExpr);
11964         return;
11965       }
11966       Inherited::VisitCXXConstructExpr(E);
11967     }
11968 
11969     void VisitCallExpr(CallExpr *E) {
11970       // Treat std::move as a use.
11971       if (E->isCallToStdMove()) {
11972         HandleValue(E->getArg(0));
11973         return;
11974       }
11975 
11976       Inherited::VisitCallExpr(E);
11977     }
11978 
11979     void VisitBinaryOperator(BinaryOperator *E) {
11980       if (E->isCompoundAssignmentOp()) {
11981         HandleValue(E->getLHS());
11982         Visit(E->getRHS());
11983         return;
11984       }
11985 
11986       Inherited::VisitBinaryOperator(E);
11987     }
11988 
11989     // A custom visitor for BinaryConditionalOperator is needed because the
11990     // regular visitor would check the condition and true expression separately
11991     // but both point to the same place giving duplicate diagnostics.
11992     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11993       Visit(E->getCond());
11994       Visit(E->getFalseExpr());
11995     }
11996 
11997     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11998       Decl* ReferenceDecl = DRE->getDecl();
11999       if (OrigDecl != ReferenceDecl) return;
12000       unsigned diag;
12001       if (isReferenceType) {
12002         diag = diag::warn_uninit_self_reference_in_reference_init;
12003       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12004         diag = diag::warn_static_self_reference_in_init;
12005       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12006                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12007                  DRE->getDecl()->getType()->isRecordType()) {
12008         diag = diag::warn_uninit_self_reference_in_init;
12009       } else {
12010         // Local variables will be handled by the CFG analysis.
12011         return;
12012       }
12013 
12014       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12015                             S.PDiag(diag)
12016                                 << DRE->getDecl() << OrigDecl->getLocation()
12017                                 << DRE->getSourceRange());
12018     }
12019   };
12020 
12021   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12022   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12023                                  bool DirectInit) {
12024     // Parameters arguments are occassionially constructed with itself,
12025     // for instance, in recursive functions.  Skip them.
12026     if (isa<ParmVarDecl>(OrigDecl))
12027       return;
12028 
12029     E = E->IgnoreParens();
12030 
12031     // Skip checking T a = a where T is not a record or reference type.
12032     // Doing so is a way to silence uninitialized warnings.
12033     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12034       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12035         if (ICE->getCastKind() == CK_LValueToRValue)
12036           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12037             if (DRE->getDecl() == OrigDecl)
12038               return;
12039 
12040     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12041   }
12042 } // end anonymous namespace
12043 
12044 namespace {
12045   // Simple wrapper to add the name of a variable or (if no variable is
12046   // available) a DeclarationName into a diagnostic.
12047   struct VarDeclOrName {
12048     VarDecl *VDecl;
12049     DeclarationName Name;
12050 
12051     friend const Sema::SemaDiagnosticBuilder &
12052     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12053       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12054     }
12055   };
12056 } // end anonymous namespace
12057 
12058 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12059                                             DeclarationName Name, QualType Type,
12060                                             TypeSourceInfo *TSI,
12061                                             SourceRange Range, bool DirectInit,
12062                                             Expr *Init) {
12063   bool IsInitCapture = !VDecl;
12064   assert((!VDecl || !VDecl->isInitCapture()) &&
12065          "init captures are expected to be deduced prior to initialization");
12066 
12067   VarDeclOrName VN{VDecl, Name};
12068 
12069   DeducedType *Deduced = Type->getContainedDeducedType();
12070   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12071 
12072   // C++11 [dcl.spec.auto]p3
12073   if (!Init) {
12074     assert(VDecl && "no init for init capture deduction?");
12075 
12076     // Except for class argument deduction, and then for an initializing
12077     // declaration only, i.e. no static at class scope or extern.
12078     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12079         VDecl->hasExternalStorage() ||
12080         VDecl->isStaticDataMember()) {
12081       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12082         << VDecl->getDeclName() << Type;
12083       return QualType();
12084     }
12085   }
12086 
12087   ArrayRef<Expr*> DeduceInits;
12088   if (Init)
12089     DeduceInits = Init;
12090 
12091   if (DirectInit) {
12092     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12093       DeduceInits = PL->exprs();
12094   }
12095 
12096   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12097     assert(VDecl && "non-auto type for init capture deduction?");
12098     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12099     InitializationKind Kind = InitializationKind::CreateForInit(
12100         VDecl->getLocation(), DirectInit, Init);
12101     // FIXME: Initialization should not be taking a mutable list of inits.
12102     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12103     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12104                                                        InitsCopy);
12105   }
12106 
12107   if (DirectInit) {
12108     if (auto *IL = dyn_cast<InitListExpr>(Init))
12109       DeduceInits = IL->inits();
12110   }
12111 
12112   // Deduction only works if we have exactly one source expression.
12113   if (DeduceInits.empty()) {
12114     // It isn't possible to write this directly, but it is possible to
12115     // end up in this situation with "auto x(some_pack...);"
12116     Diag(Init->getBeginLoc(), IsInitCapture
12117                                   ? diag::err_init_capture_no_expression
12118                                   : diag::err_auto_var_init_no_expression)
12119         << VN << Type << Range;
12120     return QualType();
12121   }
12122 
12123   if (DeduceInits.size() > 1) {
12124     Diag(DeduceInits[1]->getBeginLoc(),
12125          IsInitCapture ? diag::err_init_capture_multiple_expressions
12126                        : diag::err_auto_var_init_multiple_expressions)
12127         << VN << Type << Range;
12128     return QualType();
12129   }
12130 
12131   Expr *DeduceInit = DeduceInits[0];
12132   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12133     Diag(Init->getBeginLoc(), IsInitCapture
12134                                   ? diag::err_init_capture_paren_braces
12135                                   : diag::err_auto_var_init_paren_braces)
12136         << isa<InitListExpr>(Init) << VN << Type << Range;
12137     return QualType();
12138   }
12139 
12140   // Expressions default to 'id' when we're in a debugger.
12141   bool DefaultedAnyToId = false;
12142   if (getLangOpts().DebuggerCastResultToId &&
12143       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12144     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12145     if (Result.isInvalid()) {
12146       return QualType();
12147     }
12148     Init = Result.get();
12149     DefaultedAnyToId = true;
12150   }
12151 
12152   // C++ [dcl.decomp]p1:
12153   //   If the assignment-expression [...] has array type A and no ref-qualifier
12154   //   is present, e has type cv A
12155   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12156       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12157       DeduceInit->getType()->isConstantArrayType())
12158     return Context.getQualifiedType(DeduceInit->getType(),
12159                                     Type.getQualifiers());
12160 
12161   QualType DeducedType;
12162   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12163     if (!IsInitCapture)
12164       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12165     else if (isa<InitListExpr>(Init))
12166       Diag(Range.getBegin(),
12167            diag::err_init_capture_deduction_failure_from_init_list)
12168           << VN
12169           << (DeduceInit->getType().isNull() ? TSI->getType()
12170                                              : DeduceInit->getType())
12171           << DeduceInit->getSourceRange();
12172     else
12173       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12174           << VN << TSI->getType()
12175           << (DeduceInit->getType().isNull() ? TSI->getType()
12176                                              : DeduceInit->getType())
12177           << DeduceInit->getSourceRange();
12178   }
12179 
12180   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12181   // 'id' instead of a specific object type prevents most of our usual
12182   // checks.
12183   // We only want to warn outside of template instantiations, though:
12184   // inside a template, the 'id' could have come from a parameter.
12185   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12186       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12187     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12188     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12189   }
12190 
12191   return DeducedType;
12192 }
12193 
12194 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12195                                          Expr *Init) {
12196   assert(!Init || !Init->containsErrors());
12197   QualType DeducedType = deduceVarTypeFromInitializer(
12198       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12199       VDecl->getSourceRange(), DirectInit, Init);
12200   if (DeducedType.isNull()) {
12201     VDecl->setInvalidDecl();
12202     return true;
12203   }
12204 
12205   VDecl->setType(DeducedType);
12206   assert(VDecl->isLinkageValid());
12207 
12208   // In ARC, infer lifetime.
12209   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12210     VDecl->setInvalidDecl();
12211 
12212   if (getLangOpts().OpenCL)
12213     deduceOpenCLAddressSpace(VDecl);
12214 
12215   // If this is a redeclaration, check that the type we just deduced matches
12216   // the previously declared type.
12217   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12218     // We never need to merge the type, because we cannot form an incomplete
12219     // array of auto, nor deduce such a type.
12220     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12221   }
12222 
12223   // Check the deduced type is valid for a variable declaration.
12224   CheckVariableDeclarationType(VDecl);
12225   return VDecl->isInvalidDecl();
12226 }
12227 
12228 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12229                                               SourceLocation Loc) {
12230   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12231     Init = EWC->getSubExpr();
12232 
12233   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12234     Init = CE->getSubExpr();
12235 
12236   QualType InitType = Init->getType();
12237   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12238           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12239          "shouldn't be called if type doesn't have a non-trivial C struct");
12240   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12241     for (auto I : ILE->inits()) {
12242       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12243           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12244         continue;
12245       SourceLocation SL = I->getExprLoc();
12246       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12247     }
12248     return;
12249   }
12250 
12251   if (isa<ImplicitValueInitExpr>(Init)) {
12252     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12253       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12254                             NTCUK_Init);
12255   } else {
12256     // Assume all other explicit initializers involving copying some existing
12257     // object.
12258     // TODO: ignore any explicit initializers where we can guarantee
12259     // copy-elision.
12260     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12261       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12262   }
12263 }
12264 
12265 namespace {
12266 
12267 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12268   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12269   // in the source code or implicitly by the compiler if it is in a union
12270   // defined in a system header and has non-trivial ObjC ownership
12271   // qualifications. We don't want those fields to participate in determining
12272   // whether the containing union is non-trivial.
12273   return FD->hasAttr<UnavailableAttr>();
12274 }
12275 
12276 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12277     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12278                                     void> {
12279   using Super =
12280       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12281                                     void>;
12282 
12283   DiagNonTrivalCUnionDefaultInitializeVisitor(
12284       QualType OrigTy, SourceLocation OrigLoc,
12285       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12286       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12287 
12288   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12289                      const FieldDecl *FD, bool InNonTrivialUnion) {
12290     if (const auto *AT = S.Context.getAsArrayType(QT))
12291       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12292                                      InNonTrivialUnion);
12293     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12294   }
12295 
12296   void visitARCStrong(QualType QT, const FieldDecl *FD,
12297                       bool InNonTrivialUnion) {
12298     if (InNonTrivialUnion)
12299       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12300           << 1 << 0 << QT << FD->getName();
12301   }
12302 
12303   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12304     if (InNonTrivialUnion)
12305       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12306           << 1 << 0 << QT << FD->getName();
12307   }
12308 
12309   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12310     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12311     if (RD->isUnion()) {
12312       if (OrigLoc.isValid()) {
12313         bool IsUnion = false;
12314         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12315           IsUnion = OrigRD->isUnion();
12316         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12317             << 0 << OrigTy << IsUnion << UseContext;
12318         // Reset OrigLoc so that this diagnostic is emitted only once.
12319         OrigLoc = SourceLocation();
12320       }
12321       InNonTrivialUnion = true;
12322     }
12323 
12324     if (InNonTrivialUnion)
12325       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12326           << 0 << 0 << QT.getUnqualifiedType() << "";
12327 
12328     for (const FieldDecl *FD : RD->fields())
12329       if (!shouldIgnoreForRecordTriviality(FD))
12330         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12331   }
12332 
12333   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12334 
12335   // The non-trivial C union type or the struct/union type that contains a
12336   // non-trivial C union.
12337   QualType OrigTy;
12338   SourceLocation OrigLoc;
12339   Sema::NonTrivialCUnionContext UseContext;
12340   Sema &S;
12341 };
12342 
12343 struct DiagNonTrivalCUnionDestructedTypeVisitor
12344     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12345   using Super =
12346       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12347 
12348   DiagNonTrivalCUnionDestructedTypeVisitor(
12349       QualType OrigTy, SourceLocation OrigLoc,
12350       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12351       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12352 
12353   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12354                      const FieldDecl *FD, bool InNonTrivialUnion) {
12355     if (const auto *AT = S.Context.getAsArrayType(QT))
12356       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12357                                      InNonTrivialUnion);
12358     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12359   }
12360 
12361   void visitARCStrong(QualType QT, const FieldDecl *FD,
12362                       bool InNonTrivialUnion) {
12363     if (InNonTrivialUnion)
12364       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12365           << 1 << 1 << QT << FD->getName();
12366   }
12367 
12368   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12369     if (InNonTrivialUnion)
12370       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12371           << 1 << 1 << QT << FD->getName();
12372   }
12373 
12374   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12375     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12376     if (RD->isUnion()) {
12377       if (OrigLoc.isValid()) {
12378         bool IsUnion = false;
12379         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12380           IsUnion = OrigRD->isUnion();
12381         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12382             << 1 << OrigTy << IsUnion << UseContext;
12383         // Reset OrigLoc so that this diagnostic is emitted only once.
12384         OrigLoc = SourceLocation();
12385       }
12386       InNonTrivialUnion = true;
12387     }
12388 
12389     if (InNonTrivialUnion)
12390       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12391           << 0 << 1 << QT.getUnqualifiedType() << "";
12392 
12393     for (const FieldDecl *FD : RD->fields())
12394       if (!shouldIgnoreForRecordTriviality(FD))
12395         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12396   }
12397 
12398   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12399   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12400                           bool InNonTrivialUnion) {}
12401 
12402   // The non-trivial C union type or the struct/union type that contains a
12403   // non-trivial C union.
12404   QualType OrigTy;
12405   SourceLocation OrigLoc;
12406   Sema::NonTrivialCUnionContext UseContext;
12407   Sema &S;
12408 };
12409 
12410 struct DiagNonTrivalCUnionCopyVisitor
12411     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12412   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12413 
12414   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12415                                  Sema::NonTrivialCUnionContext UseContext,
12416                                  Sema &S)
12417       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12418 
12419   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12420                      const FieldDecl *FD, bool InNonTrivialUnion) {
12421     if (const auto *AT = S.Context.getAsArrayType(QT))
12422       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12423                                      InNonTrivialUnion);
12424     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12425   }
12426 
12427   void visitARCStrong(QualType QT, const FieldDecl *FD,
12428                       bool InNonTrivialUnion) {
12429     if (InNonTrivialUnion)
12430       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12431           << 1 << 2 << QT << FD->getName();
12432   }
12433 
12434   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12435     if (InNonTrivialUnion)
12436       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12437           << 1 << 2 << QT << FD->getName();
12438   }
12439 
12440   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12441     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12442     if (RD->isUnion()) {
12443       if (OrigLoc.isValid()) {
12444         bool IsUnion = false;
12445         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12446           IsUnion = OrigRD->isUnion();
12447         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12448             << 2 << OrigTy << IsUnion << UseContext;
12449         // Reset OrigLoc so that this diagnostic is emitted only once.
12450         OrigLoc = SourceLocation();
12451       }
12452       InNonTrivialUnion = true;
12453     }
12454 
12455     if (InNonTrivialUnion)
12456       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12457           << 0 << 2 << QT.getUnqualifiedType() << "";
12458 
12459     for (const FieldDecl *FD : RD->fields())
12460       if (!shouldIgnoreForRecordTriviality(FD))
12461         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12462   }
12463 
12464   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12465                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12466   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12467   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12468                             bool InNonTrivialUnion) {}
12469 
12470   // The non-trivial C union type or the struct/union type that contains a
12471   // non-trivial C union.
12472   QualType OrigTy;
12473   SourceLocation OrigLoc;
12474   Sema::NonTrivialCUnionContext UseContext;
12475   Sema &S;
12476 };
12477 
12478 } // namespace
12479 
12480 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12481                                  NonTrivialCUnionContext UseContext,
12482                                  unsigned NonTrivialKind) {
12483   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12484           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12485           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12486          "shouldn't be called if type doesn't have a non-trivial C union");
12487 
12488   if ((NonTrivialKind & NTCUK_Init) &&
12489       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12490     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12491         .visit(QT, nullptr, false);
12492   if ((NonTrivialKind & NTCUK_Destruct) &&
12493       QT.hasNonTrivialToPrimitiveDestructCUnion())
12494     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12495         .visit(QT, nullptr, false);
12496   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12497     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12498         .visit(QT, nullptr, false);
12499 }
12500 
12501 /// AddInitializerToDecl - Adds the initializer Init to the
12502 /// declaration dcl. If DirectInit is true, this is C++ direct
12503 /// initialization rather than copy initialization.
12504 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12505   // If there is no declaration, there was an error parsing it.  Just ignore
12506   // the initializer.
12507   if (!RealDecl || RealDecl->isInvalidDecl()) {
12508     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12509     return;
12510   }
12511 
12512   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12513     // Pure-specifiers are handled in ActOnPureSpecifier.
12514     Diag(Method->getLocation(), diag::err_member_function_initialization)
12515       << Method->getDeclName() << Init->getSourceRange();
12516     Method->setInvalidDecl();
12517     return;
12518   }
12519 
12520   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12521   if (!VDecl) {
12522     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12523     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12524     RealDecl->setInvalidDecl();
12525     return;
12526   }
12527 
12528   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12529   if (VDecl->getType()->isUndeducedType()) {
12530     // Attempt typo correction early so that the type of the init expression can
12531     // be deduced based on the chosen correction if the original init contains a
12532     // TypoExpr.
12533     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12534     if (!Res.isUsable()) {
12535       // There are unresolved typos in Init, just drop them.
12536       // FIXME: improve the recovery strategy to preserve the Init.
12537       RealDecl->setInvalidDecl();
12538       return;
12539     }
12540     if (Res.get()->containsErrors()) {
12541       // Invalidate the decl as we don't know the type for recovery-expr yet.
12542       RealDecl->setInvalidDecl();
12543       VDecl->setInit(Res.get());
12544       return;
12545     }
12546     Init = Res.get();
12547 
12548     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12549       return;
12550   }
12551 
12552   // dllimport cannot be used on variable definitions.
12553   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12554     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12555     VDecl->setInvalidDecl();
12556     return;
12557   }
12558 
12559   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12560     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12561     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12562     VDecl->setInvalidDecl();
12563     return;
12564   }
12565 
12566   if (!VDecl->getType()->isDependentType()) {
12567     // A definition must end up with a complete type, which means it must be
12568     // complete with the restriction that an array type might be completed by
12569     // the initializer; note that later code assumes this restriction.
12570     QualType BaseDeclType = VDecl->getType();
12571     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12572       BaseDeclType = Array->getElementType();
12573     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12574                             diag::err_typecheck_decl_incomplete_type)) {
12575       RealDecl->setInvalidDecl();
12576       return;
12577     }
12578 
12579     // The variable can not have an abstract class type.
12580     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12581                                diag::err_abstract_type_in_decl,
12582                                AbstractVariableType))
12583       VDecl->setInvalidDecl();
12584   }
12585 
12586   // If adding the initializer will turn this declaration into a definition,
12587   // and we already have a definition for this variable, diagnose or otherwise
12588   // handle the situation.
12589   if (VarDecl *Def = VDecl->getDefinition())
12590     if (Def != VDecl &&
12591         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12592         !VDecl->isThisDeclarationADemotedDefinition() &&
12593         checkVarDeclRedefinition(Def, VDecl))
12594       return;
12595 
12596   if (getLangOpts().CPlusPlus) {
12597     // C++ [class.static.data]p4
12598     //   If a static data member is of const integral or const
12599     //   enumeration type, its declaration in the class definition can
12600     //   specify a constant-initializer which shall be an integral
12601     //   constant expression (5.19). In that case, the member can appear
12602     //   in integral constant expressions. The member shall still be
12603     //   defined in a namespace scope if it is used in the program and the
12604     //   namespace scope definition shall not contain an initializer.
12605     //
12606     // We already performed a redefinition check above, but for static
12607     // data members we also need to check whether there was an in-class
12608     // declaration with an initializer.
12609     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12610       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12611           << VDecl->getDeclName();
12612       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12613            diag::note_previous_initializer)
12614           << 0;
12615       return;
12616     }
12617 
12618     if (VDecl->hasLocalStorage())
12619       setFunctionHasBranchProtectedScope();
12620 
12621     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12622       VDecl->setInvalidDecl();
12623       return;
12624     }
12625   }
12626 
12627   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12628   // a kernel function cannot be initialized."
12629   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12630     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12631     VDecl->setInvalidDecl();
12632     return;
12633   }
12634 
12635   // The LoaderUninitialized attribute acts as a definition (of undef).
12636   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12637     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12638     VDecl->setInvalidDecl();
12639     return;
12640   }
12641 
12642   // Get the decls type and save a reference for later, since
12643   // CheckInitializerTypes may change it.
12644   QualType DclT = VDecl->getType(), SavT = DclT;
12645 
12646   // Expressions default to 'id' when we're in a debugger
12647   // and we are assigning it to a variable of Objective-C pointer type.
12648   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12649       Init->getType() == Context.UnknownAnyTy) {
12650     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12651     if (Result.isInvalid()) {
12652       VDecl->setInvalidDecl();
12653       return;
12654     }
12655     Init = Result.get();
12656   }
12657 
12658   // Perform the initialization.
12659   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12660   if (!VDecl->isInvalidDecl()) {
12661     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12662     InitializationKind Kind = InitializationKind::CreateForInit(
12663         VDecl->getLocation(), DirectInit, Init);
12664 
12665     MultiExprArg Args = Init;
12666     if (CXXDirectInit)
12667       Args = MultiExprArg(CXXDirectInit->getExprs(),
12668                           CXXDirectInit->getNumExprs());
12669 
12670     // Try to correct any TypoExprs in the initialization arguments.
12671     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12672       ExprResult Res = CorrectDelayedTyposInExpr(
12673           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12674           [this, Entity, Kind](Expr *E) {
12675             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12676             return Init.Failed() ? ExprError() : E;
12677           });
12678       if (Res.isInvalid()) {
12679         VDecl->setInvalidDecl();
12680       } else if (Res.get() != Args[Idx]) {
12681         Args[Idx] = Res.get();
12682       }
12683     }
12684     if (VDecl->isInvalidDecl())
12685       return;
12686 
12687     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12688                                    /*TopLevelOfInitList=*/false,
12689                                    /*TreatUnavailableAsInvalid=*/false);
12690     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12691     if (Result.isInvalid()) {
12692       // If the provided initializer fails to initialize the var decl,
12693       // we attach a recovery expr for better recovery.
12694       auto RecoveryExpr =
12695           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12696       if (RecoveryExpr.get())
12697         VDecl->setInit(RecoveryExpr.get());
12698       return;
12699     }
12700 
12701     Init = Result.getAs<Expr>();
12702   }
12703 
12704   // Check for self-references within variable initializers.
12705   // Variables declared within a function/method body (except for references)
12706   // are handled by a dataflow analysis.
12707   // This is undefined behavior in C++, but valid in C.
12708   if (getLangOpts().CPlusPlus)
12709     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12710         VDecl->getType()->isReferenceType())
12711       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12712 
12713   // If the type changed, it means we had an incomplete type that was
12714   // completed by the initializer. For example:
12715   //   int ary[] = { 1, 3, 5 };
12716   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12717   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12718     VDecl->setType(DclT);
12719 
12720   if (!VDecl->isInvalidDecl()) {
12721     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12722 
12723     if (VDecl->hasAttr<BlocksAttr>())
12724       checkRetainCycles(VDecl, Init);
12725 
12726     // It is safe to assign a weak reference into a strong variable.
12727     // Although this code can still have problems:
12728     //   id x = self.weakProp;
12729     //   id y = self.weakProp;
12730     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12731     // paths through the function. This should be revisited if
12732     // -Wrepeated-use-of-weak is made flow-sensitive.
12733     if (FunctionScopeInfo *FSI = getCurFunction())
12734       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12735            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12736           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12737                            Init->getBeginLoc()))
12738         FSI->markSafeWeakUse(Init);
12739   }
12740 
12741   // The initialization is usually a full-expression.
12742   //
12743   // FIXME: If this is a braced initialization of an aggregate, it is not
12744   // an expression, and each individual field initializer is a separate
12745   // full-expression. For instance, in:
12746   //
12747   //   struct Temp { ~Temp(); };
12748   //   struct S { S(Temp); };
12749   //   struct T { S a, b; } t = { Temp(), Temp() }
12750   //
12751   // we should destroy the first Temp before constructing the second.
12752   ExprResult Result =
12753       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12754                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12755   if (Result.isInvalid()) {
12756     VDecl->setInvalidDecl();
12757     return;
12758   }
12759   Init = Result.get();
12760 
12761   // Attach the initializer to the decl.
12762   VDecl->setInit(Init);
12763 
12764   if (VDecl->isLocalVarDecl()) {
12765     // Don't check the initializer if the declaration is malformed.
12766     if (VDecl->isInvalidDecl()) {
12767       // do nothing
12768 
12769     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12770     // This is true even in C++ for OpenCL.
12771     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12772       CheckForConstantInitializer(Init, DclT);
12773 
12774     // Otherwise, C++ does not restrict the initializer.
12775     } else if (getLangOpts().CPlusPlus) {
12776       // do nothing
12777 
12778     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12779     // static storage duration shall be constant expressions or string literals.
12780     } else if (VDecl->getStorageClass() == SC_Static) {
12781       CheckForConstantInitializer(Init, DclT);
12782 
12783     // C89 is stricter than C99 for aggregate initializers.
12784     // C89 6.5.7p3: All the expressions [...] in an initializer list
12785     // for an object that has aggregate or union type shall be
12786     // constant expressions.
12787     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12788                isa<InitListExpr>(Init)) {
12789       const Expr *Culprit;
12790       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12791         Diag(Culprit->getExprLoc(),
12792              diag::ext_aggregate_init_not_constant)
12793           << Culprit->getSourceRange();
12794       }
12795     }
12796 
12797     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12798       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12799         if (VDecl->hasLocalStorage())
12800           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12801   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12802              VDecl->getLexicalDeclContext()->isRecord()) {
12803     // This is an in-class initialization for a static data member, e.g.,
12804     //
12805     // struct S {
12806     //   static const int value = 17;
12807     // };
12808 
12809     // C++ [class.mem]p4:
12810     //   A member-declarator can contain a constant-initializer only
12811     //   if it declares a static member (9.4) of const integral or
12812     //   const enumeration type, see 9.4.2.
12813     //
12814     // C++11 [class.static.data]p3:
12815     //   If a non-volatile non-inline const static data member is of integral
12816     //   or enumeration type, its declaration in the class definition can
12817     //   specify a brace-or-equal-initializer in which every initializer-clause
12818     //   that is an assignment-expression is a constant expression. A static
12819     //   data member of literal type can be declared in the class definition
12820     //   with the constexpr specifier; if so, its declaration shall specify a
12821     //   brace-or-equal-initializer in which every initializer-clause that is
12822     //   an assignment-expression is a constant expression.
12823 
12824     // Do nothing on dependent types.
12825     if (DclT->isDependentType()) {
12826 
12827     // Allow any 'static constexpr' members, whether or not they are of literal
12828     // type. We separately check that every constexpr variable is of literal
12829     // type.
12830     } else if (VDecl->isConstexpr()) {
12831 
12832     // Require constness.
12833     } else if (!DclT.isConstQualified()) {
12834       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12835         << Init->getSourceRange();
12836       VDecl->setInvalidDecl();
12837 
12838     // We allow integer constant expressions in all cases.
12839     } else if (DclT->isIntegralOrEnumerationType()) {
12840       // Check whether the expression is a constant expression.
12841       SourceLocation Loc;
12842       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12843         // In C++11, a non-constexpr const static data member with an
12844         // in-class initializer cannot be volatile.
12845         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12846       else if (Init->isValueDependent())
12847         ; // Nothing to check.
12848       else if (Init->isIntegerConstantExpr(Context, &Loc))
12849         ; // Ok, it's an ICE!
12850       else if (Init->getType()->isScopedEnumeralType() &&
12851                Init->isCXX11ConstantExpr(Context))
12852         ; // Ok, it is a scoped-enum constant expression.
12853       else if (Init->isEvaluatable(Context)) {
12854         // If we can constant fold the initializer through heroics, accept it,
12855         // but report this as a use of an extension for -pedantic.
12856         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12857           << Init->getSourceRange();
12858       } else {
12859         // Otherwise, this is some crazy unknown case.  Report the issue at the
12860         // location provided by the isIntegerConstantExpr failed check.
12861         Diag(Loc, diag::err_in_class_initializer_non_constant)
12862           << Init->getSourceRange();
12863         VDecl->setInvalidDecl();
12864       }
12865 
12866     // We allow foldable floating-point constants as an extension.
12867     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12868       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12869       // it anyway and provide a fixit to add the 'constexpr'.
12870       if (getLangOpts().CPlusPlus11) {
12871         Diag(VDecl->getLocation(),
12872              diag::ext_in_class_initializer_float_type_cxx11)
12873             << DclT << Init->getSourceRange();
12874         Diag(VDecl->getBeginLoc(),
12875              diag::note_in_class_initializer_float_type_cxx11)
12876             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12877       } else {
12878         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12879           << DclT << Init->getSourceRange();
12880 
12881         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12882           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12883             << Init->getSourceRange();
12884           VDecl->setInvalidDecl();
12885         }
12886       }
12887 
12888     // Suggest adding 'constexpr' in C++11 for literal types.
12889     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12890       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12891           << DclT << Init->getSourceRange()
12892           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12893       VDecl->setConstexpr(true);
12894 
12895     } else {
12896       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12897         << DclT << Init->getSourceRange();
12898       VDecl->setInvalidDecl();
12899     }
12900   } else if (VDecl->isFileVarDecl()) {
12901     // In C, extern is typically used to avoid tentative definitions when
12902     // declaring variables in headers, but adding an intializer makes it a
12903     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12904     // In C++, extern is often used to give implictly static const variables
12905     // external linkage, so don't warn in that case. If selectany is present,
12906     // this might be header code intended for C and C++ inclusion, so apply the
12907     // C++ rules.
12908     if (VDecl->getStorageClass() == SC_Extern &&
12909         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12910          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12911         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12912         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12913       Diag(VDecl->getLocation(), diag::warn_extern_init);
12914 
12915     // In Microsoft C++ mode, a const variable defined in namespace scope has
12916     // external linkage by default if the variable is declared with
12917     // __declspec(dllexport).
12918     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12919         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12920         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12921       VDecl->setStorageClass(SC_Extern);
12922 
12923     // C99 6.7.8p4. All file scoped initializers need to be constant.
12924     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12925       CheckForConstantInitializer(Init, DclT);
12926   }
12927 
12928   QualType InitType = Init->getType();
12929   if (!InitType.isNull() &&
12930       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12931        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12932     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12933 
12934   // We will represent direct-initialization similarly to copy-initialization:
12935   //    int x(1);  -as-> int x = 1;
12936   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12937   //
12938   // Clients that want to distinguish between the two forms, can check for
12939   // direct initializer using VarDecl::getInitStyle().
12940   // A major benefit is that clients that don't particularly care about which
12941   // exactly form was it (like the CodeGen) can handle both cases without
12942   // special case code.
12943 
12944   // C++ 8.5p11:
12945   // The form of initialization (using parentheses or '=') is generally
12946   // insignificant, but does matter when the entity being initialized has a
12947   // class type.
12948   if (CXXDirectInit) {
12949     assert(DirectInit && "Call-style initializer must be direct init.");
12950     VDecl->setInitStyle(VarDecl::CallInit);
12951   } else if (DirectInit) {
12952     // This must be list-initialization. No other way is direct-initialization.
12953     VDecl->setInitStyle(VarDecl::ListInit);
12954   }
12955 
12956   if (LangOpts.OpenMP &&
12957       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12958       VDecl->isFileVarDecl())
12959     DeclsToCheckForDeferredDiags.insert(VDecl);
12960   CheckCompleteVariableDeclaration(VDecl);
12961 }
12962 
12963 /// ActOnInitializerError - Given that there was an error parsing an
12964 /// initializer for the given declaration, try to at least re-establish
12965 /// invariants such as whether a variable's type is either dependent or
12966 /// complete.
12967 void Sema::ActOnInitializerError(Decl *D) {
12968   // Our main concern here is re-establishing invariants like "a
12969   // variable's type is either dependent or complete".
12970   if (!D || D->isInvalidDecl()) return;
12971 
12972   VarDecl *VD = dyn_cast<VarDecl>(D);
12973   if (!VD) return;
12974 
12975   // Bindings are not usable if we can't make sense of the initializer.
12976   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12977     for (auto *BD : DD->bindings())
12978       BD->setInvalidDecl();
12979 
12980   // Auto types are meaningless if we can't make sense of the initializer.
12981   if (VD->getType()->isUndeducedType()) {
12982     D->setInvalidDecl();
12983     return;
12984   }
12985 
12986   QualType Ty = VD->getType();
12987   if (Ty->isDependentType()) return;
12988 
12989   // Require a complete type.
12990   if (RequireCompleteType(VD->getLocation(),
12991                           Context.getBaseElementType(Ty),
12992                           diag::err_typecheck_decl_incomplete_type)) {
12993     VD->setInvalidDecl();
12994     return;
12995   }
12996 
12997   // Require a non-abstract type.
12998   if (RequireNonAbstractType(VD->getLocation(), Ty,
12999                              diag::err_abstract_type_in_decl,
13000                              AbstractVariableType)) {
13001     VD->setInvalidDecl();
13002     return;
13003   }
13004 
13005   // Don't bother complaining about constructors or destructors,
13006   // though.
13007 }
13008 
13009 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13010   // If there is no declaration, there was an error parsing it. Just ignore it.
13011   if (!RealDecl)
13012     return;
13013 
13014   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13015     QualType Type = Var->getType();
13016 
13017     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13018     if (isa<DecompositionDecl>(RealDecl)) {
13019       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13020       Var->setInvalidDecl();
13021       return;
13022     }
13023 
13024     if (Type->isUndeducedType() &&
13025         DeduceVariableDeclarationType(Var, false, nullptr))
13026       return;
13027 
13028     // C++11 [class.static.data]p3: A static data member can be declared with
13029     // the constexpr specifier; if so, its declaration shall specify
13030     // a brace-or-equal-initializer.
13031     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13032     // the definition of a variable [...] or the declaration of a static data
13033     // member.
13034     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13035         !Var->isThisDeclarationADemotedDefinition()) {
13036       if (Var->isStaticDataMember()) {
13037         // C++1z removes the relevant rule; the in-class declaration is always
13038         // a definition there.
13039         if (!getLangOpts().CPlusPlus17 &&
13040             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13041           Diag(Var->getLocation(),
13042                diag::err_constexpr_static_mem_var_requires_init)
13043               << Var;
13044           Var->setInvalidDecl();
13045           return;
13046         }
13047       } else {
13048         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13049         Var->setInvalidDecl();
13050         return;
13051       }
13052     }
13053 
13054     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13055     // be initialized.
13056     if (!Var->isInvalidDecl() &&
13057         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13058         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13059       bool HasConstExprDefaultConstructor = false;
13060       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13061         for (auto *Ctor : RD->ctors()) {
13062           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13063               Ctor->getMethodQualifiers().getAddressSpace() ==
13064                   LangAS::opencl_constant) {
13065             HasConstExprDefaultConstructor = true;
13066           }
13067         }
13068       }
13069       if (!HasConstExprDefaultConstructor) {
13070         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13071         Var->setInvalidDecl();
13072         return;
13073       }
13074     }
13075 
13076     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13077       if (Var->getStorageClass() == SC_Extern) {
13078         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13079             << Var;
13080         Var->setInvalidDecl();
13081         return;
13082       }
13083       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13084                               diag::err_typecheck_decl_incomplete_type)) {
13085         Var->setInvalidDecl();
13086         return;
13087       }
13088       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13089         if (!RD->hasTrivialDefaultConstructor()) {
13090           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13091           Var->setInvalidDecl();
13092           return;
13093         }
13094       }
13095       // The declaration is unitialized, no need for further checks.
13096       return;
13097     }
13098 
13099     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13100     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13101         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13102       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13103                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13104 
13105 
13106     switch (DefKind) {
13107     case VarDecl::Definition:
13108       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13109         break;
13110 
13111       // We have an out-of-line definition of a static data member
13112       // that has an in-class initializer, so we type-check this like
13113       // a declaration.
13114       //
13115       LLVM_FALLTHROUGH;
13116 
13117     case VarDecl::DeclarationOnly:
13118       // It's only a declaration.
13119 
13120       // Block scope. C99 6.7p7: If an identifier for an object is
13121       // declared with no linkage (C99 6.2.2p6), the type for the
13122       // object shall be complete.
13123       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13124           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13125           RequireCompleteType(Var->getLocation(), Type,
13126                               diag::err_typecheck_decl_incomplete_type))
13127         Var->setInvalidDecl();
13128 
13129       // Make sure that the type is not abstract.
13130       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13131           RequireNonAbstractType(Var->getLocation(), Type,
13132                                  diag::err_abstract_type_in_decl,
13133                                  AbstractVariableType))
13134         Var->setInvalidDecl();
13135       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13136           Var->getStorageClass() == SC_PrivateExtern) {
13137         Diag(Var->getLocation(), diag::warn_private_extern);
13138         Diag(Var->getLocation(), diag::note_private_extern);
13139       }
13140 
13141       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13142           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13143         ExternalDeclarations.push_back(Var);
13144 
13145       return;
13146 
13147     case VarDecl::TentativeDefinition:
13148       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13149       // object that has file scope without an initializer, and without a
13150       // storage-class specifier or with the storage-class specifier "static",
13151       // constitutes a tentative definition. Note: A tentative definition with
13152       // external linkage is valid (C99 6.2.2p5).
13153       if (!Var->isInvalidDecl()) {
13154         if (const IncompleteArrayType *ArrayT
13155                                     = Context.getAsIncompleteArrayType(Type)) {
13156           if (RequireCompleteSizedType(
13157                   Var->getLocation(), ArrayT->getElementType(),
13158                   diag::err_array_incomplete_or_sizeless_type))
13159             Var->setInvalidDecl();
13160         } else if (Var->getStorageClass() == SC_Static) {
13161           // C99 6.9.2p3: If the declaration of an identifier for an object is
13162           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13163           // declared type shall not be an incomplete type.
13164           // NOTE: code such as the following
13165           //     static struct s;
13166           //     struct s { int a; };
13167           // is accepted by gcc. Hence here we issue a warning instead of
13168           // an error and we do not invalidate the static declaration.
13169           // NOTE: to avoid multiple warnings, only check the first declaration.
13170           if (Var->isFirstDecl())
13171             RequireCompleteType(Var->getLocation(), Type,
13172                                 diag::ext_typecheck_decl_incomplete_type);
13173         }
13174       }
13175 
13176       // Record the tentative definition; we're done.
13177       if (!Var->isInvalidDecl())
13178         TentativeDefinitions.push_back(Var);
13179       return;
13180     }
13181 
13182     // Provide a specific diagnostic for uninitialized variable
13183     // definitions with incomplete array type.
13184     if (Type->isIncompleteArrayType()) {
13185       Diag(Var->getLocation(),
13186            diag::err_typecheck_incomplete_array_needs_initializer);
13187       Var->setInvalidDecl();
13188       return;
13189     }
13190 
13191     // Provide a specific diagnostic for uninitialized variable
13192     // definitions with reference type.
13193     if (Type->isReferenceType()) {
13194       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13195           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13196       return;
13197     }
13198 
13199     // Do not attempt to type-check the default initializer for a
13200     // variable with dependent type.
13201     if (Type->isDependentType())
13202       return;
13203 
13204     if (Var->isInvalidDecl())
13205       return;
13206 
13207     if (!Var->hasAttr<AliasAttr>()) {
13208       if (RequireCompleteType(Var->getLocation(),
13209                               Context.getBaseElementType(Type),
13210                               diag::err_typecheck_decl_incomplete_type)) {
13211         Var->setInvalidDecl();
13212         return;
13213       }
13214     } else {
13215       return;
13216     }
13217 
13218     // The variable can not have an abstract class type.
13219     if (RequireNonAbstractType(Var->getLocation(), Type,
13220                                diag::err_abstract_type_in_decl,
13221                                AbstractVariableType)) {
13222       Var->setInvalidDecl();
13223       return;
13224     }
13225 
13226     // Check for jumps past the implicit initializer.  C++0x
13227     // clarifies that this applies to a "variable with automatic
13228     // storage duration", not a "local variable".
13229     // C++11 [stmt.dcl]p3
13230     //   A program that jumps from a point where a variable with automatic
13231     //   storage duration is not in scope to a point where it is in scope is
13232     //   ill-formed unless the variable has scalar type, class type with a
13233     //   trivial default constructor and a trivial destructor, a cv-qualified
13234     //   version of one of these types, or an array of one of the preceding
13235     //   types and is declared without an initializer.
13236     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13237       if (const RecordType *Record
13238             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13239         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13240         // Mark the function (if we're in one) for further checking even if the
13241         // looser rules of C++11 do not require such checks, so that we can
13242         // diagnose incompatibilities with C++98.
13243         if (!CXXRecord->isPOD())
13244           setFunctionHasBranchProtectedScope();
13245       }
13246     }
13247     // In OpenCL, we can't initialize objects in the __local address space,
13248     // even implicitly, so don't synthesize an implicit initializer.
13249     if (getLangOpts().OpenCL &&
13250         Var->getType().getAddressSpace() == LangAS::opencl_local)
13251       return;
13252     // C++03 [dcl.init]p9:
13253     //   If no initializer is specified for an object, and the
13254     //   object is of (possibly cv-qualified) non-POD class type (or
13255     //   array thereof), the object shall be default-initialized; if
13256     //   the object is of const-qualified type, the underlying class
13257     //   type shall have a user-declared default
13258     //   constructor. Otherwise, if no initializer is specified for
13259     //   a non- static object, the object and its subobjects, if
13260     //   any, have an indeterminate initial value); if the object
13261     //   or any of its subobjects are of const-qualified type, the
13262     //   program is ill-formed.
13263     // C++0x [dcl.init]p11:
13264     //   If no initializer is specified for an object, the object is
13265     //   default-initialized; [...].
13266     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13267     InitializationKind Kind
13268       = InitializationKind::CreateDefault(Var->getLocation());
13269 
13270     InitializationSequence InitSeq(*this, Entity, Kind, None);
13271     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13272 
13273     if (Init.get()) {
13274       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13275       // This is important for template substitution.
13276       Var->setInitStyle(VarDecl::CallInit);
13277     } else if (Init.isInvalid()) {
13278       // If default-init fails, attach a recovery-expr initializer to track
13279       // that initialization was attempted and failed.
13280       auto RecoveryExpr =
13281           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13282       if (RecoveryExpr.get())
13283         Var->setInit(RecoveryExpr.get());
13284     }
13285 
13286     CheckCompleteVariableDeclaration(Var);
13287   }
13288 }
13289 
13290 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13291   // If there is no declaration, there was an error parsing it. Ignore it.
13292   if (!D)
13293     return;
13294 
13295   VarDecl *VD = dyn_cast<VarDecl>(D);
13296   if (!VD) {
13297     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13298     D->setInvalidDecl();
13299     return;
13300   }
13301 
13302   VD->setCXXForRangeDecl(true);
13303 
13304   // for-range-declaration cannot be given a storage class specifier.
13305   int Error = -1;
13306   switch (VD->getStorageClass()) {
13307   case SC_None:
13308     break;
13309   case SC_Extern:
13310     Error = 0;
13311     break;
13312   case SC_Static:
13313     Error = 1;
13314     break;
13315   case SC_PrivateExtern:
13316     Error = 2;
13317     break;
13318   case SC_Auto:
13319     Error = 3;
13320     break;
13321   case SC_Register:
13322     Error = 4;
13323     break;
13324   }
13325 
13326   // for-range-declaration cannot be given a storage class specifier con't.
13327   switch (VD->getTSCSpec()) {
13328   case TSCS_thread_local:
13329     Error = 6;
13330     break;
13331   case TSCS___thread:
13332   case TSCS__Thread_local:
13333   case TSCS_unspecified:
13334     break;
13335   }
13336 
13337   if (Error != -1) {
13338     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13339         << VD << Error;
13340     D->setInvalidDecl();
13341   }
13342 }
13343 
13344 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13345                                             IdentifierInfo *Ident,
13346                                             ParsedAttributes &Attrs) {
13347   // C++1y [stmt.iter]p1:
13348   //   A range-based for statement of the form
13349   //      for ( for-range-identifier : for-range-initializer ) statement
13350   //   is equivalent to
13351   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13352   DeclSpec DS(Attrs.getPool().getFactory());
13353 
13354   const char *PrevSpec;
13355   unsigned DiagID;
13356   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13357                      getPrintingPolicy());
13358 
13359   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13360   D.SetIdentifier(Ident, IdentLoc);
13361   D.takeAttributes(Attrs);
13362 
13363   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13364                 IdentLoc);
13365   Decl *Var = ActOnDeclarator(S, D);
13366   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13367   FinalizeDeclaration(Var);
13368   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13369                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13370                                                       : IdentLoc);
13371 }
13372 
13373 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13374   if (var->isInvalidDecl()) return;
13375 
13376   MaybeAddCUDAConstantAttr(var);
13377 
13378   if (getLangOpts().OpenCL) {
13379     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13380     // initialiser
13381     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13382         !var->hasInit()) {
13383       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13384           << 1 /*Init*/;
13385       var->setInvalidDecl();
13386       return;
13387     }
13388   }
13389 
13390   // In Objective-C, don't allow jumps past the implicit initialization of a
13391   // local retaining variable.
13392   if (getLangOpts().ObjC &&
13393       var->hasLocalStorage()) {
13394     switch (var->getType().getObjCLifetime()) {
13395     case Qualifiers::OCL_None:
13396     case Qualifiers::OCL_ExplicitNone:
13397     case Qualifiers::OCL_Autoreleasing:
13398       break;
13399 
13400     case Qualifiers::OCL_Weak:
13401     case Qualifiers::OCL_Strong:
13402       setFunctionHasBranchProtectedScope();
13403       break;
13404     }
13405   }
13406 
13407   if (var->hasLocalStorage() &&
13408       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13409     setFunctionHasBranchProtectedScope();
13410 
13411   // Warn about externally-visible variables being defined without a
13412   // prior declaration.  We only want to do this for global
13413   // declarations, but we also specifically need to avoid doing it for
13414   // class members because the linkage of an anonymous class can
13415   // change if it's later given a typedef name.
13416   if (var->isThisDeclarationADefinition() &&
13417       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13418       var->isExternallyVisible() && var->hasLinkage() &&
13419       !var->isInline() && !var->getDescribedVarTemplate() &&
13420       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13421       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13422       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13423                                   var->getLocation())) {
13424     // Find a previous declaration that's not a definition.
13425     VarDecl *prev = var->getPreviousDecl();
13426     while (prev && prev->isThisDeclarationADefinition())
13427       prev = prev->getPreviousDecl();
13428 
13429     if (!prev) {
13430       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13431       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13432           << /* variable */ 0;
13433     }
13434   }
13435 
13436   // Cache the result of checking for constant initialization.
13437   Optional<bool> CacheHasConstInit;
13438   const Expr *CacheCulprit = nullptr;
13439   auto checkConstInit = [&]() mutable {
13440     if (!CacheHasConstInit)
13441       CacheHasConstInit = var->getInit()->isConstantInitializer(
13442             Context, var->getType()->isReferenceType(), &CacheCulprit);
13443     return *CacheHasConstInit;
13444   };
13445 
13446   if (var->getTLSKind() == VarDecl::TLS_Static) {
13447     if (var->getType().isDestructedType()) {
13448       // GNU C++98 edits for __thread, [basic.start.term]p3:
13449       //   The type of an object with thread storage duration shall not
13450       //   have a non-trivial destructor.
13451       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13452       if (getLangOpts().CPlusPlus11)
13453         Diag(var->getLocation(), diag::note_use_thread_local);
13454     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13455       if (!checkConstInit()) {
13456         // GNU C++98 edits for __thread, [basic.start.init]p4:
13457         //   An object of thread storage duration shall not require dynamic
13458         //   initialization.
13459         // FIXME: Need strict checking here.
13460         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13461           << CacheCulprit->getSourceRange();
13462         if (getLangOpts().CPlusPlus11)
13463           Diag(var->getLocation(), diag::note_use_thread_local);
13464       }
13465     }
13466   }
13467 
13468 
13469   if (!var->getType()->isStructureType() && var->hasInit() &&
13470       isa<InitListExpr>(var->getInit())) {
13471     const auto *ILE = cast<InitListExpr>(var->getInit());
13472     unsigned NumInits = ILE->getNumInits();
13473     if (NumInits > 2)
13474       for (unsigned I = 0; I < NumInits; ++I) {
13475         const auto *Init = ILE->getInit(I);
13476         if (!Init)
13477           break;
13478         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13479         if (!SL)
13480           break;
13481 
13482         unsigned NumConcat = SL->getNumConcatenated();
13483         // Diagnose missing comma in string array initialization.
13484         // Do not warn when all the elements in the initializer are concatenated
13485         // together. Do not warn for macros too.
13486         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13487           bool OnlyOneMissingComma = true;
13488           for (unsigned J = I + 1; J < NumInits; ++J) {
13489             const auto *Init = ILE->getInit(J);
13490             if (!Init)
13491               break;
13492             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13493             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13494               OnlyOneMissingComma = false;
13495               break;
13496             }
13497           }
13498 
13499           if (OnlyOneMissingComma) {
13500             SmallVector<FixItHint, 1> Hints;
13501             for (unsigned i = 0; i < NumConcat - 1; ++i)
13502               Hints.push_back(FixItHint::CreateInsertion(
13503                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13504 
13505             Diag(SL->getStrTokenLoc(1),
13506                  diag::warn_concatenated_literal_array_init)
13507                 << Hints;
13508             Diag(SL->getBeginLoc(),
13509                  diag::note_concatenated_string_literal_silence);
13510           }
13511           // In any case, stop now.
13512           break;
13513         }
13514       }
13515   }
13516 
13517 
13518   QualType type = var->getType();
13519 
13520   if (var->hasAttr<BlocksAttr>())
13521     getCurFunction()->addByrefBlockVar(var);
13522 
13523   Expr *Init = var->getInit();
13524   bool GlobalStorage = var->hasGlobalStorage();
13525   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13526   QualType baseType = Context.getBaseElementType(type);
13527   bool HasConstInit = true;
13528 
13529   // Check whether the initializer is sufficiently constant.
13530   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13531       !Init->isValueDependent() &&
13532       (GlobalStorage || var->isConstexpr() ||
13533        var->mightBeUsableInConstantExpressions(Context))) {
13534     // If this variable might have a constant initializer or might be usable in
13535     // constant expressions, check whether or not it actually is now.  We can't
13536     // do this lazily, because the result might depend on things that change
13537     // later, such as which constexpr functions happen to be defined.
13538     SmallVector<PartialDiagnosticAt, 8> Notes;
13539     if (!getLangOpts().CPlusPlus11) {
13540       // Prior to C++11, in contexts where a constant initializer is required,
13541       // the set of valid constant initializers is described by syntactic rules
13542       // in [expr.const]p2-6.
13543       // FIXME: Stricter checking for these rules would be useful for constinit /
13544       // -Wglobal-constructors.
13545       HasConstInit = checkConstInit();
13546 
13547       // Compute and cache the constant value, and remember that we have a
13548       // constant initializer.
13549       if (HasConstInit) {
13550         (void)var->checkForConstantInitialization(Notes);
13551         Notes.clear();
13552       } else if (CacheCulprit) {
13553         Notes.emplace_back(CacheCulprit->getExprLoc(),
13554                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13555         Notes.back().second << CacheCulprit->getSourceRange();
13556       }
13557     } else {
13558       // Evaluate the initializer to see if it's a constant initializer.
13559       HasConstInit = var->checkForConstantInitialization(Notes);
13560     }
13561 
13562     if (HasConstInit) {
13563       // FIXME: Consider replacing the initializer with a ConstantExpr.
13564     } else if (var->isConstexpr()) {
13565       SourceLocation DiagLoc = var->getLocation();
13566       // If the note doesn't add any useful information other than a source
13567       // location, fold it into the primary diagnostic.
13568       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13569                                    diag::note_invalid_subexpr_in_const_expr) {
13570         DiagLoc = Notes[0].first;
13571         Notes.clear();
13572       }
13573       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13574           << var << Init->getSourceRange();
13575       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13576         Diag(Notes[I].first, Notes[I].second);
13577     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13578       auto *Attr = var->getAttr<ConstInitAttr>();
13579       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13580           << Init->getSourceRange();
13581       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13582           << Attr->getRange() << Attr->isConstinit();
13583       for (auto &it : Notes)
13584         Diag(it.first, it.second);
13585     } else if (IsGlobal &&
13586                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13587                                            var->getLocation())) {
13588       // Warn about globals which don't have a constant initializer.  Don't
13589       // warn about globals with a non-trivial destructor because we already
13590       // warned about them.
13591       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13592       if (!(RD && !RD->hasTrivialDestructor())) {
13593         // checkConstInit() here permits trivial default initialization even in
13594         // C++11 onwards, where such an initializer is not a constant initializer
13595         // but nonetheless doesn't require a global constructor.
13596         if (!checkConstInit())
13597           Diag(var->getLocation(), diag::warn_global_constructor)
13598               << Init->getSourceRange();
13599       }
13600     }
13601   }
13602 
13603   // Apply section attributes and pragmas to global variables.
13604   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13605       !inTemplateInstantiation()) {
13606     PragmaStack<StringLiteral *> *Stack = nullptr;
13607     int SectionFlags = ASTContext::PSF_Read;
13608     if (var->getType().isConstQualified()) {
13609       if (HasConstInit)
13610         Stack = &ConstSegStack;
13611       else {
13612         Stack = &BSSSegStack;
13613         SectionFlags |= ASTContext::PSF_Write;
13614       }
13615     } else if (var->hasInit() && HasConstInit) {
13616       Stack = &DataSegStack;
13617       SectionFlags |= ASTContext::PSF_Write;
13618     } else {
13619       Stack = &BSSSegStack;
13620       SectionFlags |= ASTContext::PSF_Write;
13621     }
13622     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13623       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13624         SectionFlags |= ASTContext::PSF_Implicit;
13625       UnifySection(SA->getName(), SectionFlags, var);
13626     } else if (Stack->CurrentValue) {
13627       SectionFlags |= ASTContext::PSF_Implicit;
13628       auto SectionName = Stack->CurrentValue->getString();
13629       var->addAttr(SectionAttr::CreateImplicit(
13630           Context, SectionName, Stack->CurrentPragmaLocation,
13631           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13632       if (UnifySection(SectionName, SectionFlags, var))
13633         var->dropAttr<SectionAttr>();
13634     }
13635 
13636     // Apply the init_seg attribute if this has an initializer.  If the
13637     // initializer turns out to not be dynamic, we'll end up ignoring this
13638     // attribute.
13639     if (CurInitSeg && var->getInit())
13640       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13641                                                CurInitSegLoc,
13642                                                AttributeCommonInfo::AS_Pragma));
13643   }
13644 
13645   // All the following checks are C++ only.
13646   if (!getLangOpts().CPlusPlus) {
13647     // If this variable must be emitted, add it as an initializer for the
13648     // current module.
13649     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13650       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13651     return;
13652   }
13653 
13654   // Require the destructor.
13655   if (!type->isDependentType())
13656     if (const RecordType *recordType = baseType->getAs<RecordType>())
13657       FinalizeVarWithDestructor(var, recordType);
13658 
13659   // If this variable must be emitted, add it as an initializer for the current
13660   // module.
13661   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13662     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13663 
13664   // Build the bindings if this is a structured binding declaration.
13665   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13666     CheckCompleteDecompositionDeclaration(DD);
13667 }
13668 
13669 /// Check if VD needs to be dllexport/dllimport due to being in a
13670 /// dllexport/import function.
13671 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13672   assert(VD->isStaticLocal());
13673 
13674   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13675 
13676   // Find outermost function when VD is in lambda function.
13677   while (FD && !getDLLAttr(FD) &&
13678          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13679          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13680     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13681   }
13682 
13683   if (!FD)
13684     return;
13685 
13686   // Static locals inherit dll attributes from their function.
13687   if (Attr *A = getDLLAttr(FD)) {
13688     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13689     NewAttr->setInherited(true);
13690     VD->addAttr(NewAttr);
13691   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13692     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13693     NewAttr->setInherited(true);
13694     VD->addAttr(NewAttr);
13695 
13696     // Export this function to enforce exporting this static variable even
13697     // if it is not used in this compilation unit.
13698     if (!FD->hasAttr<DLLExportAttr>())
13699       FD->addAttr(NewAttr);
13700 
13701   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13702     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13703     NewAttr->setInherited(true);
13704     VD->addAttr(NewAttr);
13705   }
13706 }
13707 
13708 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13709 /// any semantic actions necessary after any initializer has been attached.
13710 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13711   // Note that we are no longer parsing the initializer for this declaration.
13712   ParsingInitForAutoVars.erase(ThisDecl);
13713 
13714   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13715   if (!VD)
13716     return;
13717 
13718   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13719   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13720       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13721     if (PragmaClangBSSSection.Valid)
13722       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13723           Context, PragmaClangBSSSection.SectionName,
13724           PragmaClangBSSSection.PragmaLocation,
13725           AttributeCommonInfo::AS_Pragma));
13726     if (PragmaClangDataSection.Valid)
13727       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13728           Context, PragmaClangDataSection.SectionName,
13729           PragmaClangDataSection.PragmaLocation,
13730           AttributeCommonInfo::AS_Pragma));
13731     if (PragmaClangRodataSection.Valid)
13732       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13733           Context, PragmaClangRodataSection.SectionName,
13734           PragmaClangRodataSection.PragmaLocation,
13735           AttributeCommonInfo::AS_Pragma));
13736     if (PragmaClangRelroSection.Valid)
13737       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13738           Context, PragmaClangRelroSection.SectionName,
13739           PragmaClangRelroSection.PragmaLocation,
13740           AttributeCommonInfo::AS_Pragma));
13741   }
13742 
13743   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13744     for (auto *BD : DD->bindings()) {
13745       FinalizeDeclaration(BD);
13746     }
13747   }
13748 
13749   checkAttributesAfterMerging(*this, *VD);
13750 
13751   // Perform TLS alignment check here after attributes attached to the variable
13752   // which may affect the alignment have been processed. Only perform the check
13753   // if the target has a maximum TLS alignment (zero means no constraints).
13754   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13755     // Protect the check so that it's not performed on dependent types and
13756     // dependent alignments (we can't determine the alignment in that case).
13757     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13758       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13759       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13760         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13761           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13762           << (unsigned)MaxAlignChars.getQuantity();
13763       }
13764     }
13765   }
13766 
13767   if (VD->isStaticLocal())
13768     CheckStaticLocalForDllExport(VD);
13769 
13770   // Perform check for initializers of device-side global variables.
13771   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13772   // 7.5). We must also apply the same checks to all __shared__
13773   // variables whether they are local or not. CUDA also allows
13774   // constant initializers for __constant__ and __device__ variables.
13775   if (getLangOpts().CUDA)
13776     checkAllowedCUDAInitializer(VD);
13777 
13778   // Grab the dllimport or dllexport attribute off of the VarDecl.
13779   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13780 
13781   // Imported static data members cannot be defined out-of-line.
13782   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13783     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13784         VD->isThisDeclarationADefinition()) {
13785       // We allow definitions of dllimport class template static data members
13786       // with a warning.
13787       CXXRecordDecl *Context =
13788         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13789       bool IsClassTemplateMember =
13790           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13791           Context->getDescribedClassTemplate();
13792 
13793       Diag(VD->getLocation(),
13794            IsClassTemplateMember
13795                ? diag::warn_attribute_dllimport_static_field_definition
13796                : diag::err_attribute_dllimport_static_field_definition);
13797       Diag(IA->getLocation(), diag::note_attribute);
13798       if (!IsClassTemplateMember)
13799         VD->setInvalidDecl();
13800     }
13801   }
13802 
13803   // dllimport/dllexport variables cannot be thread local, their TLS index
13804   // isn't exported with the variable.
13805   if (DLLAttr && VD->getTLSKind()) {
13806     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13807     if (F && getDLLAttr(F)) {
13808       assert(VD->isStaticLocal());
13809       // But if this is a static local in a dlimport/dllexport function, the
13810       // function will never be inlined, which means the var would never be
13811       // imported, so having it marked import/export is safe.
13812     } else {
13813       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13814                                                                     << DLLAttr;
13815       VD->setInvalidDecl();
13816     }
13817   }
13818 
13819   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13820     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13821       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13822           << Attr;
13823       VD->dropAttr<UsedAttr>();
13824     }
13825   }
13826   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13827     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13828       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13829           << Attr;
13830       VD->dropAttr<RetainAttr>();
13831     }
13832   }
13833 
13834   const DeclContext *DC = VD->getDeclContext();
13835   // If there's a #pragma GCC visibility in scope, and this isn't a class
13836   // member, set the visibility of this variable.
13837   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13838     AddPushedVisibilityAttribute(VD);
13839 
13840   // FIXME: Warn on unused var template partial specializations.
13841   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13842     MarkUnusedFileScopedDecl(VD);
13843 
13844   // Now we have parsed the initializer and can update the table of magic
13845   // tag values.
13846   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13847       !VD->getType()->isIntegralOrEnumerationType())
13848     return;
13849 
13850   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13851     const Expr *MagicValueExpr = VD->getInit();
13852     if (!MagicValueExpr) {
13853       continue;
13854     }
13855     Optional<llvm::APSInt> MagicValueInt;
13856     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13857       Diag(I->getRange().getBegin(),
13858            diag::err_type_tag_for_datatype_not_ice)
13859         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13860       continue;
13861     }
13862     if (MagicValueInt->getActiveBits() > 64) {
13863       Diag(I->getRange().getBegin(),
13864            diag::err_type_tag_for_datatype_too_large)
13865         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13866       continue;
13867     }
13868     uint64_t MagicValue = MagicValueInt->getZExtValue();
13869     RegisterTypeTagForDatatype(I->getArgumentKind(),
13870                                MagicValue,
13871                                I->getMatchingCType(),
13872                                I->getLayoutCompatible(),
13873                                I->getMustBeNull());
13874   }
13875 }
13876 
13877 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13878   auto *VD = dyn_cast<VarDecl>(DD);
13879   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13880 }
13881 
13882 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13883                                                    ArrayRef<Decl *> Group) {
13884   SmallVector<Decl*, 8> Decls;
13885 
13886   if (DS.isTypeSpecOwned())
13887     Decls.push_back(DS.getRepAsDecl());
13888 
13889   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13890   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13891   bool DiagnosedMultipleDecomps = false;
13892   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13893   bool DiagnosedNonDeducedAuto = false;
13894 
13895   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13896     if (Decl *D = Group[i]) {
13897       // For declarators, there are some additional syntactic-ish checks we need
13898       // to perform.
13899       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13900         if (!FirstDeclaratorInGroup)
13901           FirstDeclaratorInGroup = DD;
13902         if (!FirstDecompDeclaratorInGroup)
13903           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13904         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13905             !hasDeducedAuto(DD))
13906           FirstNonDeducedAutoInGroup = DD;
13907 
13908         if (FirstDeclaratorInGroup != DD) {
13909           // A decomposition declaration cannot be combined with any other
13910           // declaration in the same group.
13911           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13912             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13913                  diag::err_decomp_decl_not_alone)
13914                 << FirstDeclaratorInGroup->getSourceRange()
13915                 << DD->getSourceRange();
13916             DiagnosedMultipleDecomps = true;
13917           }
13918 
13919           // A declarator that uses 'auto' in any way other than to declare a
13920           // variable with a deduced type cannot be combined with any other
13921           // declarator in the same group.
13922           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13923             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13924                  diag::err_auto_non_deduced_not_alone)
13925                 << FirstNonDeducedAutoInGroup->getType()
13926                        ->hasAutoForTrailingReturnType()
13927                 << FirstDeclaratorInGroup->getSourceRange()
13928                 << DD->getSourceRange();
13929             DiagnosedNonDeducedAuto = true;
13930           }
13931         }
13932       }
13933 
13934       Decls.push_back(D);
13935     }
13936   }
13937 
13938   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13939     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13940       handleTagNumbering(Tag, S);
13941       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13942           getLangOpts().CPlusPlus)
13943         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13944     }
13945   }
13946 
13947   return BuildDeclaratorGroup(Decls);
13948 }
13949 
13950 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13951 /// group, performing any necessary semantic checking.
13952 Sema::DeclGroupPtrTy
13953 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13954   // C++14 [dcl.spec.auto]p7: (DR1347)
13955   //   If the type that replaces the placeholder type is not the same in each
13956   //   deduction, the program is ill-formed.
13957   if (Group.size() > 1) {
13958     QualType Deduced;
13959     VarDecl *DeducedDecl = nullptr;
13960     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13961       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13962       if (!D || D->isInvalidDecl())
13963         break;
13964       DeducedType *DT = D->getType()->getContainedDeducedType();
13965       if (!DT || DT->getDeducedType().isNull())
13966         continue;
13967       if (Deduced.isNull()) {
13968         Deduced = DT->getDeducedType();
13969         DeducedDecl = D;
13970       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13971         auto *AT = dyn_cast<AutoType>(DT);
13972         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13973                         diag::err_auto_different_deductions)
13974                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13975                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13976                    << D->getDeclName();
13977         if (DeducedDecl->hasInit())
13978           Dia << DeducedDecl->getInit()->getSourceRange();
13979         if (D->getInit())
13980           Dia << D->getInit()->getSourceRange();
13981         D->setInvalidDecl();
13982         break;
13983       }
13984     }
13985   }
13986 
13987   ActOnDocumentableDecls(Group);
13988 
13989   return DeclGroupPtrTy::make(
13990       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13991 }
13992 
13993 void Sema::ActOnDocumentableDecl(Decl *D) {
13994   ActOnDocumentableDecls(D);
13995 }
13996 
13997 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13998   // Don't parse the comment if Doxygen diagnostics are ignored.
13999   if (Group.empty() || !Group[0])
14000     return;
14001 
14002   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14003                       Group[0]->getLocation()) &&
14004       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14005                       Group[0]->getLocation()))
14006     return;
14007 
14008   if (Group.size() >= 2) {
14009     // This is a decl group.  Normally it will contain only declarations
14010     // produced from declarator list.  But in case we have any definitions or
14011     // additional declaration references:
14012     //   'typedef struct S {} S;'
14013     //   'typedef struct S *S;'
14014     //   'struct S *pS;'
14015     // FinalizeDeclaratorGroup adds these as separate declarations.
14016     Decl *MaybeTagDecl = Group[0];
14017     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14018       Group = Group.slice(1);
14019     }
14020   }
14021 
14022   // FIMXE: We assume every Decl in the group is in the same file.
14023   // This is false when preprocessor constructs the group from decls in
14024   // different files (e. g. macros or #include).
14025   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14026 }
14027 
14028 /// Common checks for a parameter-declaration that should apply to both function
14029 /// parameters and non-type template parameters.
14030 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14031   // Check that there are no default arguments inside the type of this
14032   // parameter.
14033   if (getLangOpts().CPlusPlus)
14034     CheckExtraCXXDefaultArguments(D);
14035 
14036   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14037   if (D.getCXXScopeSpec().isSet()) {
14038     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14039       << D.getCXXScopeSpec().getRange();
14040   }
14041 
14042   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14043   // simple identifier except [...irrelevant cases...].
14044   switch (D.getName().getKind()) {
14045   case UnqualifiedIdKind::IK_Identifier:
14046     break;
14047 
14048   case UnqualifiedIdKind::IK_OperatorFunctionId:
14049   case UnqualifiedIdKind::IK_ConversionFunctionId:
14050   case UnqualifiedIdKind::IK_LiteralOperatorId:
14051   case UnqualifiedIdKind::IK_ConstructorName:
14052   case UnqualifiedIdKind::IK_DestructorName:
14053   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14054   case UnqualifiedIdKind::IK_DeductionGuideName:
14055     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14056       << GetNameForDeclarator(D).getName();
14057     break;
14058 
14059   case UnqualifiedIdKind::IK_TemplateId:
14060   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14061     // GetNameForDeclarator would not produce a useful name in this case.
14062     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14063     break;
14064   }
14065 }
14066 
14067 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14068 /// to introduce parameters into function prototype scope.
14069 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14070   const DeclSpec &DS = D.getDeclSpec();
14071 
14072   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14073 
14074   // C++03 [dcl.stc]p2 also permits 'auto'.
14075   StorageClass SC = SC_None;
14076   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14077     SC = SC_Register;
14078     // In C++11, the 'register' storage class specifier is deprecated.
14079     // In C++17, it is not allowed, but we tolerate it as an extension.
14080     if (getLangOpts().CPlusPlus11) {
14081       Diag(DS.getStorageClassSpecLoc(),
14082            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14083                                      : diag::warn_deprecated_register)
14084         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14085     }
14086   } else if (getLangOpts().CPlusPlus &&
14087              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14088     SC = SC_Auto;
14089   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14090     Diag(DS.getStorageClassSpecLoc(),
14091          diag::err_invalid_storage_class_in_func_decl);
14092     D.getMutableDeclSpec().ClearStorageClassSpecs();
14093   }
14094 
14095   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14096     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14097       << DeclSpec::getSpecifierName(TSCS);
14098   if (DS.isInlineSpecified())
14099     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14100         << getLangOpts().CPlusPlus17;
14101   if (DS.hasConstexprSpecifier())
14102     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14103         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14104 
14105   DiagnoseFunctionSpecifiers(DS);
14106 
14107   CheckFunctionOrTemplateParamDeclarator(S, D);
14108 
14109   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14110   QualType parmDeclType = TInfo->getType();
14111 
14112   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14113   IdentifierInfo *II = D.getIdentifier();
14114   if (II) {
14115     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14116                    ForVisibleRedeclaration);
14117     LookupName(R, S);
14118     if (R.isSingleResult()) {
14119       NamedDecl *PrevDecl = R.getFoundDecl();
14120       if (PrevDecl->isTemplateParameter()) {
14121         // Maybe we will complain about the shadowed template parameter.
14122         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14123         // Just pretend that we didn't see the previous declaration.
14124         PrevDecl = nullptr;
14125       } else if (S->isDeclScope(PrevDecl)) {
14126         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14127         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14128 
14129         // Recover by removing the name
14130         II = nullptr;
14131         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14132         D.setInvalidType(true);
14133       }
14134     }
14135   }
14136 
14137   // Temporarily put parameter variables in the translation unit, not
14138   // the enclosing context.  This prevents them from accidentally
14139   // looking like class members in C++.
14140   ParmVarDecl *New =
14141       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14142                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14143 
14144   if (D.isInvalidType())
14145     New->setInvalidDecl();
14146 
14147   assert(S->isFunctionPrototypeScope());
14148   assert(S->getFunctionPrototypeDepth() >= 1);
14149   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14150                     S->getNextFunctionPrototypeIndex());
14151 
14152   // Add the parameter declaration into this scope.
14153   S->AddDecl(New);
14154   if (II)
14155     IdResolver.AddDecl(New);
14156 
14157   ProcessDeclAttributes(S, New, D);
14158 
14159   if (D.getDeclSpec().isModulePrivateSpecified())
14160     Diag(New->getLocation(), diag::err_module_private_local)
14161         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14162         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14163 
14164   if (New->hasAttr<BlocksAttr>()) {
14165     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14166   }
14167 
14168   if (getLangOpts().OpenCL)
14169     deduceOpenCLAddressSpace(New);
14170 
14171   return New;
14172 }
14173 
14174 /// Synthesizes a variable for a parameter arising from a
14175 /// typedef.
14176 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14177                                               SourceLocation Loc,
14178                                               QualType T) {
14179   /* FIXME: setting StartLoc == Loc.
14180      Would it be worth to modify callers so as to provide proper source
14181      location for the unnamed parameters, embedding the parameter's type? */
14182   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14183                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14184                                            SC_None, nullptr);
14185   Param->setImplicit();
14186   return Param;
14187 }
14188 
14189 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14190   // Don't diagnose unused-parameter errors in template instantiations; we
14191   // will already have done so in the template itself.
14192   if (inTemplateInstantiation())
14193     return;
14194 
14195   for (const ParmVarDecl *Parameter : Parameters) {
14196     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14197         !Parameter->hasAttr<UnusedAttr>()) {
14198       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14199         << Parameter->getDeclName();
14200     }
14201   }
14202 }
14203 
14204 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14205     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14206   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14207     return;
14208 
14209   // Warn if the return value is pass-by-value and larger than the specified
14210   // threshold.
14211   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14212     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14213     if (Size > LangOpts.NumLargeByValueCopy)
14214       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14215   }
14216 
14217   // Warn if any parameter is pass-by-value and larger than the specified
14218   // threshold.
14219   for (const ParmVarDecl *Parameter : Parameters) {
14220     QualType T = Parameter->getType();
14221     if (T->isDependentType() || !T.isPODType(Context))
14222       continue;
14223     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14224     if (Size > LangOpts.NumLargeByValueCopy)
14225       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14226           << Parameter << Size;
14227   }
14228 }
14229 
14230 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14231                                   SourceLocation NameLoc, IdentifierInfo *Name,
14232                                   QualType T, TypeSourceInfo *TSInfo,
14233                                   StorageClass SC) {
14234   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14235   if (getLangOpts().ObjCAutoRefCount &&
14236       T.getObjCLifetime() == Qualifiers::OCL_None &&
14237       T->isObjCLifetimeType()) {
14238 
14239     Qualifiers::ObjCLifetime lifetime;
14240 
14241     // Special cases for arrays:
14242     //   - if it's const, use __unsafe_unretained
14243     //   - otherwise, it's an error
14244     if (T->isArrayType()) {
14245       if (!T.isConstQualified()) {
14246         if (DelayedDiagnostics.shouldDelayDiagnostics())
14247           DelayedDiagnostics.add(
14248               sema::DelayedDiagnostic::makeForbiddenType(
14249               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14250         else
14251           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14252               << TSInfo->getTypeLoc().getSourceRange();
14253       }
14254       lifetime = Qualifiers::OCL_ExplicitNone;
14255     } else {
14256       lifetime = T->getObjCARCImplicitLifetime();
14257     }
14258     T = Context.getLifetimeQualifiedType(T, lifetime);
14259   }
14260 
14261   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14262                                          Context.getAdjustedParameterType(T),
14263                                          TSInfo, SC, nullptr);
14264 
14265   // Make a note if we created a new pack in the scope of a lambda, so that
14266   // we know that references to that pack must also be expanded within the
14267   // lambda scope.
14268   if (New->isParameterPack())
14269     if (auto *LSI = getEnclosingLambda())
14270       LSI->LocalPacks.push_back(New);
14271 
14272   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14273       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14274     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14275                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14276 
14277   // Parameters can not be abstract class types.
14278   // For record types, this is done by the AbstractClassUsageDiagnoser once
14279   // the class has been completely parsed.
14280   if (!CurContext->isRecord() &&
14281       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14282                              AbstractParamType))
14283     New->setInvalidDecl();
14284 
14285   // Parameter declarators cannot be interface types. All ObjC objects are
14286   // passed by reference.
14287   if (T->isObjCObjectType()) {
14288     SourceLocation TypeEndLoc =
14289         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14290     Diag(NameLoc,
14291          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14292       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14293     T = Context.getObjCObjectPointerType(T);
14294     New->setType(T);
14295   }
14296 
14297   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14298   // duration shall not be qualified by an address-space qualifier."
14299   // Since all parameters have automatic store duration, they can not have
14300   // an address space.
14301   if (T.getAddressSpace() != LangAS::Default &&
14302       // OpenCL allows function arguments declared to be an array of a type
14303       // to be qualified with an address space.
14304       !(getLangOpts().OpenCL &&
14305         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14306     Diag(NameLoc, diag::err_arg_with_address_space);
14307     New->setInvalidDecl();
14308   }
14309 
14310   // PPC MMA non-pointer types are not allowed as function argument types.
14311   if (Context.getTargetInfo().getTriple().isPPC64() &&
14312       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14313     New->setInvalidDecl();
14314   }
14315 
14316   return New;
14317 }
14318 
14319 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14320                                            SourceLocation LocAfterDecls) {
14321   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14322 
14323   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14324   // in the declaration list shall have at least one declarator, those
14325   // declarators shall only declare identifiers from the identifier list, and
14326   // every identifier in the identifier list shall be declared.
14327   //
14328   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14329   // identifiers it names shall be declared in the declaration list."
14330   //
14331   // This is why we only diagnose in C99 and later. Note, the other conditions
14332   // listed are checked elsewhere.
14333   if (!FTI.hasPrototype) {
14334     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14335       --i;
14336       if (FTI.Params[i].Param == nullptr) {
14337         if (getLangOpts().C99) {
14338           SmallString<256> Code;
14339           llvm::raw_svector_ostream(Code)
14340               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14341           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14342               << FTI.Params[i].Ident
14343               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14344         }
14345 
14346         // Implicitly declare the argument as type 'int' for lack of a better
14347         // type.
14348         AttributeFactory attrs;
14349         DeclSpec DS(attrs);
14350         const char* PrevSpec; // unused
14351         unsigned DiagID; // unused
14352         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14353                            DiagID, Context.getPrintingPolicy());
14354         // Use the identifier location for the type source range.
14355         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14356         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14357         Declarator ParamD(DS, ParsedAttributesView::none(),
14358                           DeclaratorContext::KNRTypeList);
14359         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14360         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14361       }
14362     }
14363   }
14364 }
14365 
14366 Decl *
14367 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14368                               MultiTemplateParamsArg TemplateParameterLists,
14369                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14370   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14371   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14372   Scope *ParentScope = FnBodyScope->getParent();
14373 
14374   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14375   // we define a non-templated function definition, we will create a declaration
14376   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14377   // The base function declaration will have the equivalent of an `omp declare
14378   // variant` annotation which specifies the mangled definition as a
14379   // specialization function under the OpenMP context defined as part of the
14380   // `omp begin declare variant`.
14381   SmallVector<FunctionDecl *, 4> Bases;
14382   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14383     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14384         ParentScope, D, TemplateParameterLists, Bases);
14385 
14386   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14387   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14388   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14389 
14390   if (!Bases.empty())
14391     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14392 
14393   return Dcl;
14394 }
14395 
14396 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14397   Consumer.HandleInlineFunctionDefinition(D);
14398 }
14399 
14400 static bool
14401 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14402                                 const FunctionDecl *&PossiblePrototype) {
14403   // Don't warn about invalid declarations.
14404   if (FD->isInvalidDecl())
14405     return false;
14406 
14407   // Or declarations that aren't global.
14408   if (!FD->isGlobal())
14409     return false;
14410 
14411   // Don't warn about C++ member functions.
14412   if (isa<CXXMethodDecl>(FD))
14413     return false;
14414 
14415   // Don't warn about 'main'.
14416   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14417     if (IdentifierInfo *II = FD->getIdentifier())
14418       if (II->isStr("main") || II->isStr("efi_main"))
14419         return false;
14420 
14421   // Don't warn about inline functions.
14422   if (FD->isInlined())
14423     return false;
14424 
14425   // Don't warn about function templates.
14426   if (FD->getDescribedFunctionTemplate())
14427     return false;
14428 
14429   // Don't warn about function template specializations.
14430   if (FD->isFunctionTemplateSpecialization())
14431     return false;
14432 
14433   // Don't warn for OpenCL kernels.
14434   if (FD->hasAttr<OpenCLKernelAttr>())
14435     return false;
14436 
14437   // Don't warn on explicitly deleted functions.
14438   if (FD->isDeleted())
14439     return false;
14440 
14441   // Don't warn on implicitly local functions (such as having local-typed
14442   // parameters).
14443   if (!FD->isExternallyVisible())
14444     return false;
14445 
14446   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14447        Prev; Prev = Prev->getPreviousDecl()) {
14448     // Ignore any declarations that occur in function or method
14449     // scope, because they aren't visible from the header.
14450     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14451       continue;
14452 
14453     PossiblePrototype = Prev;
14454     return Prev->getType()->isFunctionNoProtoType();
14455   }
14456 
14457   return true;
14458 }
14459 
14460 void
14461 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14462                                    const FunctionDecl *EffectiveDefinition,
14463                                    SkipBodyInfo *SkipBody) {
14464   const FunctionDecl *Definition = EffectiveDefinition;
14465   if (!Definition &&
14466       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14467     return;
14468 
14469   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14470     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14471       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14472         // A merged copy of the same function, instantiated as a member of
14473         // the same class, is OK.
14474         if (declaresSameEntity(OrigFD, OrigDef) &&
14475             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14476                                cast<Decl>(FD->getLexicalDeclContext())))
14477           return;
14478       }
14479     }
14480   }
14481 
14482   if (canRedefineFunction(Definition, getLangOpts()))
14483     return;
14484 
14485   // Don't emit an error when this is redefinition of a typo-corrected
14486   // definition.
14487   if (TypoCorrectedFunctionDefinitions.count(Definition))
14488     return;
14489 
14490   // If we don't have a visible definition of the function, and it's inline or
14491   // a template, skip the new definition.
14492   if (SkipBody && !hasVisibleDefinition(Definition) &&
14493       (Definition->getFormalLinkage() == InternalLinkage ||
14494        Definition->isInlined() ||
14495        Definition->getDescribedFunctionTemplate() ||
14496        Definition->getNumTemplateParameterLists())) {
14497     SkipBody->ShouldSkip = true;
14498     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14499     if (auto *TD = Definition->getDescribedFunctionTemplate())
14500       makeMergedDefinitionVisible(TD);
14501     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14502     return;
14503   }
14504 
14505   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14506       Definition->getStorageClass() == SC_Extern)
14507     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14508         << FD << getLangOpts().CPlusPlus;
14509   else
14510     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14511 
14512   Diag(Definition->getLocation(), diag::note_previous_definition);
14513   FD->setInvalidDecl();
14514 }
14515 
14516 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14517                                    Sema &S) {
14518   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14519 
14520   LambdaScopeInfo *LSI = S.PushLambdaScope();
14521   LSI->CallOperator = CallOperator;
14522   LSI->Lambda = LambdaClass;
14523   LSI->ReturnType = CallOperator->getReturnType();
14524   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14525 
14526   if (LCD == LCD_None)
14527     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14528   else if (LCD == LCD_ByCopy)
14529     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14530   else if (LCD == LCD_ByRef)
14531     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14532   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14533 
14534   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14535   LSI->Mutable = !CallOperator->isConst();
14536 
14537   // Add the captures to the LSI so they can be noted as already
14538   // captured within tryCaptureVar.
14539   auto I = LambdaClass->field_begin();
14540   for (const auto &C : LambdaClass->captures()) {
14541     if (C.capturesVariable()) {
14542       VarDecl *VD = C.getCapturedVar();
14543       if (VD->isInitCapture())
14544         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14545       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14546       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14547           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14548           /*EllipsisLoc*/C.isPackExpansion()
14549                          ? C.getEllipsisLoc() : SourceLocation(),
14550           I->getType(), /*Invalid*/false);
14551 
14552     } else if (C.capturesThis()) {
14553       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14554                           C.getCaptureKind() == LCK_StarThis);
14555     } else {
14556       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14557                              I->getType());
14558     }
14559     ++I;
14560   }
14561 }
14562 
14563 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14564                                     SkipBodyInfo *SkipBody,
14565                                     FnBodyKind BodyKind) {
14566   if (!D) {
14567     // Parsing the function declaration failed in some way. Push on a fake scope
14568     // anyway so we can try to parse the function body.
14569     PushFunctionScope();
14570     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14571     return D;
14572   }
14573 
14574   FunctionDecl *FD = nullptr;
14575 
14576   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14577     FD = FunTmpl->getTemplatedDecl();
14578   else
14579     FD = cast<FunctionDecl>(D);
14580 
14581   // Do not push if it is a lambda because one is already pushed when building
14582   // the lambda in ActOnStartOfLambdaDefinition().
14583   if (!isLambdaCallOperator(FD))
14584     PushExpressionEvaluationContext(
14585         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14586                           : ExprEvalContexts.back().Context);
14587 
14588   // Check for defining attributes before the check for redefinition.
14589   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14590     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14591     FD->dropAttr<AliasAttr>();
14592     FD->setInvalidDecl();
14593   }
14594   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14595     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14596     FD->dropAttr<IFuncAttr>();
14597     FD->setInvalidDecl();
14598   }
14599 
14600   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14601     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14602         Ctor->isDefaultConstructor() &&
14603         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14604       // If this is an MS ABI dllexport default constructor, instantiate any
14605       // default arguments.
14606       InstantiateDefaultCtorDefaultArgs(Ctor);
14607     }
14608   }
14609 
14610   // See if this is a redefinition. If 'will have body' (or similar) is already
14611   // set, then these checks were already performed when it was set.
14612   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14613       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14614     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14615 
14616     // If we're skipping the body, we're done. Don't enter the scope.
14617     if (SkipBody && SkipBody->ShouldSkip)
14618       return D;
14619   }
14620 
14621   // Mark this function as "will have a body eventually".  This lets users to
14622   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14623   // this function.
14624   FD->setWillHaveBody();
14625 
14626   // If we are instantiating a generic lambda call operator, push
14627   // a LambdaScopeInfo onto the function stack.  But use the information
14628   // that's already been calculated (ActOnLambdaExpr) to prime the current
14629   // LambdaScopeInfo.
14630   // When the template operator is being specialized, the LambdaScopeInfo,
14631   // has to be properly restored so that tryCaptureVariable doesn't try
14632   // and capture any new variables. In addition when calculating potential
14633   // captures during transformation of nested lambdas, it is necessary to
14634   // have the LSI properly restored.
14635   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14636     assert(inTemplateInstantiation() &&
14637            "There should be an active template instantiation on the stack "
14638            "when instantiating a generic lambda!");
14639     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14640   } else {
14641     // Enter a new function scope
14642     PushFunctionScope();
14643   }
14644 
14645   // Builtin functions cannot be defined.
14646   if (unsigned BuiltinID = FD->getBuiltinID()) {
14647     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14648         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14649       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14650       FD->setInvalidDecl();
14651     }
14652   }
14653 
14654   // The return type of a function definition must be complete (C99 6.9.1p3),
14655   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14656   QualType ResultType = FD->getReturnType();
14657   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14658       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14659       RequireCompleteType(FD->getLocation(), ResultType,
14660                           diag::err_func_def_incomplete_result))
14661     FD->setInvalidDecl();
14662 
14663   if (FnBodyScope)
14664     PushDeclContext(FnBodyScope, FD);
14665 
14666   // Check the validity of our function parameters
14667   if (BodyKind != FnBodyKind::Delete)
14668     CheckParmsForFunctionDef(FD->parameters(),
14669                              /*CheckParameterNames=*/true);
14670 
14671   // Add non-parameter declarations already in the function to the current
14672   // scope.
14673   if (FnBodyScope) {
14674     for (Decl *NPD : FD->decls()) {
14675       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14676       if (!NonParmDecl)
14677         continue;
14678       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14679              "parameters should not be in newly created FD yet");
14680 
14681       // If the decl has a name, make it accessible in the current scope.
14682       if (NonParmDecl->getDeclName())
14683         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14684 
14685       // Similarly, dive into enums and fish their constants out, making them
14686       // accessible in this scope.
14687       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14688         for (auto *EI : ED->enumerators())
14689           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14690       }
14691     }
14692   }
14693 
14694   // Introduce our parameters into the function scope
14695   for (auto Param : FD->parameters()) {
14696     Param->setOwningFunction(FD);
14697 
14698     // If this has an identifier, add it to the scope stack.
14699     if (Param->getIdentifier() && FnBodyScope) {
14700       CheckShadow(FnBodyScope, Param);
14701 
14702       PushOnScopeChains(Param, FnBodyScope);
14703     }
14704   }
14705 
14706   // Ensure that the function's exception specification is instantiated.
14707   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14708     ResolveExceptionSpec(D->getLocation(), FPT);
14709 
14710   // dllimport cannot be applied to non-inline function definitions.
14711   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14712       !FD->isTemplateInstantiation()) {
14713     assert(!FD->hasAttr<DLLExportAttr>());
14714     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14715     FD->setInvalidDecl();
14716     return D;
14717   }
14718   // We want to attach documentation to original Decl (which might be
14719   // a function template).
14720   ActOnDocumentableDecl(D);
14721   if (getCurLexicalContext()->isObjCContainer() &&
14722       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14723       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14724     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14725 
14726   return D;
14727 }
14728 
14729 /// Given the set of return statements within a function body,
14730 /// compute the variables that are subject to the named return value
14731 /// optimization.
14732 ///
14733 /// Each of the variables that is subject to the named return value
14734 /// optimization will be marked as NRVO variables in the AST, and any
14735 /// return statement that has a marked NRVO variable as its NRVO candidate can
14736 /// use the named return value optimization.
14737 ///
14738 /// This function applies a very simplistic algorithm for NRVO: if every return
14739 /// statement in the scope of a variable has the same NRVO candidate, that
14740 /// candidate is an NRVO variable.
14741 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14742   ReturnStmt **Returns = Scope->Returns.data();
14743 
14744   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14745     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14746       if (!NRVOCandidate->isNRVOVariable())
14747         Returns[I]->setNRVOCandidate(nullptr);
14748     }
14749   }
14750 }
14751 
14752 bool Sema::canDelayFunctionBody(const Declarator &D) {
14753   // We can't delay parsing the body of a constexpr function template (yet).
14754   if (D.getDeclSpec().hasConstexprSpecifier())
14755     return false;
14756 
14757   // We can't delay parsing the body of a function template with a deduced
14758   // return type (yet).
14759   if (D.getDeclSpec().hasAutoTypeSpec()) {
14760     // If the placeholder introduces a non-deduced trailing return type,
14761     // we can still delay parsing it.
14762     if (D.getNumTypeObjects()) {
14763       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14764       if (Outer.Kind == DeclaratorChunk::Function &&
14765           Outer.Fun.hasTrailingReturnType()) {
14766         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14767         return Ty.isNull() || !Ty->isUndeducedType();
14768       }
14769     }
14770     return false;
14771   }
14772 
14773   return true;
14774 }
14775 
14776 bool Sema::canSkipFunctionBody(Decl *D) {
14777   // We cannot skip the body of a function (or function template) which is
14778   // constexpr, since we may need to evaluate its body in order to parse the
14779   // rest of the file.
14780   // We cannot skip the body of a function with an undeduced return type,
14781   // because any callers of that function need to know the type.
14782   if (const FunctionDecl *FD = D->getAsFunction()) {
14783     if (FD->isConstexpr())
14784       return false;
14785     // We can't simply call Type::isUndeducedType here, because inside template
14786     // auto can be deduced to a dependent type, which is not considered
14787     // "undeduced".
14788     if (FD->getReturnType()->getContainedDeducedType())
14789       return false;
14790   }
14791   return Consumer.shouldSkipFunctionBody(D);
14792 }
14793 
14794 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14795   if (!Decl)
14796     return nullptr;
14797   if (FunctionDecl *FD = Decl->getAsFunction())
14798     FD->setHasSkippedBody();
14799   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14800     MD->setHasSkippedBody();
14801   return Decl;
14802 }
14803 
14804 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14805   return ActOnFinishFunctionBody(D, BodyArg, false);
14806 }
14807 
14808 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14809 /// body.
14810 class ExitFunctionBodyRAII {
14811 public:
14812   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14813   ~ExitFunctionBodyRAII() {
14814     if (!IsLambda)
14815       S.PopExpressionEvaluationContext();
14816   }
14817 
14818 private:
14819   Sema &S;
14820   bool IsLambda = false;
14821 };
14822 
14823 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14824   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14825 
14826   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14827     if (EscapeInfo.count(BD))
14828       return EscapeInfo[BD];
14829 
14830     bool R = false;
14831     const BlockDecl *CurBD = BD;
14832 
14833     do {
14834       R = !CurBD->doesNotEscape();
14835       if (R)
14836         break;
14837       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14838     } while (CurBD);
14839 
14840     return EscapeInfo[BD] = R;
14841   };
14842 
14843   // If the location where 'self' is implicitly retained is inside a escaping
14844   // block, emit a diagnostic.
14845   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14846        S.ImplicitlyRetainedSelfLocs)
14847     if (IsOrNestedInEscapingBlock(P.second))
14848       S.Diag(P.first, diag::warn_implicitly_retains_self)
14849           << FixItHint::CreateInsertion(P.first, "self->");
14850 }
14851 
14852 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14853                                     bool IsInstantiation) {
14854   FunctionScopeInfo *FSI = getCurFunction();
14855   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14856 
14857   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14858     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14859 
14860   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14861   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14862 
14863   if (getLangOpts().Coroutines && FSI->isCoroutine())
14864     CheckCompletedCoroutineBody(FD, Body);
14865 
14866   {
14867     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14868     // one is already popped when finishing the lambda in BuildLambdaExpr().
14869     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14870     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14871 
14872     if (FD) {
14873       FD->setBody(Body);
14874       FD->setWillHaveBody(false);
14875 
14876       if (getLangOpts().CPlusPlus14) {
14877         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14878             FD->getReturnType()->isUndeducedType()) {
14879           // For a function with a deduced result type to return void,
14880           // the result type as written must be 'auto' or 'decltype(auto)',
14881           // possibly cv-qualified or constrained, but not ref-qualified.
14882           if (!FD->getReturnType()->getAs<AutoType>()) {
14883             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14884                 << FD->getReturnType();
14885             FD->setInvalidDecl();
14886           } else {
14887             // Falling off the end of the function is the same as 'return;'.
14888             Expr *Dummy = nullptr;
14889             if (DeduceFunctionTypeFromReturnExpr(
14890                     FD, dcl->getLocation(), Dummy,
14891                     FD->getReturnType()->getAs<AutoType>()))
14892               FD->setInvalidDecl();
14893           }
14894         }
14895       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14896         // In C++11, we don't use 'auto' deduction rules for lambda call
14897         // operators because we don't support return type deduction.
14898         auto *LSI = getCurLambda();
14899         if (LSI->HasImplicitReturnType) {
14900           deduceClosureReturnType(*LSI);
14901 
14902           // C++11 [expr.prim.lambda]p4:
14903           //   [...] if there are no return statements in the compound-statement
14904           //   [the deduced type is] the type void
14905           QualType RetType =
14906               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14907 
14908           // Update the return type to the deduced type.
14909           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14910           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14911                                               Proto->getExtProtoInfo()));
14912         }
14913       }
14914 
14915       // If the function implicitly returns zero (like 'main') or is naked,
14916       // don't complain about missing return statements.
14917       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14918         WP.disableCheckFallThrough();
14919 
14920       // MSVC permits the use of pure specifier (=0) on function definition,
14921       // defined at class scope, warn about this non-standard construct.
14922       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14923         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14924 
14925       if (!FD->isInvalidDecl()) {
14926         // Don't diagnose unused parameters of defaulted, deleted or naked
14927         // functions.
14928         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14929             !FD->hasAttr<NakedAttr>())
14930           DiagnoseUnusedParameters(FD->parameters());
14931         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14932                                                FD->getReturnType(), FD);
14933 
14934         // If this is a structor, we need a vtable.
14935         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14936           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14937         else if (CXXDestructorDecl *Destructor =
14938                      dyn_cast<CXXDestructorDecl>(FD))
14939           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14940 
14941         // Try to apply the named return value optimization. We have to check
14942         // if we can do this here because lambdas keep return statements around
14943         // to deduce an implicit return type.
14944         if (FD->getReturnType()->isRecordType() &&
14945             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14946           computeNRVO(Body, FSI);
14947       }
14948 
14949       // GNU warning -Wmissing-prototypes:
14950       //   Warn if a global function is defined without a previous
14951       //   prototype declaration. This warning is issued even if the
14952       //   definition itself provides a prototype. The aim is to detect
14953       //   global functions that fail to be declared in header files.
14954       const FunctionDecl *PossiblePrototype = nullptr;
14955       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14956         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14957 
14958         if (PossiblePrototype) {
14959           // We found a declaration that is not a prototype,
14960           // but that could be a zero-parameter prototype
14961           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14962             TypeLoc TL = TI->getTypeLoc();
14963             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14964               Diag(PossiblePrototype->getLocation(),
14965                    diag::note_declaration_not_a_prototype)
14966                   << (FD->getNumParams() != 0)
14967                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14968                                                     FTL.getRParenLoc(), "void")
14969                                               : FixItHint{});
14970           }
14971         } else {
14972           // Returns true if the token beginning at this Loc is `const`.
14973           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14974                                   const LangOptions &LangOpts) {
14975             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14976             if (LocInfo.first.isInvalid())
14977               return false;
14978 
14979             bool Invalid = false;
14980             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14981             if (Invalid)
14982               return false;
14983 
14984             if (LocInfo.second > Buffer.size())
14985               return false;
14986 
14987             const char *LexStart = Buffer.data() + LocInfo.second;
14988             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14989 
14990             return StartTok.consume_front("const") &&
14991                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14992                     StartTok.startswith("/*") || StartTok.startswith("//"));
14993           };
14994 
14995           auto findBeginLoc = [&]() {
14996             // If the return type has `const` qualifier, we want to insert
14997             // `static` before `const` (and not before the typename).
14998             if ((FD->getReturnType()->isAnyPointerType() &&
14999                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15000                 FD->getReturnType().isConstQualified()) {
15001               // But only do this if we can determine where the `const` is.
15002 
15003               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15004                                getLangOpts()))
15005 
15006                 return FD->getBeginLoc();
15007             }
15008             return FD->getTypeSpecStartLoc();
15009           };
15010           Diag(FD->getTypeSpecStartLoc(),
15011                diag::note_static_for_internal_linkage)
15012               << /* function */ 1
15013               << (FD->getStorageClass() == SC_None
15014                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15015                       : FixItHint{});
15016         }
15017       }
15018 
15019       // If the function being defined does not have a prototype, then we may
15020       // need to diagnose it as changing behavior in C2x because we now know
15021       // whether the function accepts arguments or not. This only handles the
15022       // case where the definition has no prototype but does have parameters
15023       // and either there is no previous potential prototype, or the previous
15024       // potential prototype also has no actual prototype. This handles cases
15025       // like:
15026       //   void f(); void f(a) int a; {}
15027       //   void g(a) int a; {}
15028       // See MergeFunctionDecl() for other cases of the behavior change
15029       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15030       // type without a prototype.
15031       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15032           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15033                                   !PossiblePrototype->isImplicit()))) {
15034         // The function definition has parameters, so this will change behavior
15035         // in C2x. If there is a possible prototype, it comes before the
15036         // function definition.
15037         // FIXME: The declaration may have already been diagnosed as being
15038         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15039         // there's no way to test for the "changes behavior" condition in
15040         // SemaType.cpp when forming the declaration's function type. So, we do
15041         // this awkward dance instead.
15042         //
15043         // If we have a possible prototype and it declares a function with a
15044         // prototype, we don't want to diagnose it; if we have a possible
15045         // prototype and it has no prototype, it may have already been
15046         // diagnosed in SemaType.cpp as deprecated depending on whether
15047         // -Wstrict-prototypes is enabled. If we already warned about it being
15048         // deprecated, add a note that it also changes behavior. If we didn't
15049         // warn about it being deprecated (because the diagnostic is not
15050         // enabled), warn now that it is deprecated and changes behavior.
15051 
15052         // This K&R C function definition definitely changes behavior in C2x,
15053         // so diagnose it.
15054         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15055             << /*definition*/ 1 << /* not supported in C2x */ 0;
15056 
15057         // If we have a possible prototype for the function which is a user-
15058         // visible declaration, we already tested that it has no prototype.
15059         // This will change behavior in C2x. This gets a warning rather than a
15060         // note because it's the same behavior-changing problem as with the
15061         // definition.
15062         if (PossiblePrototype)
15063           Diag(PossiblePrototype->getLocation(),
15064                diag::warn_non_prototype_changes_behavior)
15065               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15066               << /*definition*/ 1;
15067       }
15068 
15069       // Warn on CPUDispatch with an actual body.
15070       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15071         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15072           if (!CmpndBody->body_empty())
15073             Diag(CmpndBody->body_front()->getBeginLoc(),
15074                  diag::warn_dispatch_body_ignored);
15075 
15076       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15077         const CXXMethodDecl *KeyFunction;
15078         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15079             MD->isVirtual() &&
15080             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15081             MD == KeyFunction->getCanonicalDecl()) {
15082           // Update the key-function state if necessary for this ABI.
15083           if (FD->isInlined() &&
15084               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15085             Context.setNonKeyFunction(MD);
15086 
15087             // If the newly-chosen key function is already defined, then we
15088             // need to mark the vtable as used retroactively.
15089             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15090             const FunctionDecl *Definition;
15091             if (KeyFunction && KeyFunction->isDefined(Definition))
15092               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15093           } else {
15094             // We just defined they key function; mark the vtable as used.
15095             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15096           }
15097         }
15098       }
15099 
15100       assert(
15101           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15102           "Function parsing confused");
15103     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15104       assert(MD == getCurMethodDecl() && "Method parsing confused");
15105       MD->setBody(Body);
15106       if (!MD->isInvalidDecl()) {
15107         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15108                                                MD->getReturnType(), MD);
15109 
15110         if (Body)
15111           computeNRVO(Body, FSI);
15112       }
15113       if (FSI->ObjCShouldCallSuper) {
15114         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15115             << MD->getSelector().getAsString();
15116         FSI->ObjCShouldCallSuper = false;
15117       }
15118       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15119         const ObjCMethodDecl *InitMethod = nullptr;
15120         bool isDesignated =
15121             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15122         assert(isDesignated && InitMethod);
15123         (void)isDesignated;
15124 
15125         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15126           auto IFace = MD->getClassInterface();
15127           if (!IFace)
15128             return false;
15129           auto SuperD = IFace->getSuperClass();
15130           if (!SuperD)
15131             return false;
15132           return SuperD->getIdentifier() ==
15133                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15134         };
15135         // Don't issue this warning for unavailable inits or direct subclasses
15136         // of NSObject.
15137         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15138           Diag(MD->getLocation(),
15139                diag::warn_objc_designated_init_missing_super_call);
15140           Diag(InitMethod->getLocation(),
15141                diag::note_objc_designated_init_marked_here);
15142         }
15143         FSI->ObjCWarnForNoDesignatedInitChain = false;
15144       }
15145       if (FSI->ObjCWarnForNoInitDelegation) {
15146         // Don't issue this warning for unavaialable inits.
15147         if (!MD->isUnavailable())
15148           Diag(MD->getLocation(),
15149                diag::warn_objc_secondary_init_missing_init_call);
15150         FSI->ObjCWarnForNoInitDelegation = false;
15151       }
15152 
15153       diagnoseImplicitlyRetainedSelf(*this);
15154     } else {
15155       // Parsing the function declaration failed in some way. Pop the fake scope
15156       // we pushed on.
15157       PopFunctionScopeInfo(ActivePolicy, dcl);
15158       return nullptr;
15159     }
15160 
15161     if (Body && FSI->HasPotentialAvailabilityViolations)
15162       DiagnoseUnguardedAvailabilityViolations(dcl);
15163 
15164     assert(!FSI->ObjCShouldCallSuper &&
15165            "This should only be set for ObjC methods, which should have been "
15166            "handled in the block above.");
15167 
15168     // Verify and clean out per-function state.
15169     if (Body && (!FD || !FD->isDefaulted())) {
15170       // C++ constructors that have function-try-blocks can't have return
15171       // statements in the handlers of that block. (C++ [except.handle]p14)
15172       // Verify this.
15173       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15174         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15175 
15176       // Verify that gotos and switch cases don't jump into scopes illegally.
15177       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15178         DiagnoseInvalidJumps(Body);
15179 
15180       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15181         if (!Destructor->getParent()->isDependentType())
15182           CheckDestructor(Destructor);
15183 
15184         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15185                                                Destructor->getParent());
15186       }
15187 
15188       // If any errors have occurred, clear out any temporaries that may have
15189       // been leftover. This ensures that these temporaries won't be picked up
15190       // for deletion in some later function.
15191       if (hasUncompilableErrorOccurred() ||
15192           getDiagnostics().getSuppressAllDiagnostics()) {
15193         DiscardCleanupsInEvaluationContext();
15194       }
15195       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15196         // Since the body is valid, issue any analysis-based warnings that are
15197         // enabled.
15198         ActivePolicy = &WP;
15199       }
15200 
15201       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15202           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15203         FD->setInvalidDecl();
15204 
15205       if (FD && FD->hasAttr<NakedAttr>()) {
15206         for (const Stmt *S : Body->children()) {
15207           // Allow local register variables without initializer as they don't
15208           // require prologue.
15209           bool RegisterVariables = false;
15210           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15211             for (const auto *Decl : DS->decls()) {
15212               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15213                 RegisterVariables =
15214                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15215                 if (!RegisterVariables)
15216                   break;
15217               }
15218             }
15219           }
15220           if (RegisterVariables)
15221             continue;
15222           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15223             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15224             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15225             FD->setInvalidDecl();
15226             break;
15227           }
15228         }
15229       }
15230 
15231       assert(ExprCleanupObjects.size() ==
15232                  ExprEvalContexts.back().NumCleanupObjects &&
15233              "Leftover temporaries in function");
15234       assert(!Cleanup.exprNeedsCleanups() &&
15235              "Unaccounted cleanups in function");
15236       assert(MaybeODRUseExprs.empty() &&
15237              "Leftover expressions for odr-use checking");
15238     }
15239   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15240     // the declaration context below. Otherwise, we're unable to transform
15241     // 'this' expressions when transforming immediate context functions.
15242 
15243   if (!IsInstantiation)
15244     PopDeclContext();
15245 
15246   PopFunctionScopeInfo(ActivePolicy, dcl);
15247   // If any errors have occurred, clear out any temporaries that may have
15248   // been leftover. This ensures that these temporaries won't be picked up for
15249   // deletion in some later function.
15250   if (hasUncompilableErrorOccurred()) {
15251     DiscardCleanupsInEvaluationContext();
15252   }
15253 
15254   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15255                                   !LangOpts.OMPTargetTriples.empty())) ||
15256              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15257     auto ES = getEmissionStatus(FD);
15258     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15259         ES == Sema::FunctionEmissionStatus::Unknown)
15260       DeclsToCheckForDeferredDiags.insert(FD);
15261   }
15262 
15263   if (FD && !FD->isDeleted())
15264     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15265 
15266   return dcl;
15267 }
15268 
15269 /// When we finish delayed parsing of an attribute, we must attach it to the
15270 /// relevant Decl.
15271 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15272                                        ParsedAttributes &Attrs) {
15273   // Always attach attributes to the underlying decl.
15274   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15275     D = TD->getTemplatedDecl();
15276   ProcessDeclAttributeList(S, D, Attrs);
15277 
15278   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15279     if (Method->isStatic())
15280       checkThisInStaticMemberFunctionAttributes(Method);
15281 }
15282 
15283 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15284 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15285 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15286                                           IdentifierInfo &II, Scope *S) {
15287   // It is not valid to implicitly define a function in C2x.
15288   assert(LangOpts.implicitFunctionsAllowed() &&
15289          "Implicit function declarations aren't allowed in this language mode");
15290 
15291   // Find the scope in which the identifier is injected and the corresponding
15292   // DeclContext.
15293   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15294   // In that case, we inject the declaration into the translation unit scope
15295   // instead.
15296   Scope *BlockScope = S;
15297   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15298     BlockScope = BlockScope->getParent();
15299 
15300   Scope *ContextScope = BlockScope;
15301   while (!ContextScope->getEntity())
15302     ContextScope = ContextScope->getParent();
15303   ContextRAII SavedContext(*this, ContextScope->getEntity());
15304 
15305   // Before we produce a declaration for an implicitly defined
15306   // function, see whether there was a locally-scoped declaration of
15307   // this name as a function or variable. If so, use that
15308   // (non-visible) declaration, and complain about it.
15309   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15310   if (ExternCPrev) {
15311     // We still need to inject the function into the enclosing block scope so
15312     // that later (non-call) uses can see it.
15313     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15314 
15315     // C89 footnote 38:
15316     //   If in fact it is not defined as having type "function returning int",
15317     //   the behavior is undefined.
15318     if (!isa<FunctionDecl>(ExternCPrev) ||
15319         !Context.typesAreCompatible(
15320             cast<FunctionDecl>(ExternCPrev)->getType(),
15321             Context.getFunctionNoProtoType(Context.IntTy))) {
15322       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15323           << ExternCPrev << !getLangOpts().C99;
15324       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15325       return ExternCPrev;
15326     }
15327   }
15328 
15329   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15330   unsigned diag_id;
15331   if (II.getName().startswith("__builtin_"))
15332     diag_id = diag::warn_builtin_unknown;
15333   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15334   else if (getLangOpts().C99)
15335     diag_id = diag::ext_implicit_function_decl_c99;
15336   else
15337     diag_id = diag::warn_implicit_function_decl;
15338 
15339   TypoCorrection Corrected;
15340   // Because typo correction is expensive, only do it if the implicit
15341   // function declaration is going to be treated as an error.
15342   //
15343   // Perform the corection before issuing the main diagnostic, as some consumers
15344   // use typo-correction callbacks to enhance the main diagnostic.
15345   if (S && !ExternCPrev &&
15346       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15347     DeclFilterCCC<FunctionDecl> CCC{};
15348     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15349                             S, nullptr, CCC, CTK_NonError);
15350   }
15351 
15352   Diag(Loc, diag_id) << &II;
15353   if (Corrected) {
15354     // If the correction is going to suggest an implicitly defined function,
15355     // skip the correction as not being a particularly good idea.
15356     bool Diagnose = true;
15357     if (const auto *D = Corrected.getCorrectionDecl())
15358       Diagnose = !D->isImplicit();
15359     if (Diagnose)
15360       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15361                    /*ErrorRecovery*/ false);
15362   }
15363 
15364   // If we found a prior declaration of this function, don't bother building
15365   // another one. We've already pushed that one into scope, so there's nothing
15366   // more to do.
15367   if (ExternCPrev)
15368     return ExternCPrev;
15369 
15370   // Set a Declarator for the implicit definition: int foo();
15371   const char *Dummy;
15372   AttributeFactory attrFactory;
15373   DeclSpec DS(attrFactory);
15374   unsigned DiagID;
15375   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15376                                   Context.getPrintingPolicy());
15377   (void)Error; // Silence warning.
15378   assert(!Error && "Error setting up implicit decl!");
15379   SourceLocation NoLoc;
15380   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15381   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15382                                              /*IsAmbiguous=*/false,
15383                                              /*LParenLoc=*/NoLoc,
15384                                              /*Params=*/nullptr,
15385                                              /*NumParams=*/0,
15386                                              /*EllipsisLoc=*/NoLoc,
15387                                              /*RParenLoc=*/NoLoc,
15388                                              /*RefQualifierIsLvalueRef=*/true,
15389                                              /*RefQualifierLoc=*/NoLoc,
15390                                              /*MutableLoc=*/NoLoc, EST_None,
15391                                              /*ESpecRange=*/SourceRange(),
15392                                              /*Exceptions=*/nullptr,
15393                                              /*ExceptionRanges=*/nullptr,
15394                                              /*NumExceptions=*/0,
15395                                              /*NoexceptExpr=*/nullptr,
15396                                              /*ExceptionSpecTokens=*/nullptr,
15397                                              /*DeclsInPrototype=*/None, Loc,
15398                                              Loc, D),
15399                 std::move(DS.getAttributes()), SourceLocation());
15400   D.SetIdentifier(&II, Loc);
15401 
15402   // Insert this function into the enclosing block scope.
15403   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15404   FD->setImplicit();
15405 
15406   AddKnownFunctionAttributes(FD);
15407 
15408   return FD;
15409 }
15410 
15411 /// If this function is a C++ replaceable global allocation function
15412 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15413 /// adds any function attributes that we know a priori based on the standard.
15414 ///
15415 /// We need to check for duplicate attributes both here and where user-written
15416 /// attributes are applied to declarations.
15417 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15418     FunctionDecl *FD) {
15419   if (FD->isInvalidDecl())
15420     return;
15421 
15422   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15423       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15424     return;
15425 
15426   Optional<unsigned> AlignmentParam;
15427   bool IsNothrow = false;
15428   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15429     return;
15430 
15431   // C++2a [basic.stc.dynamic.allocation]p4:
15432   //   An allocation function that has a non-throwing exception specification
15433   //   indicates failure by returning a null pointer value. Any other allocation
15434   //   function never returns a null pointer value and indicates failure only by
15435   //   throwing an exception [...]
15436   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15437     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15438 
15439   // C++2a [basic.stc.dynamic.allocation]p2:
15440   //   An allocation function attempts to allocate the requested amount of
15441   //   storage. [...] If the request succeeds, the value returned by a
15442   //   replaceable allocation function is a [...] pointer value p0 different
15443   //   from any previously returned value p1 [...]
15444   //
15445   // However, this particular information is being added in codegen,
15446   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15447 
15448   // C++2a [basic.stc.dynamic.allocation]p2:
15449   //   An allocation function attempts to allocate the requested amount of
15450   //   storage. If it is successful, it returns the address of the start of a
15451   //   block of storage whose length in bytes is at least as large as the
15452   //   requested size.
15453   if (!FD->hasAttr<AllocSizeAttr>()) {
15454     FD->addAttr(AllocSizeAttr::CreateImplicit(
15455         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15456         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15457   }
15458 
15459   // C++2a [basic.stc.dynamic.allocation]p3:
15460   //   For an allocation function [...], the pointer returned on a successful
15461   //   call shall represent the address of storage that is aligned as follows:
15462   //   (3.1) If the allocation function takes an argument of type
15463   //         std​::​align_­val_­t, the storage will have the alignment
15464   //         specified by the value of this argument.
15465   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15466     FD->addAttr(AllocAlignAttr::CreateImplicit(
15467         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15468   }
15469 
15470   // FIXME:
15471   // C++2a [basic.stc.dynamic.allocation]p3:
15472   //   For an allocation function [...], the pointer returned on a successful
15473   //   call shall represent the address of storage that is aligned as follows:
15474   //   (3.2) Otherwise, if the allocation function is named operator new[],
15475   //         the storage is aligned for any object that does not have
15476   //         new-extended alignment ([basic.align]) and is no larger than the
15477   //         requested size.
15478   //   (3.3) Otherwise, the storage is aligned for any object that does not
15479   //         have new-extended alignment and is of the requested size.
15480 }
15481 
15482 /// Adds any function attributes that we know a priori based on
15483 /// the declaration of this function.
15484 ///
15485 /// These attributes can apply both to implicitly-declared builtins
15486 /// (like __builtin___printf_chk) or to library-declared functions
15487 /// like NSLog or printf.
15488 ///
15489 /// We need to check for duplicate attributes both here and where user-written
15490 /// attributes are applied to declarations.
15491 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15492   if (FD->isInvalidDecl())
15493     return;
15494 
15495   // If this is a built-in function, map its builtin attributes to
15496   // actual attributes.
15497   if (unsigned BuiltinID = FD->getBuiltinID()) {
15498     // Handle printf-formatting attributes.
15499     unsigned FormatIdx;
15500     bool HasVAListArg;
15501     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15502       if (!FD->hasAttr<FormatAttr>()) {
15503         const char *fmt = "printf";
15504         unsigned int NumParams = FD->getNumParams();
15505         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15506             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15507           fmt = "NSString";
15508         FD->addAttr(FormatAttr::CreateImplicit(Context,
15509                                                &Context.Idents.get(fmt),
15510                                                FormatIdx+1,
15511                                                HasVAListArg ? 0 : FormatIdx+2,
15512                                                FD->getLocation()));
15513       }
15514     }
15515     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15516                                              HasVAListArg)) {
15517      if (!FD->hasAttr<FormatAttr>())
15518        FD->addAttr(FormatAttr::CreateImplicit(Context,
15519                                               &Context.Idents.get("scanf"),
15520                                               FormatIdx+1,
15521                                               HasVAListArg ? 0 : FormatIdx+2,
15522                                               FD->getLocation()));
15523     }
15524 
15525     // Handle automatically recognized callbacks.
15526     SmallVector<int, 4> Encoding;
15527     if (!FD->hasAttr<CallbackAttr>() &&
15528         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15529       FD->addAttr(CallbackAttr::CreateImplicit(
15530           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15531 
15532     // Mark const if we don't care about errno and that is the only thing
15533     // preventing the function from being const. This allows IRgen to use LLVM
15534     // intrinsics for such functions.
15535     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15536         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15537       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15538 
15539     // We make "fma" on GNU or Windows const because we know it does not set
15540     // errno in those environments even though it could set errno based on the
15541     // C standard.
15542     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15543     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15544         !FD->hasAttr<ConstAttr>()) {
15545       switch (BuiltinID) {
15546       case Builtin::BI__builtin_fma:
15547       case Builtin::BI__builtin_fmaf:
15548       case Builtin::BI__builtin_fmal:
15549       case Builtin::BIfma:
15550       case Builtin::BIfmaf:
15551       case Builtin::BIfmal:
15552         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15553         break;
15554       default:
15555         break;
15556       }
15557     }
15558 
15559     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15560         !FD->hasAttr<ReturnsTwiceAttr>())
15561       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15562                                          FD->getLocation()));
15563     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15564       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15565     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15566       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15567     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15568       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15569     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15570         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15571       // Add the appropriate attribute, depending on the CUDA compilation mode
15572       // and which target the builtin belongs to. For example, during host
15573       // compilation, aux builtins are __device__, while the rest are __host__.
15574       if (getLangOpts().CUDAIsDevice !=
15575           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15576         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15577       else
15578         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15579     }
15580 
15581     // Add known guaranteed alignment for allocation functions.
15582     switch (BuiltinID) {
15583     case Builtin::BImemalign:
15584     case Builtin::BIaligned_alloc:
15585       if (!FD->hasAttr<AllocAlignAttr>())
15586         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15587                                                    FD->getLocation()));
15588       break;
15589     default:
15590       break;
15591     }
15592 
15593     // Add allocsize attribute for allocation functions.
15594     switch (BuiltinID) {
15595     case Builtin::BIcalloc:
15596       FD->addAttr(AllocSizeAttr::CreateImplicit(
15597           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15598       break;
15599     case Builtin::BImemalign:
15600     case Builtin::BIaligned_alloc:
15601     case Builtin::BIrealloc:
15602       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15603                                                 ParamIdx(), FD->getLocation()));
15604       break;
15605     case Builtin::BImalloc:
15606       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15607                                                 ParamIdx(), FD->getLocation()));
15608       break;
15609     default:
15610       break;
15611     }
15612   }
15613 
15614   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15615 
15616   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15617   // throw, add an implicit nothrow attribute to any extern "C" function we come
15618   // across.
15619   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15620       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15621     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15622     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15623       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15624   }
15625 
15626   IdentifierInfo *Name = FD->getIdentifier();
15627   if (!Name)
15628     return;
15629   if ((!getLangOpts().CPlusPlus &&
15630        FD->getDeclContext()->isTranslationUnit()) ||
15631       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15632        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15633        LinkageSpecDecl::lang_c)) {
15634     // Okay: this could be a libc/libm/Objective-C function we know
15635     // about.
15636   } else
15637     return;
15638 
15639   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15640     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15641     // target-specific builtins, perhaps?
15642     if (!FD->hasAttr<FormatAttr>())
15643       FD->addAttr(FormatAttr::CreateImplicit(Context,
15644                                              &Context.Idents.get("printf"), 2,
15645                                              Name->isStr("vasprintf") ? 0 : 3,
15646                                              FD->getLocation()));
15647   }
15648 
15649   if (Name->isStr("__CFStringMakeConstantString")) {
15650     // We already have a __builtin___CFStringMakeConstantString,
15651     // but builds that use -fno-constant-cfstrings don't go through that.
15652     if (!FD->hasAttr<FormatArgAttr>())
15653       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15654                                                 FD->getLocation()));
15655   }
15656 }
15657 
15658 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15659                                     TypeSourceInfo *TInfo) {
15660   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15661   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15662 
15663   if (!TInfo) {
15664     assert(D.isInvalidType() && "no declarator info for valid type");
15665     TInfo = Context.getTrivialTypeSourceInfo(T);
15666   }
15667 
15668   // Scope manipulation handled by caller.
15669   TypedefDecl *NewTD =
15670       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15671                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15672 
15673   // Bail out immediately if we have an invalid declaration.
15674   if (D.isInvalidType()) {
15675     NewTD->setInvalidDecl();
15676     return NewTD;
15677   }
15678 
15679   if (D.getDeclSpec().isModulePrivateSpecified()) {
15680     if (CurContext->isFunctionOrMethod())
15681       Diag(NewTD->getLocation(), diag::err_module_private_local)
15682           << 2 << NewTD
15683           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15684           << FixItHint::CreateRemoval(
15685                  D.getDeclSpec().getModulePrivateSpecLoc());
15686     else
15687       NewTD->setModulePrivate();
15688   }
15689 
15690   // C++ [dcl.typedef]p8:
15691   //   If the typedef declaration defines an unnamed class (or
15692   //   enum), the first typedef-name declared by the declaration
15693   //   to be that class type (or enum type) is used to denote the
15694   //   class type (or enum type) for linkage purposes only.
15695   // We need to check whether the type was declared in the declaration.
15696   switch (D.getDeclSpec().getTypeSpecType()) {
15697   case TST_enum:
15698   case TST_struct:
15699   case TST_interface:
15700   case TST_union:
15701   case TST_class: {
15702     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15703     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15704     break;
15705   }
15706 
15707   default:
15708     break;
15709   }
15710 
15711   return NewTD;
15712 }
15713 
15714 /// Check that this is a valid underlying type for an enum declaration.
15715 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15716   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15717   QualType T = TI->getType();
15718 
15719   if (T->isDependentType())
15720     return false;
15721 
15722   // This doesn't use 'isIntegralType' despite the error message mentioning
15723   // integral type because isIntegralType would also allow enum types in C.
15724   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15725     if (BT->isInteger())
15726       return false;
15727 
15728   if (T->isBitIntType())
15729     return false;
15730 
15731   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15732 }
15733 
15734 /// Check whether this is a valid redeclaration of a previous enumeration.
15735 /// \return true if the redeclaration was invalid.
15736 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15737                                   QualType EnumUnderlyingTy, bool IsFixed,
15738                                   const EnumDecl *Prev) {
15739   if (IsScoped != Prev->isScoped()) {
15740     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15741       << Prev->isScoped();
15742     Diag(Prev->getLocation(), diag::note_previous_declaration);
15743     return true;
15744   }
15745 
15746   if (IsFixed && Prev->isFixed()) {
15747     if (!EnumUnderlyingTy->isDependentType() &&
15748         !Prev->getIntegerType()->isDependentType() &&
15749         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15750                                         Prev->getIntegerType())) {
15751       // TODO: Highlight the underlying type of the redeclaration.
15752       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15753         << EnumUnderlyingTy << Prev->getIntegerType();
15754       Diag(Prev->getLocation(), diag::note_previous_declaration)
15755           << Prev->getIntegerTypeRange();
15756       return true;
15757     }
15758   } else if (IsFixed != Prev->isFixed()) {
15759     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15760       << Prev->isFixed();
15761     Diag(Prev->getLocation(), diag::note_previous_declaration);
15762     return true;
15763   }
15764 
15765   return false;
15766 }
15767 
15768 /// Get diagnostic %select index for tag kind for
15769 /// redeclaration diagnostic message.
15770 /// WARNING: Indexes apply to particular diagnostics only!
15771 ///
15772 /// \returns diagnostic %select index.
15773 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15774   switch (Tag) {
15775   case TTK_Struct: return 0;
15776   case TTK_Interface: return 1;
15777   case TTK_Class:  return 2;
15778   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15779   }
15780 }
15781 
15782 /// Determine if tag kind is a class-key compatible with
15783 /// class for redeclaration (class, struct, or __interface).
15784 ///
15785 /// \returns true iff the tag kind is compatible.
15786 static bool isClassCompatTagKind(TagTypeKind Tag)
15787 {
15788   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15789 }
15790 
15791 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15792                                              TagTypeKind TTK) {
15793   if (isa<TypedefDecl>(PrevDecl))
15794     return NTK_Typedef;
15795   else if (isa<TypeAliasDecl>(PrevDecl))
15796     return NTK_TypeAlias;
15797   else if (isa<ClassTemplateDecl>(PrevDecl))
15798     return NTK_Template;
15799   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15800     return NTK_TypeAliasTemplate;
15801   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15802     return NTK_TemplateTemplateArgument;
15803   switch (TTK) {
15804   case TTK_Struct:
15805   case TTK_Interface:
15806   case TTK_Class:
15807     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15808   case TTK_Union:
15809     return NTK_NonUnion;
15810   case TTK_Enum:
15811     return NTK_NonEnum;
15812   }
15813   llvm_unreachable("invalid TTK");
15814 }
15815 
15816 /// Determine whether a tag with a given kind is acceptable
15817 /// as a redeclaration of the given tag declaration.
15818 ///
15819 /// \returns true if the new tag kind is acceptable, false otherwise.
15820 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15821                                         TagTypeKind NewTag, bool isDefinition,
15822                                         SourceLocation NewTagLoc,
15823                                         const IdentifierInfo *Name) {
15824   // C++ [dcl.type.elab]p3:
15825   //   The class-key or enum keyword present in the
15826   //   elaborated-type-specifier shall agree in kind with the
15827   //   declaration to which the name in the elaborated-type-specifier
15828   //   refers. This rule also applies to the form of
15829   //   elaborated-type-specifier that declares a class-name or
15830   //   friend class since it can be construed as referring to the
15831   //   definition of the class. Thus, in any
15832   //   elaborated-type-specifier, the enum keyword shall be used to
15833   //   refer to an enumeration (7.2), the union class-key shall be
15834   //   used to refer to a union (clause 9), and either the class or
15835   //   struct class-key shall be used to refer to a class (clause 9)
15836   //   declared using the class or struct class-key.
15837   TagTypeKind OldTag = Previous->getTagKind();
15838   if (OldTag != NewTag &&
15839       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15840     return false;
15841 
15842   // Tags are compatible, but we might still want to warn on mismatched tags.
15843   // Non-class tags can't be mismatched at this point.
15844   if (!isClassCompatTagKind(NewTag))
15845     return true;
15846 
15847   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15848   // by our warning analysis. We don't want to warn about mismatches with (eg)
15849   // declarations in system headers that are designed to be specialized, but if
15850   // a user asks us to warn, we should warn if their code contains mismatched
15851   // declarations.
15852   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15853     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15854                                       Loc);
15855   };
15856   if (IsIgnoredLoc(NewTagLoc))
15857     return true;
15858 
15859   auto IsIgnored = [&](const TagDecl *Tag) {
15860     return IsIgnoredLoc(Tag->getLocation());
15861   };
15862   while (IsIgnored(Previous)) {
15863     Previous = Previous->getPreviousDecl();
15864     if (!Previous)
15865       return true;
15866     OldTag = Previous->getTagKind();
15867   }
15868 
15869   bool isTemplate = false;
15870   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15871     isTemplate = Record->getDescribedClassTemplate();
15872 
15873   if (inTemplateInstantiation()) {
15874     if (OldTag != NewTag) {
15875       // In a template instantiation, do not offer fix-its for tag mismatches
15876       // since they usually mess up the template instead of fixing the problem.
15877       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15878         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15879         << getRedeclDiagFromTagKind(OldTag);
15880       // FIXME: Note previous location?
15881     }
15882     return true;
15883   }
15884 
15885   if (isDefinition) {
15886     // On definitions, check all previous tags and issue a fix-it for each
15887     // one that doesn't match the current tag.
15888     if (Previous->getDefinition()) {
15889       // Don't suggest fix-its for redefinitions.
15890       return true;
15891     }
15892 
15893     bool previousMismatch = false;
15894     for (const TagDecl *I : Previous->redecls()) {
15895       if (I->getTagKind() != NewTag) {
15896         // Ignore previous declarations for which the warning was disabled.
15897         if (IsIgnored(I))
15898           continue;
15899 
15900         if (!previousMismatch) {
15901           previousMismatch = true;
15902           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15903             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15904             << getRedeclDiagFromTagKind(I->getTagKind());
15905         }
15906         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15907           << getRedeclDiagFromTagKind(NewTag)
15908           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15909                TypeWithKeyword::getTagTypeKindName(NewTag));
15910       }
15911     }
15912     return true;
15913   }
15914 
15915   // Identify the prevailing tag kind: this is the kind of the definition (if
15916   // there is a non-ignored definition), or otherwise the kind of the prior
15917   // (non-ignored) declaration.
15918   const TagDecl *PrevDef = Previous->getDefinition();
15919   if (PrevDef && IsIgnored(PrevDef))
15920     PrevDef = nullptr;
15921   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15922   if (Redecl->getTagKind() != NewTag) {
15923     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15924       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15925       << getRedeclDiagFromTagKind(OldTag);
15926     Diag(Redecl->getLocation(), diag::note_previous_use);
15927 
15928     // If there is a previous definition, suggest a fix-it.
15929     if (PrevDef) {
15930       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15931         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15932         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15933              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15934     }
15935   }
15936 
15937   return true;
15938 }
15939 
15940 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15941 /// from an outer enclosing namespace or file scope inside a friend declaration.
15942 /// This should provide the commented out code in the following snippet:
15943 ///   namespace N {
15944 ///     struct X;
15945 ///     namespace M {
15946 ///       struct Y { friend struct /*N::*/ X; };
15947 ///     }
15948 ///   }
15949 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15950                                          SourceLocation NameLoc) {
15951   // While the decl is in a namespace, do repeated lookup of that name and see
15952   // if we get the same namespace back.  If we do not, continue until
15953   // translation unit scope, at which point we have a fully qualified NNS.
15954   SmallVector<IdentifierInfo *, 4> Namespaces;
15955   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15956   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15957     // This tag should be declared in a namespace, which can only be enclosed by
15958     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15959     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15960     if (!Namespace || Namespace->isAnonymousNamespace())
15961       return FixItHint();
15962     IdentifierInfo *II = Namespace->getIdentifier();
15963     Namespaces.push_back(II);
15964     NamedDecl *Lookup = SemaRef.LookupSingleName(
15965         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15966     if (Lookup == Namespace)
15967       break;
15968   }
15969 
15970   // Once we have all the namespaces, reverse them to go outermost first, and
15971   // build an NNS.
15972   SmallString<64> Insertion;
15973   llvm::raw_svector_ostream OS(Insertion);
15974   if (DC->isTranslationUnit())
15975     OS << "::";
15976   std::reverse(Namespaces.begin(), Namespaces.end());
15977   for (auto *II : Namespaces)
15978     OS << II->getName() << "::";
15979   return FixItHint::CreateInsertion(NameLoc, Insertion);
15980 }
15981 
15982 /// Determine whether a tag originally declared in context \p OldDC can
15983 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15984 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15985 /// using-declaration).
15986 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15987                                          DeclContext *NewDC) {
15988   OldDC = OldDC->getRedeclContext();
15989   NewDC = NewDC->getRedeclContext();
15990 
15991   if (OldDC->Equals(NewDC))
15992     return true;
15993 
15994   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15995   // encloses the other).
15996   if (S.getLangOpts().MSVCCompat &&
15997       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15998     return true;
15999 
16000   return false;
16001 }
16002 
16003 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16004 /// former case, Name will be non-null.  In the later case, Name will be null.
16005 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16006 /// reference/declaration/definition of a tag.
16007 ///
16008 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16009 /// trailing-type-specifier) other than one in an alias-declaration.
16010 ///
16011 /// \param SkipBody If non-null, will be set to indicate if the caller should
16012 /// skip the definition of this tag and treat it as if it were a declaration.
16013 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16014                      SourceLocation KWLoc, CXXScopeSpec &SS,
16015                      IdentifierInfo *Name, SourceLocation NameLoc,
16016                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16017                      SourceLocation ModulePrivateLoc,
16018                      MultiTemplateParamsArg TemplateParameterLists,
16019                      bool &OwnedDecl, bool &IsDependent,
16020                      SourceLocation ScopedEnumKWLoc,
16021                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16022                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16023                      SkipBodyInfo *SkipBody) {
16024   // If this is not a definition, it must have a name.
16025   IdentifierInfo *OrigName = Name;
16026   assert((Name != nullptr || TUK == TUK_Definition) &&
16027          "Nameless record must be a definition!");
16028   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16029 
16030   OwnedDecl = false;
16031   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16032   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16033 
16034   // FIXME: Check member specializations more carefully.
16035   bool isMemberSpecialization = false;
16036   bool Invalid = false;
16037 
16038   // We only need to do this matching if we have template parameters
16039   // or a scope specifier, which also conveniently avoids this work
16040   // for non-C++ cases.
16041   if (TemplateParameterLists.size() > 0 ||
16042       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16043     if (TemplateParameterList *TemplateParams =
16044             MatchTemplateParametersToScopeSpecifier(
16045                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16046                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16047       if (Kind == TTK_Enum) {
16048         Diag(KWLoc, diag::err_enum_template);
16049         return nullptr;
16050       }
16051 
16052       if (TemplateParams->size() > 0) {
16053         // This is a declaration or definition of a class template (which may
16054         // be a member of another template).
16055 
16056         if (Invalid)
16057           return nullptr;
16058 
16059         OwnedDecl = false;
16060         DeclResult Result = CheckClassTemplate(
16061             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16062             AS, ModulePrivateLoc,
16063             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16064             TemplateParameterLists.data(), SkipBody);
16065         return Result.get();
16066       } else {
16067         // The "template<>" header is extraneous.
16068         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16069           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16070         isMemberSpecialization = true;
16071       }
16072     }
16073 
16074     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16075         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16076       return nullptr;
16077   }
16078 
16079   // Figure out the underlying type if this a enum declaration. We need to do
16080   // this early, because it's needed to detect if this is an incompatible
16081   // redeclaration.
16082   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16083   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16084 
16085   if (Kind == TTK_Enum) {
16086     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16087       // No underlying type explicitly specified, or we failed to parse the
16088       // type, default to int.
16089       EnumUnderlying = Context.IntTy.getTypePtr();
16090     } else if (UnderlyingType.get()) {
16091       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16092       // integral type; any cv-qualification is ignored.
16093       TypeSourceInfo *TI = nullptr;
16094       GetTypeFromParser(UnderlyingType.get(), &TI);
16095       EnumUnderlying = TI;
16096 
16097       if (CheckEnumUnderlyingType(TI))
16098         // Recover by falling back to int.
16099         EnumUnderlying = Context.IntTy.getTypePtr();
16100 
16101       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16102                                           UPPC_FixedUnderlyingType))
16103         EnumUnderlying = Context.IntTy.getTypePtr();
16104 
16105     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16106       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16107       // of 'int'. However, if this is an unfixed forward declaration, don't set
16108       // the underlying type unless the user enables -fms-compatibility. This
16109       // makes unfixed forward declared enums incomplete and is more conforming.
16110       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16111         EnumUnderlying = Context.IntTy.getTypePtr();
16112     }
16113   }
16114 
16115   DeclContext *SearchDC = CurContext;
16116   DeclContext *DC = CurContext;
16117   bool isStdBadAlloc = false;
16118   bool isStdAlignValT = false;
16119 
16120   RedeclarationKind Redecl = forRedeclarationInCurContext();
16121   if (TUK == TUK_Friend || TUK == TUK_Reference)
16122     Redecl = NotForRedeclaration;
16123 
16124   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16125   /// implemented asks for structural equivalence checking, the returned decl
16126   /// here is passed back to the parser, allowing the tag body to be parsed.
16127   auto createTagFromNewDecl = [&]() -> TagDecl * {
16128     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16129     // If there is an identifier, use the location of the identifier as the
16130     // location of the decl, otherwise use the location of the struct/union
16131     // keyword.
16132     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16133     TagDecl *New = nullptr;
16134 
16135     if (Kind == TTK_Enum) {
16136       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16137                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16138       // If this is an undefined enum, bail.
16139       if (TUK != TUK_Definition && !Invalid)
16140         return nullptr;
16141       if (EnumUnderlying) {
16142         EnumDecl *ED = cast<EnumDecl>(New);
16143         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16144           ED->setIntegerTypeSourceInfo(TI);
16145         else
16146           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16147         ED->setPromotionType(ED->getIntegerType());
16148       }
16149     } else { // struct/union
16150       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16151                                nullptr);
16152     }
16153 
16154     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16155       // Add alignment attributes if necessary; these attributes are checked
16156       // when the ASTContext lays out the structure.
16157       //
16158       // It is important for implementing the correct semantics that this
16159       // happen here (in ActOnTag). The #pragma pack stack is
16160       // maintained as a result of parser callbacks which can occur at
16161       // many points during the parsing of a struct declaration (because
16162       // the #pragma tokens are effectively skipped over during the
16163       // parsing of the struct).
16164       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16165         AddAlignmentAttributesForRecord(RD);
16166         AddMsStructLayoutForRecord(RD);
16167       }
16168     }
16169     New->setLexicalDeclContext(CurContext);
16170     return New;
16171   };
16172 
16173   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16174   if (Name && SS.isNotEmpty()) {
16175     // We have a nested-name tag ('struct foo::bar').
16176 
16177     // Check for invalid 'foo::'.
16178     if (SS.isInvalid()) {
16179       Name = nullptr;
16180       goto CreateNewDecl;
16181     }
16182 
16183     // If this is a friend or a reference to a class in a dependent
16184     // context, don't try to make a decl for it.
16185     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16186       DC = computeDeclContext(SS, false);
16187       if (!DC) {
16188         IsDependent = true;
16189         return nullptr;
16190       }
16191     } else {
16192       DC = computeDeclContext(SS, true);
16193       if (!DC) {
16194         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16195           << SS.getRange();
16196         return nullptr;
16197       }
16198     }
16199 
16200     if (RequireCompleteDeclContext(SS, DC))
16201       return nullptr;
16202 
16203     SearchDC = DC;
16204     // Look-up name inside 'foo::'.
16205     LookupQualifiedName(Previous, DC);
16206 
16207     if (Previous.isAmbiguous())
16208       return nullptr;
16209 
16210     if (Previous.empty()) {
16211       // Name lookup did not find anything. However, if the
16212       // nested-name-specifier refers to the current instantiation,
16213       // and that current instantiation has any dependent base
16214       // classes, we might find something at instantiation time: treat
16215       // this as a dependent elaborated-type-specifier.
16216       // But this only makes any sense for reference-like lookups.
16217       if (Previous.wasNotFoundInCurrentInstantiation() &&
16218           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16219         IsDependent = true;
16220         return nullptr;
16221       }
16222 
16223       // A tag 'foo::bar' must already exist.
16224       Diag(NameLoc, diag::err_not_tag_in_scope)
16225         << Kind << Name << DC << SS.getRange();
16226       Name = nullptr;
16227       Invalid = true;
16228       goto CreateNewDecl;
16229     }
16230   } else if (Name) {
16231     // C++14 [class.mem]p14:
16232     //   If T is the name of a class, then each of the following shall have a
16233     //   name different from T:
16234     //    -- every member of class T that is itself a type
16235     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16236         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16237       return nullptr;
16238 
16239     // If this is a named struct, check to see if there was a previous forward
16240     // declaration or definition.
16241     // FIXME: We're looking into outer scopes here, even when we
16242     // shouldn't be. Doing so can result in ambiguities that we
16243     // shouldn't be diagnosing.
16244     LookupName(Previous, S);
16245 
16246     // When declaring or defining a tag, ignore ambiguities introduced
16247     // by types using'ed into this scope.
16248     if (Previous.isAmbiguous() &&
16249         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16250       LookupResult::Filter F = Previous.makeFilter();
16251       while (F.hasNext()) {
16252         NamedDecl *ND = F.next();
16253         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16254                 SearchDC->getRedeclContext()))
16255           F.erase();
16256       }
16257       F.done();
16258     }
16259 
16260     // C++11 [namespace.memdef]p3:
16261     //   If the name in a friend declaration is neither qualified nor
16262     //   a template-id and the declaration is a function or an
16263     //   elaborated-type-specifier, the lookup to determine whether
16264     //   the entity has been previously declared shall not consider
16265     //   any scopes outside the innermost enclosing namespace.
16266     //
16267     // MSVC doesn't implement the above rule for types, so a friend tag
16268     // declaration may be a redeclaration of a type declared in an enclosing
16269     // scope.  They do implement this rule for friend functions.
16270     //
16271     // Does it matter that this should be by scope instead of by
16272     // semantic context?
16273     if (!Previous.empty() && TUK == TUK_Friend) {
16274       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16275       LookupResult::Filter F = Previous.makeFilter();
16276       bool FriendSawTagOutsideEnclosingNamespace = false;
16277       while (F.hasNext()) {
16278         NamedDecl *ND = F.next();
16279         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16280         if (DC->isFileContext() &&
16281             !EnclosingNS->Encloses(ND->getDeclContext())) {
16282           if (getLangOpts().MSVCCompat)
16283             FriendSawTagOutsideEnclosingNamespace = true;
16284           else
16285             F.erase();
16286         }
16287       }
16288       F.done();
16289 
16290       // Diagnose this MSVC extension in the easy case where lookup would have
16291       // unambiguously found something outside the enclosing namespace.
16292       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16293         NamedDecl *ND = Previous.getFoundDecl();
16294         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16295             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16296       }
16297     }
16298 
16299     // Note:  there used to be some attempt at recovery here.
16300     if (Previous.isAmbiguous())
16301       return nullptr;
16302 
16303     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16304       // FIXME: This makes sure that we ignore the contexts associated
16305       // with C structs, unions, and enums when looking for a matching
16306       // tag declaration or definition. See the similar lookup tweak
16307       // in Sema::LookupName; is there a better way to deal with this?
16308       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16309         SearchDC = SearchDC->getParent();
16310     } else if (getLangOpts().CPlusPlus) {
16311       // Inside ObjCContainer want to keep it as a lexical decl context but go
16312       // past it (most often to TranslationUnit) to find the semantic decl
16313       // context.
16314       while (isa<ObjCContainerDecl>(SearchDC))
16315         SearchDC = SearchDC->getParent();
16316     }
16317   } else if (getLangOpts().CPlusPlus) {
16318     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16319     // TagDecl the same way as we skip it for named TagDecl.
16320     while (isa<ObjCContainerDecl>(SearchDC))
16321       SearchDC = SearchDC->getParent();
16322   }
16323 
16324   if (Previous.isSingleResult() &&
16325       Previous.getFoundDecl()->isTemplateParameter()) {
16326     // Maybe we will complain about the shadowed template parameter.
16327     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16328     // Just pretend that we didn't see the previous declaration.
16329     Previous.clear();
16330   }
16331 
16332   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16333       DC->Equals(getStdNamespace())) {
16334     if (Name->isStr("bad_alloc")) {
16335       // This is a declaration of or a reference to "std::bad_alloc".
16336       isStdBadAlloc = true;
16337 
16338       // If std::bad_alloc has been implicitly declared (but made invisible to
16339       // name lookup), fill in this implicit declaration as the previous
16340       // declaration, so that the declarations get chained appropriately.
16341       if (Previous.empty() && StdBadAlloc)
16342         Previous.addDecl(getStdBadAlloc());
16343     } else if (Name->isStr("align_val_t")) {
16344       isStdAlignValT = true;
16345       if (Previous.empty() && StdAlignValT)
16346         Previous.addDecl(getStdAlignValT());
16347     }
16348   }
16349 
16350   // If we didn't find a previous declaration, and this is a reference
16351   // (or friend reference), move to the correct scope.  In C++, we
16352   // also need to do a redeclaration lookup there, just in case
16353   // there's a shadow friend decl.
16354   if (Name && Previous.empty() &&
16355       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16356     if (Invalid) goto CreateNewDecl;
16357     assert(SS.isEmpty());
16358 
16359     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16360       // C++ [basic.scope.pdecl]p5:
16361       //   -- for an elaborated-type-specifier of the form
16362       //
16363       //          class-key identifier
16364       //
16365       //      if the elaborated-type-specifier is used in the
16366       //      decl-specifier-seq or parameter-declaration-clause of a
16367       //      function defined in namespace scope, the identifier is
16368       //      declared as a class-name in the namespace that contains
16369       //      the declaration; otherwise, except as a friend
16370       //      declaration, the identifier is declared in the smallest
16371       //      non-class, non-function-prototype scope that contains the
16372       //      declaration.
16373       //
16374       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16375       // C structs and unions.
16376       //
16377       // It is an error in C++ to declare (rather than define) an enum
16378       // type, including via an elaborated type specifier.  We'll
16379       // diagnose that later; for now, declare the enum in the same
16380       // scope as we would have picked for any other tag type.
16381       //
16382       // GNU C also supports this behavior as part of its incomplete
16383       // enum types extension, while GNU C++ does not.
16384       //
16385       // Find the context where we'll be declaring the tag.
16386       // FIXME: We would like to maintain the current DeclContext as the
16387       // lexical context,
16388       SearchDC = getTagInjectionContext(SearchDC);
16389 
16390       // Find the scope where we'll be declaring the tag.
16391       S = getTagInjectionScope(S, getLangOpts());
16392     } else {
16393       assert(TUK == TUK_Friend);
16394       // C++ [namespace.memdef]p3:
16395       //   If a friend declaration in a non-local class first declares a
16396       //   class or function, the friend class or function is a member of
16397       //   the innermost enclosing namespace.
16398       SearchDC = SearchDC->getEnclosingNamespaceContext();
16399     }
16400 
16401     // In C++, we need to do a redeclaration lookup to properly
16402     // diagnose some problems.
16403     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16404     // hidden declaration so that we don't get ambiguity errors when using a
16405     // type declared by an elaborated-type-specifier.  In C that is not correct
16406     // and we should instead merge compatible types found by lookup.
16407     if (getLangOpts().CPlusPlus) {
16408       // FIXME: This can perform qualified lookups into function contexts,
16409       // which are meaningless.
16410       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16411       LookupQualifiedName(Previous, SearchDC);
16412     } else {
16413       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16414       LookupName(Previous, S);
16415     }
16416   }
16417 
16418   // If we have a known previous declaration to use, then use it.
16419   if (Previous.empty() && SkipBody && SkipBody->Previous)
16420     Previous.addDecl(SkipBody->Previous);
16421 
16422   if (!Previous.empty()) {
16423     NamedDecl *PrevDecl = Previous.getFoundDecl();
16424     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16425 
16426     // It's okay to have a tag decl in the same scope as a typedef
16427     // which hides a tag decl in the same scope.  Finding this
16428     // with a redeclaration lookup can only actually happen in C++.
16429     //
16430     // This is also okay for elaborated-type-specifiers, which is
16431     // technically forbidden by the current standard but which is
16432     // okay according to the likely resolution of an open issue;
16433     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16434     if (getLangOpts().CPlusPlus) {
16435       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16436         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16437           TagDecl *Tag = TT->getDecl();
16438           if (Tag->getDeclName() == Name &&
16439               Tag->getDeclContext()->getRedeclContext()
16440                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16441             PrevDecl = Tag;
16442             Previous.clear();
16443             Previous.addDecl(Tag);
16444             Previous.resolveKind();
16445           }
16446         }
16447       }
16448     }
16449 
16450     // If this is a redeclaration of a using shadow declaration, it must
16451     // declare a tag in the same context. In MSVC mode, we allow a
16452     // redefinition if either context is within the other.
16453     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16454       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16455       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16456           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16457           !(OldTag && isAcceptableTagRedeclContext(
16458                           *this, OldTag->getDeclContext(), SearchDC))) {
16459         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16460         Diag(Shadow->getTargetDecl()->getLocation(),
16461              diag::note_using_decl_target);
16462         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16463             << 0;
16464         // Recover by ignoring the old declaration.
16465         Previous.clear();
16466         goto CreateNewDecl;
16467       }
16468     }
16469 
16470     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16471       // If this is a use of a previous tag, or if the tag is already declared
16472       // in the same scope (so that the definition/declaration completes or
16473       // rementions the tag), reuse the decl.
16474       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16475           isDeclInScope(DirectPrevDecl, SearchDC, S,
16476                         SS.isNotEmpty() || isMemberSpecialization)) {
16477         // Make sure that this wasn't declared as an enum and now used as a
16478         // struct or something similar.
16479         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16480                                           TUK == TUK_Definition, KWLoc,
16481                                           Name)) {
16482           bool SafeToContinue
16483             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16484                Kind != TTK_Enum);
16485           if (SafeToContinue)
16486             Diag(KWLoc, diag::err_use_with_wrong_tag)
16487               << Name
16488               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16489                                               PrevTagDecl->getKindName());
16490           else
16491             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16492           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16493 
16494           if (SafeToContinue)
16495             Kind = PrevTagDecl->getTagKind();
16496           else {
16497             // Recover by making this an anonymous redefinition.
16498             Name = nullptr;
16499             Previous.clear();
16500             Invalid = true;
16501           }
16502         }
16503 
16504         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16505           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16506           if (TUK == TUK_Reference || TUK == TUK_Friend)
16507             return PrevTagDecl;
16508 
16509           QualType EnumUnderlyingTy;
16510           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16511             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16512           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16513             EnumUnderlyingTy = QualType(T, 0);
16514 
16515           // All conflicts with previous declarations are recovered by
16516           // returning the previous declaration, unless this is a definition,
16517           // in which case we want the caller to bail out.
16518           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16519                                      ScopedEnum, EnumUnderlyingTy,
16520                                      IsFixed, PrevEnum))
16521             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16522         }
16523 
16524         // C++11 [class.mem]p1:
16525         //   A member shall not be declared twice in the member-specification,
16526         //   except that a nested class or member class template can be declared
16527         //   and then later defined.
16528         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16529             S->isDeclScope(PrevDecl)) {
16530           Diag(NameLoc, diag::ext_member_redeclared);
16531           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16532         }
16533 
16534         if (!Invalid) {
16535           // If this is a use, just return the declaration we found, unless
16536           // we have attributes.
16537           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16538             if (!Attrs.empty()) {
16539               // FIXME: Diagnose these attributes. For now, we create a new
16540               // declaration to hold them.
16541             } else if (TUK == TUK_Reference &&
16542                        (PrevTagDecl->getFriendObjectKind() ==
16543                             Decl::FOK_Undeclared ||
16544                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16545                        SS.isEmpty()) {
16546               // This declaration is a reference to an existing entity, but
16547               // has different visibility from that entity: it either makes
16548               // a friend visible or it makes a type visible in a new module.
16549               // In either case, create a new declaration. We only do this if
16550               // the declaration would have meant the same thing if no prior
16551               // declaration were found, that is, if it was found in the same
16552               // scope where we would have injected a declaration.
16553               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16554                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16555                 return PrevTagDecl;
16556               // This is in the injected scope, create a new declaration in
16557               // that scope.
16558               S = getTagInjectionScope(S, getLangOpts());
16559             } else {
16560               return PrevTagDecl;
16561             }
16562           }
16563 
16564           // Diagnose attempts to redefine a tag.
16565           if (TUK == TUK_Definition) {
16566             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16567               // If we're defining a specialization and the previous definition
16568               // is from an implicit instantiation, don't emit an error
16569               // here; we'll catch this in the general case below.
16570               bool IsExplicitSpecializationAfterInstantiation = false;
16571               if (isMemberSpecialization) {
16572                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16573                   IsExplicitSpecializationAfterInstantiation =
16574                     RD->getTemplateSpecializationKind() !=
16575                     TSK_ExplicitSpecialization;
16576                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16577                   IsExplicitSpecializationAfterInstantiation =
16578                     ED->getTemplateSpecializationKind() !=
16579                     TSK_ExplicitSpecialization;
16580               }
16581 
16582               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16583               // not keep more that one definition around (merge them). However,
16584               // ensure the decl passes the structural compatibility check in
16585               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16586               NamedDecl *Hidden = nullptr;
16587               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16588                 // There is a definition of this tag, but it is not visible. We
16589                 // explicitly make use of C++'s one definition rule here, and
16590                 // assume that this definition is identical to the hidden one
16591                 // we already have. Make the existing definition visible and
16592                 // use it in place of this one.
16593                 if (!getLangOpts().CPlusPlus) {
16594                   // Postpone making the old definition visible until after we
16595                   // complete parsing the new one and do the structural
16596                   // comparison.
16597                   SkipBody->CheckSameAsPrevious = true;
16598                   SkipBody->New = createTagFromNewDecl();
16599                   SkipBody->Previous = Def;
16600                   return Def;
16601                 } else {
16602                   SkipBody->ShouldSkip = true;
16603                   SkipBody->Previous = Def;
16604                   makeMergedDefinitionVisible(Hidden);
16605                   // Carry on and handle it like a normal definition. We'll
16606                   // skip starting the definitiion later.
16607                 }
16608               } else if (!IsExplicitSpecializationAfterInstantiation) {
16609                 // A redeclaration in function prototype scope in C isn't
16610                 // visible elsewhere, so merely issue a warning.
16611                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16612                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16613                 else
16614                   Diag(NameLoc, diag::err_redefinition) << Name;
16615                 notePreviousDefinition(Def,
16616                                        NameLoc.isValid() ? NameLoc : KWLoc);
16617                 // If this is a redefinition, recover by making this
16618                 // struct be anonymous, which will make any later
16619                 // references get the previous definition.
16620                 Name = nullptr;
16621                 Previous.clear();
16622                 Invalid = true;
16623               }
16624             } else {
16625               // If the type is currently being defined, complain
16626               // about a nested redefinition.
16627               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16628               if (TD->isBeingDefined()) {
16629                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16630                 Diag(PrevTagDecl->getLocation(),
16631                      diag::note_previous_definition);
16632                 Name = nullptr;
16633                 Previous.clear();
16634                 Invalid = true;
16635               }
16636             }
16637 
16638             // Okay, this is definition of a previously declared or referenced
16639             // tag. We're going to create a new Decl for it.
16640           }
16641 
16642           // Okay, we're going to make a redeclaration.  If this is some kind
16643           // of reference, make sure we build the redeclaration in the same DC
16644           // as the original, and ignore the current access specifier.
16645           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16646             SearchDC = PrevTagDecl->getDeclContext();
16647             AS = AS_none;
16648           }
16649         }
16650         // If we get here we have (another) forward declaration or we
16651         // have a definition.  Just create a new decl.
16652 
16653       } else {
16654         // If we get here, this is a definition of a new tag type in a nested
16655         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16656         // new decl/type.  We set PrevDecl to NULL so that the entities
16657         // have distinct types.
16658         Previous.clear();
16659       }
16660       // If we get here, we're going to create a new Decl. If PrevDecl
16661       // is non-NULL, it's a definition of the tag declared by
16662       // PrevDecl. If it's NULL, we have a new definition.
16663 
16664     // Otherwise, PrevDecl is not a tag, but was found with tag
16665     // lookup.  This is only actually possible in C++, where a few
16666     // things like templates still live in the tag namespace.
16667     } else {
16668       // Use a better diagnostic if an elaborated-type-specifier
16669       // found the wrong kind of type on the first
16670       // (non-redeclaration) lookup.
16671       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16672           !Previous.isForRedeclaration()) {
16673         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16674         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16675                                                        << Kind;
16676         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16677         Invalid = true;
16678 
16679       // Otherwise, only diagnose if the declaration is in scope.
16680       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16681                                 SS.isNotEmpty() || isMemberSpecialization)) {
16682         // do nothing
16683 
16684       // Diagnose implicit declarations introduced by elaborated types.
16685       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16686         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16687         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16688         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16689         Invalid = true;
16690 
16691       // Otherwise it's a declaration.  Call out a particularly common
16692       // case here.
16693       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16694         unsigned Kind = 0;
16695         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16696         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16697           << Name << Kind << TND->getUnderlyingType();
16698         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16699         Invalid = true;
16700 
16701       // Otherwise, diagnose.
16702       } else {
16703         // The tag name clashes with something else in the target scope,
16704         // issue an error and recover by making this tag be anonymous.
16705         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16706         notePreviousDefinition(PrevDecl, NameLoc);
16707         Name = nullptr;
16708         Invalid = true;
16709       }
16710 
16711       // The existing declaration isn't relevant to us; we're in a
16712       // new scope, so clear out the previous declaration.
16713       Previous.clear();
16714     }
16715   }
16716 
16717 CreateNewDecl:
16718 
16719   TagDecl *PrevDecl = nullptr;
16720   if (Previous.isSingleResult())
16721     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16722 
16723   // If there is an identifier, use the location of the identifier as the
16724   // location of the decl, otherwise use the location of the struct/union
16725   // keyword.
16726   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16727 
16728   // Otherwise, create a new declaration. If there is a previous
16729   // declaration of the same entity, the two will be linked via
16730   // PrevDecl.
16731   TagDecl *New;
16732 
16733   if (Kind == TTK_Enum) {
16734     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16735     // enum X { A, B, C } D;    D should chain to X.
16736     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16737                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16738                            ScopedEnumUsesClassTag, IsFixed);
16739 
16740     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16741       StdAlignValT = cast<EnumDecl>(New);
16742 
16743     // If this is an undefined enum, warn.
16744     if (TUK != TUK_Definition && !Invalid) {
16745       TagDecl *Def;
16746       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16747         // C++0x: 7.2p2: opaque-enum-declaration.
16748         // Conflicts are diagnosed above. Do nothing.
16749       }
16750       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16751         Diag(Loc, diag::ext_forward_ref_enum_def)
16752           << New;
16753         Diag(Def->getLocation(), diag::note_previous_definition);
16754       } else {
16755         unsigned DiagID = diag::ext_forward_ref_enum;
16756         if (getLangOpts().MSVCCompat)
16757           DiagID = diag::ext_ms_forward_ref_enum;
16758         else if (getLangOpts().CPlusPlus)
16759           DiagID = diag::err_forward_ref_enum;
16760         Diag(Loc, DiagID);
16761       }
16762     }
16763 
16764     if (EnumUnderlying) {
16765       EnumDecl *ED = cast<EnumDecl>(New);
16766       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16767         ED->setIntegerTypeSourceInfo(TI);
16768       else
16769         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16770       ED->setPromotionType(ED->getIntegerType());
16771       assert(ED->isComplete() && "enum with type should be complete");
16772     }
16773   } else {
16774     // struct/union/class
16775 
16776     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16777     // struct X { int A; } D;    D should chain to X.
16778     if (getLangOpts().CPlusPlus) {
16779       // FIXME: Look for a way to use RecordDecl for simple structs.
16780       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16781                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16782 
16783       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16784         StdBadAlloc = cast<CXXRecordDecl>(New);
16785     } else
16786       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16787                                cast_or_null<RecordDecl>(PrevDecl));
16788   }
16789 
16790   // C++11 [dcl.type]p3:
16791   //   A type-specifier-seq shall not define a class or enumeration [...].
16792   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16793       TUK == TUK_Definition) {
16794     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16795       << Context.getTagDeclType(New);
16796     Invalid = true;
16797   }
16798 
16799   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16800       DC->getDeclKind() == Decl::Enum) {
16801     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16802       << Context.getTagDeclType(New);
16803     Invalid = true;
16804   }
16805 
16806   // Maybe add qualifier info.
16807   if (SS.isNotEmpty()) {
16808     if (SS.isSet()) {
16809       // If this is either a declaration or a definition, check the
16810       // nested-name-specifier against the current context.
16811       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16812           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16813                                        isMemberSpecialization))
16814         Invalid = true;
16815 
16816       New->setQualifierInfo(SS.getWithLocInContext(Context));
16817       if (TemplateParameterLists.size() > 0) {
16818         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16819       }
16820     }
16821     else
16822       Invalid = true;
16823   }
16824 
16825   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16826     // Add alignment attributes if necessary; these attributes are checked when
16827     // the ASTContext lays out the structure.
16828     //
16829     // It is important for implementing the correct semantics that this
16830     // happen here (in ActOnTag). The #pragma pack stack is
16831     // maintained as a result of parser callbacks which can occur at
16832     // many points during the parsing of a struct declaration (because
16833     // the #pragma tokens are effectively skipped over during the
16834     // parsing of the struct).
16835     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16836       AddAlignmentAttributesForRecord(RD);
16837       AddMsStructLayoutForRecord(RD);
16838     }
16839   }
16840 
16841   if (ModulePrivateLoc.isValid()) {
16842     if (isMemberSpecialization)
16843       Diag(New->getLocation(), diag::err_module_private_specialization)
16844         << 2
16845         << FixItHint::CreateRemoval(ModulePrivateLoc);
16846     // __module_private__ does not apply to local classes. However, we only
16847     // diagnose this as an error when the declaration specifiers are
16848     // freestanding. Here, we just ignore the __module_private__.
16849     else if (!SearchDC->isFunctionOrMethod())
16850       New->setModulePrivate();
16851   }
16852 
16853   // If this is a specialization of a member class (of a class template),
16854   // check the specialization.
16855   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16856     Invalid = true;
16857 
16858   // If we're declaring or defining a tag in function prototype scope in C,
16859   // note that this type can only be used within the function and add it to
16860   // the list of decls to inject into the function definition scope.
16861   if ((Name || Kind == TTK_Enum) &&
16862       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16863     if (getLangOpts().CPlusPlus) {
16864       // C++ [dcl.fct]p6:
16865       //   Types shall not be defined in return or parameter types.
16866       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16867         Diag(Loc, diag::err_type_defined_in_param_type)
16868             << Name;
16869         Invalid = true;
16870       }
16871     } else if (!PrevDecl) {
16872       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16873     }
16874   }
16875 
16876   if (Invalid)
16877     New->setInvalidDecl();
16878 
16879   // Set the lexical context. If the tag has a C++ scope specifier, the
16880   // lexical context will be different from the semantic context.
16881   New->setLexicalDeclContext(CurContext);
16882 
16883   // Mark this as a friend decl if applicable.
16884   // In Microsoft mode, a friend declaration also acts as a forward
16885   // declaration so we always pass true to setObjectOfFriendDecl to make
16886   // the tag name visible.
16887   if (TUK == TUK_Friend)
16888     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16889 
16890   // Set the access specifier.
16891   if (!Invalid && SearchDC->isRecord())
16892     SetMemberAccessSpecifier(New, PrevDecl, AS);
16893 
16894   if (PrevDecl)
16895     CheckRedeclarationInModule(New, PrevDecl);
16896 
16897   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16898     New->startDefinition();
16899 
16900   ProcessDeclAttributeList(S, New, Attrs);
16901   AddPragmaAttributes(S, New);
16902 
16903   // If this has an identifier, add it to the scope stack.
16904   if (TUK == TUK_Friend) {
16905     // We might be replacing an existing declaration in the lookup tables;
16906     // if so, borrow its access specifier.
16907     if (PrevDecl)
16908       New->setAccess(PrevDecl->getAccess());
16909 
16910     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16911     DC->makeDeclVisibleInContext(New);
16912     if (Name) // can be null along some error paths
16913       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16914         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16915   } else if (Name) {
16916     S = getNonFieldDeclScope(S);
16917     PushOnScopeChains(New, S, true);
16918   } else {
16919     CurContext->addDecl(New);
16920   }
16921 
16922   // If this is the C FILE type, notify the AST context.
16923   if (IdentifierInfo *II = New->getIdentifier())
16924     if (!New->isInvalidDecl() &&
16925         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16926         II->isStr("FILE"))
16927       Context.setFILEDecl(New);
16928 
16929   if (PrevDecl)
16930     mergeDeclAttributes(New, PrevDecl);
16931 
16932   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16933     inferGslOwnerPointerAttribute(CXXRD);
16934 
16935   // If there's a #pragma GCC visibility in scope, set the visibility of this
16936   // record.
16937   AddPushedVisibilityAttribute(New);
16938 
16939   if (isMemberSpecialization && !New->isInvalidDecl())
16940     CompleteMemberSpecialization(New, Previous);
16941 
16942   OwnedDecl = true;
16943   // In C++, don't return an invalid declaration. We can't recover well from
16944   // the cases where we make the type anonymous.
16945   if (Invalid && getLangOpts().CPlusPlus) {
16946     if (New->isBeingDefined())
16947       if (auto RD = dyn_cast<RecordDecl>(New))
16948         RD->completeDefinition();
16949     return nullptr;
16950   } else if (SkipBody && SkipBody->ShouldSkip) {
16951     return SkipBody->Previous;
16952   } else {
16953     return New;
16954   }
16955 }
16956 
16957 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16958   AdjustDeclIfTemplate(TagD);
16959   TagDecl *Tag = cast<TagDecl>(TagD);
16960 
16961   // Enter the tag context.
16962   PushDeclContext(S, Tag);
16963 
16964   ActOnDocumentableDecl(TagD);
16965 
16966   // If there's a #pragma GCC visibility in scope, set the visibility of this
16967   // record.
16968   AddPushedVisibilityAttribute(Tag);
16969 }
16970 
16971 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16972   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16973     return false;
16974 
16975   // Make the previous decl visible.
16976   makeMergedDefinitionVisible(SkipBody.Previous);
16977   return true;
16978 }
16979 
16980 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
16981   assert(IDecl->getLexicalParent() == CurContext &&
16982       "The next DeclContext should be lexically contained in the current one.");
16983   CurContext = IDecl;
16984 }
16985 
16986 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16987                                            SourceLocation FinalLoc,
16988                                            bool IsFinalSpelledSealed,
16989                                            bool IsAbstract,
16990                                            SourceLocation LBraceLoc) {
16991   AdjustDeclIfTemplate(TagD);
16992   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16993 
16994   FieldCollector->StartClass();
16995 
16996   if (!Record->getIdentifier())
16997     return;
16998 
16999   if (IsAbstract)
17000     Record->markAbstract();
17001 
17002   if (FinalLoc.isValid()) {
17003     Record->addAttr(FinalAttr::Create(
17004         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17005         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17006   }
17007   // C++ [class]p2:
17008   //   [...] The class-name is also inserted into the scope of the
17009   //   class itself; this is known as the injected-class-name. For
17010   //   purposes of access checking, the injected-class-name is treated
17011   //   as if it were a public member name.
17012   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17013       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17014       Record->getLocation(), Record->getIdentifier(),
17015       /*PrevDecl=*/nullptr,
17016       /*DelayTypeCreation=*/true);
17017   Context.getTypeDeclType(InjectedClassName, Record);
17018   InjectedClassName->setImplicit();
17019   InjectedClassName->setAccess(AS_public);
17020   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17021       InjectedClassName->setDescribedClassTemplate(Template);
17022   PushOnScopeChains(InjectedClassName, S);
17023   assert(InjectedClassName->isInjectedClassName() &&
17024          "Broken injected-class-name");
17025 }
17026 
17027 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17028                                     SourceRange BraceRange) {
17029   AdjustDeclIfTemplate(TagD);
17030   TagDecl *Tag = cast<TagDecl>(TagD);
17031   Tag->setBraceRange(BraceRange);
17032 
17033   // Make sure we "complete" the definition even it is invalid.
17034   if (Tag->isBeingDefined()) {
17035     assert(Tag->isInvalidDecl() && "We should already have completed it");
17036     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17037       RD->completeDefinition();
17038   }
17039 
17040   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17041     FieldCollector->FinishClass();
17042     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17043       auto *Def = RD->getDefinition();
17044       assert(Def && "The record is expected to have a completed definition");
17045       unsigned NumInitMethods = 0;
17046       for (auto *Method : Def->methods()) {
17047         if (!Method->getIdentifier())
17048             continue;
17049         if (Method->getName() == "__init")
17050           NumInitMethods++;
17051       }
17052       if (NumInitMethods > 1 || !Def->hasInitMethod())
17053         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17054     }
17055   }
17056 
17057   // Exit this scope of this tag's definition.
17058   PopDeclContext();
17059 
17060   if (getCurLexicalContext()->isObjCContainer() &&
17061       Tag->getDeclContext()->isFileContext())
17062     Tag->setTopLevelDeclInObjCContainer();
17063 
17064   // Notify the consumer that we've defined a tag.
17065   if (!Tag->isInvalidDecl())
17066     Consumer.HandleTagDeclDefinition(Tag);
17067 
17068   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17069   // from XLs and instead matches the XL #pragma pack(1) behavior.
17070   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17071       AlignPackStack.hasValue()) {
17072     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17073     // Only diagnose #pragma align(packed).
17074     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17075       return;
17076     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17077     if (!RD)
17078       return;
17079     // Only warn if there is at least 1 bitfield member.
17080     if (llvm::any_of(RD->fields(),
17081                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17082       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17083   }
17084 }
17085 
17086 void Sema::ActOnObjCContainerFinishDefinition() {
17087   // Exit this scope of this interface definition.
17088   PopDeclContext();
17089 }
17090 
17091 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17092   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17093   OriginalLexicalContext = ObjCCtx;
17094   ActOnObjCContainerFinishDefinition();
17095 }
17096 
17097 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17098   ActOnObjCContainerStartDefinition(ObjCCtx);
17099   OriginalLexicalContext = nullptr;
17100 }
17101 
17102 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17103   AdjustDeclIfTemplate(TagD);
17104   TagDecl *Tag = cast<TagDecl>(TagD);
17105   Tag->setInvalidDecl();
17106 
17107   // Make sure we "complete" the definition even it is invalid.
17108   if (Tag->isBeingDefined()) {
17109     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17110       RD->completeDefinition();
17111   }
17112 
17113   // We're undoing ActOnTagStartDefinition here, not
17114   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17115   // the FieldCollector.
17116 
17117   PopDeclContext();
17118 }
17119 
17120 // Note that FieldName may be null for anonymous bitfields.
17121 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17122                                 IdentifierInfo *FieldName, QualType FieldTy,
17123                                 bool IsMsStruct, Expr *BitWidth) {
17124   assert(BitWidth);
17125   if (BitWidth->containsErrors())
17126     return ExprError();
17127 
17128   // C99 6.7.2.1p4 - verify the field type.
17129   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17130   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17131     // Handle incomplete and sizeless types with a specific error.
17132     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17133                                  diag::err_field_incomplete_or_sizeless))
17134       return ExprError();
17135     if (FieldName)
17136       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17137         << FieldName << FieldTy << BitWidth->getSourceRange();
17138     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17139       << FieldTy << BitWidth->getSourceRange();
17140   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17141                                              UPPC_BitFieldWidth))
17142     return ExprError();
17143 
17144   // If the bit-width is type- or value-dependent, don't try to check
17145   // it now.
17146   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17147     return BitWidth;
17148 
17149   llvm::APSInt Value;
17150   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17151   if (ICE.isInvalid())
17152     return ICE;
17153   BitWidth = ICE.get();
17154 
17155   // Zero-width bitfield is ok for anonymous field.
17156   if (Value == 0 && FieldName)
17157     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17158 
17159   if (Value.isSigned() && Value.isNegative()) {
17160     if (FieldName)
17161       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17162                << FieldName << toString(Value, 10);
17163     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17164       << toString(Value, 10);
17165   }
17166 
17167   // The size of the bit-field must not exceed our maximum permitted object
17168   // size.
17169   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17170     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17171            << !FieldName << FieldName << toString(Value, 10);
17172   }
17173 
17174   if (!FieldTy->isDependentType()) {
17175     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17176     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17177     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17178 
17179     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17180     // ABI.
17181     bool CStdConstraintViolation =
17182         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17183     bool MSBitfieldViolation =
17184         Value.ugt(TypeStorageSize) &&
17185         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17186     if (CStdConstraintViolation || MSBitfieldViolation) {
17187       unsigned DiagWidth =
17188           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17189       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17190              << (bool)FieldName << FieldName << toString(Value, 10)
17191              << !CStdConstraintViolation << DiagWidth;
17192     }
17193 
17194     // Warn on types where the user might conceivably expect to get all
17195     // specified bits as value bits: that's all integral types other than
17196     // 'bool'.
17197     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17198       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17199           << FieldName << toString(Value, 10)
17200           << (unsigned)TypeWidth;
17201     }
17202   }
17203 
17204   return BitWidth;
17205 }
17206 
17207 /// ActOnField - Each field of a C struct/union is passed into this in order
17208 /// to create a FieldDecl object for it.
17209 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17210                        Declarator &D, Expr *BitfieldWidth) {
17211   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17212                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17213                                /*InitStyle=*/ICIS_NoInit, AS_public);
17214   return Res;
17215 }
17216 
17217 /// HandleField - Analyze a field of a C struct or a C++ data member.
17218 ///
17219 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17220                              SourceLocation DeclStart,
17221                              Declarator &D, Expr *BitWidth,
17222                              InClassInitStyle InitStyle,
17223                              AccessSpecifier AS) {
17224   if (D.isDecompositionDeclarator()) {
17225     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17226     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17227       << Decomp.getSourceRange();
17228     return nullptr;
17229   }
17230 
17231   IdentifierInfo *II = D.getIdentifier();
17232   SourceLocation Loc = DeclStart;
17233   if (II) Loc = D.getIdentifierLoc();
17234 
17235   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17236   QualType T = TInfo->getType();
17237   if (getLangOpts().CPlusPlus) {
17238     CheckExtraCXXDefaultArguments(D);
17239 
17240     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17241                                         UPPC_DataMemberType)) {
17242       D.setInvalidType();
17243       T = Context.IntTy;
17244       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17245     }
17246   }
17247 
17248   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17249 
17250   if (D.getDeclSpec().isInlineSpecified())
17251     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17252         << getLangOpts().CPlusPlus17;
17253   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17254     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17255          diag::err_invalid_thread)
17256       << DeclSpec::getSpecifierName(TSCS);
17257 
17258   // Check to see if this name was declared as a member previously
17259   NamedDecl *PrevDecl = nullptr;
17260   LookupResult Previous(*this, II, Loc, LookupMemberName,
17261                         ForVisibleRedeclaration);
17262   LookupName(Previous, S);
17263   switch (Previous.getResultKind()) {
17264     case LookupResult::Found:
17265     case LookupResult::FoundUnresolvedValue:
17266       PrevDecl = Previous.getAsSingle<NamedDecl>();
17267       break;
17268 
17269     case LookupResult::FoundOverloaded:
17270       PrevDecl = Previous.getRepresentativeDecl();
17271       break;
17272 
17273     case LookupResult::NotFound:
17274     case LookupResult::NotFoundInCurrentInstantiation:
17275     case LookupResult::Ambiguous:
17276       break;
17277   }
17278   Previous.suppressDiagnostics();
17279 
17280   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17281     // Maybe we will complain about the shadowed template parameter.
17282     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17283     // Just pretend that we didn't see the previous declaration.
17284     PrevDecl = nullptr;
17285   }
17286 
17287   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17288     PrevDecl = nullptr;
17289 
17290   bool Mutable
17291     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17292   SourceLocation TSSL = D.getBeginLoc();
17293   FieldDecl *NewFD
17294     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17295                      TSSL, AS, PrevDecl, &D);
17296 
17297   if (NewFD->isInvalidDecl())
17298     Record->setInvalidDecl();
17299 
17300   if (D.getDeclSpec().isModulePrivateSpecified())
17301     NewFD->setModulePrivate();
17302 
17303   if (NewFD->isInvalidDecl() && PrevDecl) {
17304     // Don't introduce NewFD into scope; there's already something
17305     // with the same name in the same scope.
17306   } else if (II) {
17307     PushOnScopeChains(NewFD, S);
17308   } else
17309     Record->addDecl(NewFD);
17310 
17311   return NewFD;
17312 }
17313 
17314 /// Build a new FieldDecl and check its well-formedness.
17315 ///
17316 /// This routine builds a new FieldDecl given the fields name, type,
17317 /// record, etc. \p PrevDecl should refer to any previous declaration
17318 /// with the same name and in the same scope as the field to be
17319 /// created.
17320 ///
17321 /// \returns a new FieldDecl.
17322 ///
17323 /// \todo The Declarator argument is a hack. It will be removed once
17324 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17325                                 TypeSourceInfo *TInfo,
17326                                 RecordDecl *Record, SourceLocation Loc,
17327                                 bool Mutable, Expr *BitWidth,
17328                                 InClassInitStyle InitStyle,
17329                                 SourceLocation TSSL,
17330                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17331                                 Declarator *D) {
17332   IdentifierInfo *II = Name.getAsIdentifierInfo();
17333   bool InvalidDecl = false;
17334   if (D) InvalidDecl = D->isInvalidType();
17335 
17336   // If we receive a broken type, recover by assuming 'int' and
17337   // marking this declaration as invalid.
17338   if (T.isNull() || T->containsErrors()) {
17339     InvalidDecl = true;
17340     T = Context.IntTy;
17341   }
17342 
17343   QualType EltTy = Context.getBaseElementType(T);
17344   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17345     if (RequireCompleteSizedType(Loc, EltTy,
17346                                  diag::err_field_incomplete_or_sizeless)) {
17347       // Fields of incomplete type force their record to be invalid.
17348       Record->setInvalidDecl();
17349       InvalidDecl = true;
17350     } else {
17351       NamedDecl *Def;
17352       EltTy->isIncompleteType(&Def);
17353       if (Def && Def->isInvalidDecl()) {
17354         Record->setInvalidDecl();
17355         InvalidDecl = true;
17356       }
17357     }
17358   }
17359 
17360   // TR 18037 does not allow fields to be declared with address space
17361   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17362       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17363     Diag(Loc, diag::err_field_with_address_space);
17364     Record->setInvalidDecl();
17365     InvalidDecl = true;
17366   }
17367 
17368   if (LangOpts.OpenCL) {
17369     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17370     // used as structure or union field: image, sampler, event or block types.
17371     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17372         T->isBlockPointerType()) {
17373       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17374       Record->setInvalidDecl();
17375       InvalidDecl = true;
17376     }
17377     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17378     // is enabled.
17379     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17380                         "__cl_clang_bitfields", LangOpts)) {
17381       Diag(Loc, diag::err_opencl_bitfields);
17382       InvalidDecl = true;
17383     }
17384   }
17385 
17386   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17387   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17388       T.hasQualifiers()) {
17389     InvalidDecl = true;
17390     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17391   }
17392 
17393   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17394   // than a variably modified type.
17395   if (!InvalidDecl && T->isVariablyModifiedType()) {
17396     if (!tryToFixVariablyModifiedVarType(
17397             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17398       InvalidDecl = true;
17399   }
17400 
17401   // Fields can not have abstract class types
17402   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17403                                              diag::err_abstract_type_in_decl,
17404                                              AbstractFieldType))
17405     InvalidDecl = true;
17406 
17407   if (InvalidDecl)
17408     BitWidth = nullptr;
17409   // If this is declared as a bit-field, check the bit-field.
17410   if (BitWidth) {
17411     BitWidth =
17412         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17413     if (!BitWidth) {
17414       InvalidDecl = true;
17415       BitWidth = nullptr;
17416     }
17417   }
17418 
17419   // Check that 'mutable' is consistent with the type of the declaration.
17420   if (!InvalidDecl && Mutable) {
17421     unsigned DiagID = 0;
17422     if (T->isReferenceType())
17423       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17424                                         : diag::err_mutable_reference;
17425     else if (T.isConstQualified())
17426       DiagID = diag::err_mutable_const;
17427 
17428     if (DiagID) {
17429       SourceLocation ErrLoc = Loc;
17430       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17431         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17432       Diag(ErrLoc, DiagID);
17433       if (DiagID != diag::ext_mutable_reference) {
17434         Mutable = false;
17435         InvalidDecl = true;
17436       }
17437     }
17438   }
17439 
17440   // C++11 [class.union]p8 (DR1460):
17441   //   At most one variant member of a union may have a
17442   //   brace-or-equal-initializer.
17443   if (InitStyle != ICIS_NoInit)
17444     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17445 
17446   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17447                                        BitWidth, Mutable, InitStyle);
17448   if (InvalidDecl)
17449     NewFD->setInvalidDecl();
17450 
17451   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17452     Diag(Loc, diag::err_duplicate_member) << II;
17453     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17454     NewFD->setInvalidDecl();
17455   }
17456 
17457   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17458     if (Record->isUnion()) {
17459       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17460         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17461         if (RDecl->getDefinition()) {
17462           // C++ [class.union]p1: An object of a class with a non-trivial
17463           // constructor, a non-trivial copy constructor, a non-trivial
17464           // destructor, or a non-trivial copy assignment operator
17465           // cannot be a member of a union, nor can an array of such
17466           // objects.
17467           if (CheckNontrivialField(NewFD))
17468             NewFD->setInvalidDecl();
17469         }
17470       }
17471 
17472       // C++ [class.union]p1: If a union contains a member of reference type,
17473       // the program is ill-formed, except when compiling with MSVC extensions
17474       // enabled.
17475       if (EltTy->isReferenceType()) {
17476         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17477                                     diag::ext_union_member_of_reference_type :
17478                                     diag::err_union_member_of_reference_type)
17479           << NewFD->getDeclName() << EltTy;
17480         if (!getLangOpts().MicrosoftExt)
17481           NewFD->setInvalidDecl();
17482       }
17483     }
17484   }
17485 
17486   // FIXME: We need to pass in the attributes given an AST
17487   // representation, not a parser representation.
17488   if (D) {
17489     // FIXME: The current scope is almost... but not entirely... correct here.
17490     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17491 
17492     if (NewFD->hasAttrs())
17493       CheckAlignasUnderalignment(NewFD);
17494   }
17495 
17496   // In auto-retain/release, infer strong retension for fields of
17497   // retainable type.
17498   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17499     NewFD->setInvalidDecl();
17500 
17501   if (T.isObjCGCWeak())
17502     Diag(Loc, diag::warn_attribute_weak_on_field);
17503 
17504   // PPC MMA non-pointer types are not allowed as field types.
17505   if (Context.getTargetInfo().getTriple().isPPC64() &&
17506       CheckPPCMMAType(T, NewFD->getLocation()))
17507     NewFD->setInvalidDecl();
17508 
17509   NewFD->setAccess(AS);
17510   return NewFD;
17511 }
17512 
17513 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17514   assert(FD);
17515   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17516 
17517   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17518     return false;
17519 
17520   QualType EltTy = Context.getBaseElementType(FD->getType());
17521   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17522     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17523     if (RDecl->getDefinition()) {
17524       // We check for copy constructors before constructors
17525       // because otherwise we'll never get complaints about
17526       // copy constructors.
17527 
17528       CXXSpecialMember member = CXXInvalid;
17529       // We're required to check for any non-trivial constructors. Since the
17530       // implicit default constructor is suppressed if there are any
17531       // user-declared constructors, we just need to check that there is a
17532       // trivial default constructor and a trivial copy constructor. (We don't
17533       // worry about move constructors here, since this is a C++98 check.)
17534       if (RDecl->hasNonTrivialCopyConstructor())
17535         member = CXXCopyConstructor;
17536       else if (!RDecl->hasTrivialDefaultConstructor())
17537         member = CXXDefaultConstructor;
17538       else if (RDecl->hasNonTrivialCopyAssignment())
17539         member = CXXCopyAssignment;
17540       else if (RDecl->hasNonTrivialDestructor())
17541         member = CXXDestructor;
17542 
17543       if (member != CXXInvalid) {
17544         if (!getLangOpts().CPlusPlus11 &&
17545             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17546           // Objective-C++ ARC: it is an error to have a non-trivial field of
17547           // a union. However, system headers in Objective-C programs
17548           // occasionally have Objective-C lifetime objects within unions,
17549           // and rather than cause the program to fail, we make those
17550           // members unavailable.
17551           SourceLocation Loc = FD->getLocation();
17552           if (getSourceManager().isInSystemHeader(Loc)) {
17553             if (!FD->hasAttr<UnavailableAttr>())
17554               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17555                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17556             return false;
17557           }
17558         }
17559 
17560         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17561                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17562                diag::err_illegal_union_or_anon_struct_member)
17563           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17564         DiagnoseNontrivial(RDecl, member);
17565         return !getLangOpts().CPlusPlus11;
17566       }
17567     }
17568   }
17569 
17570   return false;
17571 }
17572 
17573 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17574 ///  AST enum value.
17575 static ObjCIvarDecl::AccessControl
17576 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17577   switch (ivarVisibility) {
17578   default: llvm_unreachable("Unknown visitibility kind");
17579   case tok::objc_private: return ObjCIvarDecl::Private;
17580   case tok::objc_public: return ObjCIvarDecl::Public;
17581   case tok::objc_protected: return ObjCIvarDecl::Protected;
17582   case tok::objc_package: return ObjCIvarDecl::Package;
17583   }
17584 }
17585 
17586 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17587 /// in order to create an IvarDecl object for it.
17588 Decl *Sema::ActOnIvar(Scope *S,
17589                                 SourceLocation DeclStart,
17590                                 Declarator &D, Expr *BitfieldWidth,
17591                                 tok::ObjCKeywordKind Visibility) {
17592 
17593   IdentifierInfo *II = D.getIdentifier();
17594   Expr *BitWidth = (Expr*)BitfieldWidth;
17595   SourceLocation Loc = DeclStart;
17596   if (II) Loc = D.getIdentifierLoc();
17597 
17598   // FIXME: Unnamed fields can be handled in various different ways, for
17599   // example, unnamed unions inject all members into the struct namespace!
17600 
17601   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17602   QualType T = TInfo->getType();
17603 
17604   if (BitWidth) {
17605     // 6.7.2.1p3, 6.7.2.1p4
17606     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17607     if (!BitWidth)
17608       D.setInvalidType();
17609   } else {
17610     // Not a bitfield.
17611 
17612     // validate II.
17613 
17614   }
17615   if (T->isReferenceType()) {
17616     Diag(Loc, diag::err_ivar_reference_type);
17617     D.setInvalidType();
17618   }
17619   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17620   // than a variably modified type.
17621   else if (T->isVariablyModifiedType()) {
17622     if (!tryToFixVariablyModifiedVarType(
17623             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17624       D.setInvalidType();
17625   }
17626 
17627   // Get the visibility (access control) for this ivar.
17628   ObjCIvarDecl::AccessControl ac =
17629     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17630                                         : ObjCIvarDecl::None;
17631   // Must set ivar's DeclContext to its enclosing interface.
17632   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17633   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17634     return nullptr;
17635   ObjCContainerDecl *EnclosingContext;
17636   if (ObjCImplementationDecl *IMPDecl =
17637       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17638     if (LangOpts.ObjCRuntime.isFragile()) {
17639     // Case of ivar declared in an implementation. Context is that of its class.
17640       EnclosingContext = IMPDecl->getClassInterface();
17641       assert(EnclosingContext && "Implementation has no class interface!");
17642     }
17643     else
17644       EnclosingContext = EnclosingDecl;
17645   } else {
17646     if (ObjCCategoryDecl *CDecl =
17647         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17648       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17649         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17650         return nullptr;
17651       }
17652     }
17653     EnclosingContext = EnclosingDecl;
17654   }
17655 
17656   // Construct the decl.
17657   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17658                                              DeclStart, Loc, II, T,
17659                                              TInfo, ac, (Expr *)BitfieldWidth);
17660 
17661   if (II) {
17662     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17663                                            ForVisibleRedeclaration);
17664     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17665         && !isa<TagDecl>(PrevDecl)) {
17666       Diag(Loc, diag::err_duplicate_member) << II;
17667       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17668       NewID->setInvalidDecl();
17669     }
17670   }
17671 
17672   // Process attributes attached to the ivar.
17673   ProcessDeclAttributes(S, NewID, D);
17674 
17675   if (D.isInvalidType())
17676     NewID->setInvalidDecl();
17677 
17678   // In ARC, infer 'retaining' for ivars of retainable type.
17679   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17680     NewID->setInvalidDecl();
17681 
17682   if (D.getDeclSpec().isModulePrivateSpecified())
17683     NewID->setModulePrivate();
17684 
17685   if (II) {
17686     // FIXME: When interfaces are DeclContexts, we'll need to add
17687     // these to the interface.
17688     S->AddDecl(NewID);
17689     IdResolver.AddDecl(NewID);
17690   }
17691 
17692   if (LangOpts.ObjCRuntime.isNonFragile() &&
17693       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17694     Diag(Loc, diag::warn_ivars_in_interface);
17695 
17696   return NewID;
17697 }
17698 
17699 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17700 /// class and class extensions. For every class \@interface and class
17701 /// extension \@interface, if the last ivar is a bitfield of any type,
17702 /// then add an implicit `char :0` ivar to the end of that interface.
17703 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17704                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17705   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17706     return;
17707 
17708   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17709   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17710 
17711   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17712     return;
17713   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17714   if (!ID) {
17715     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17716       if (!CD->IsClassExtension())
17717         return;
17718     }
17719     // No need to add this to end of @implementation.
17720     else
17721       return;
17722   }
17723   // All conditions are met. Add a new bitfield to the tail end of ivars.
17724   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17725   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17726 
17727   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17728                               DeclLoc, DeclLoc, nullptr,
17729                               Context.CharTy,
17730                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17731                                                                DeclLoc),
17732                               ObjCIvarDecl::Private, BW,
17733                               true);
17734   AllIvarDecls.push_back(Ivar);
17735 }
17736 
17737 namespace {
17738 /// [class.dtor]p4:
17739 ///   At the end of the definition of a class, overload resolution is
17740 ///   performed among the prospective destructors declared in that class with
17741 ///   an empty argument list to select the destructor for the class, also
17742 ///   known as the selected destructor.
17743 ///
17744 /// We do the overload resolution here, then mark the selected constructor in the AST.
17745 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17746 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17747   if (!Record->hasUserDeclaredDestructor()) {
17748     return;
17749   }
17750 
17751   SourceLocation Loc = Record->getLocation();
17752   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17753 
17754   for (auto *Decl : Record->decls()) {
17755     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17756       if (DD->isInvalidDecl())
17757         continue;
17758       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17759                              OCS);
17760       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17761     }
17762   }
17763 
17764   if (OCS.empty()) {
17765     return;
17766   }
17767   OverloadCandidateSet::iterator Best;
17768   unsigned Msg = 0;
17769   OverloadCandidateDisplayKind DisplayKind;
17770 
17771   switch (OCS.BestViableFunction(S, Loc, Best)) {
17772   case OR_Success:
17773   case OR_Deleted:
17774     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17775     break;
17776 
17777   case OR_Ambiguous:
17778     Msg = diag::err_ambiguous_destructor;
17779     DisplayKind = OCD_AmbiguousCandidates;
17780     break;
17781 
17782   case OR_No_Viable_Function:
17783     Msg = diag::err_no_viable_destructor;
17784     DisplayKind = OCD_AllCandidates;
17785     break;
17786   }
17787 
17788   if (Msg) {
17789     // OpenCL have got their own thing going with destructors. It's slightly broken,
17790     // but we allow it.
17791     if (!S.LangOpts.OpenCL) {
17792       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17793       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17794       Record->setInvalidDecl();
17795     }
17796     // It's a bit hacky: At this point we've raised an error but we want the
17797     // rest of the compiler to continue somehow working. However almost
17798     // everything we'll try to do with the class will depend on there being a
17799     // destructor. So let's pretend the first one is selected and hope for the
17800     // best.
17801     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17802   }
17803 }
17804 } // namespace
17805 
17806 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17807                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17808                        SourceLocation RBrac,
17809                        const ParsedAttributesView &Attrs) {
17810   assert(EnclosingDecl && "missing record or interface decl");
17811 
17812   // If this is an Objective-C @implementation or category and we have
17813   // new fields here we should reset the layout of the interface since
17814   // it will now change.
17815   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17816     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17817     switch (DC->getKind()) {
17818     default: break;
17819     case Decl::ObjCCategory:
17820       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17821       break;
17822     case Decl::ObjCImplementation:
17823       Context.
17824         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17825       break;
17826     }
17827   }
17828 
17829   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17830   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17831 
17832   if (CXXRecord && !CXXRecord->isDependentType())
17833     ComputeSelectedDestructor(*this, CXXRecord);
17834 
17835   // Start counting up the number of named members; make sure to include
17836   // members of anonymous structs and unions in the total.
17837   unsigned NumNamedMembers = 0;
17838   if (Record) {
17839     for (const auto *I : Record->decls()) {
17840       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17841         if (IFD->getDeclName())
17842           ++NumNamedMembers;
17843     }
17844   }
17845 
17846   // Verify that all the fields are okay.
17847   SmallVector<FieldDecl*, 32> RecFields;
17848 
17849   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17850        i != end; ++i) {
17851     FieldDecl *FD = cast<FieldDecl>(*i);
17852 
17853     // Get the type for the field.
17854     const Type *FDTy = FD->getType().getTypePtr();
17855 
17856     if (!FD->isAnonymousStructOrUnion()) {
17857       // Remember all fields written by the user.
17858       RecFields.push_back(FD);
17859     }
17860 
17861     // If the field is already invalid for some reason, don't emit more
17862     // diagnostics about it.
17863     if (FD->isInvalidDecl()) {
17864       EnclosingDecl->setInvalidDecl();
17865       continue;
17866     }
17867 
17868     // C99 6.7.2.1p2:
17869     //   A structure or union shall not contain a member with
17870     //   incomplete or function type (hence, a structure shall not
17871     //   contain an instance of itself, but may contain a pointer to
17872     //   an instance of itself), except that the last member of a
17873     //   structure with more than one named member may have incomplete
17874     //   array type; such a structure (and any union containing,
17875     //   possibly recursively, a member that is such a structure)
17876     //   shall not be a member of a structure or an element of an
17877     //   array.
17878     bool IsLastField = (i + 1 == Fields.end());
17879     if (FDTy->isFunctionType()) {
17880       // Field declared as a function.
17881       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17882         << FD->getDeclName();
17883       FD->setInvalidDecl();
17884       EnclosingDecl->setInvalidDecl();
17885       continue;
17886     } else if (FDTy->isIncompleteArrayType() &&
17887                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17888       if (Record) {
17889         // Flexible array member.
17890         // Microsoft and g++ is more permissive regarding flexible array.
17891         // It will accept flexible array in union and also
17892         // as the sole element of a struct/class.
17893         unsigned DiagID = 0;
17894         if (!Record->isUnion() && !IsLastField) {
17895           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17896             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17897           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17898           FD->setInvalidDecl();
17899           EnclosingDecl->setInvalidDecl();
17900           continue;
17901         } else if (Record->isUnion())
17902           DiagID = getLangOpts().MicrosoftExt
17903                        ? diag::ext_flexible_array_union_ms
17904                        : getLangOpts().CPlusPlus
17905                              ? diag::ext_flexible_array_union_gnu
17906                              : diag::err_flexible_array_union;
17907         else if (NumNamedMembers < 1)
17908           DiagID = getLangOpts().MicrosoftExt
17909                        ? diag::ext_flexible_array_empty_aggregate_ms
17910                        : getLangOpts().CPlusPlus
17911                              ? diag::ext_flexible_array_empty_aggregate_gnu
17912                              : diag::err_flexible_array_empty_aggregate;
17913 
17914         if (DiagID)
17915           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17916                                           << Record->getTagKind();
17917         // While the layout of types that contain virtual bases is not specified
17918         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17919         // virtual bases after the derived members.  This would make a flexible
17920         // array member declared at the end of an object not adjacent to the end
17921         // of the type.
17922         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17923           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17924               << FD->getDeclName() << Record->getTagKind();
17925         if (!getLangOpts().C99)
17926           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17927             << FD->getDeclName() << Record->getTagKind();
17928 
17929         // If the element type has a non-trivial destructor, we would not
17930         // implicitly destroy the elements, so disallow it for now.
17931         //
17932         // FIXME: GCC allows this. We should probably either implicitly delete
17933         // the destructor of the containing class, or just allow this.
17934         QualType BaseElem = Context.getBaseElementType(FD->getType());
17935         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17936           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17937             << FD->getDeclName() << FD->getType();
17938           FD->setInvalidDecl();
17939           EnclosingDecl->setInvalidDecl();
17940           continue;
17941         }
17942         // Okay, we have a legal flexible array member at the end of the struct.
17943         Record->setHasFlexibleArrayMember(true);
17944       } else {
17945         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17946         // unless they are followed by another ivar. That check is done
17947         // elsewhere, after synthesized ivars are known.
17948       }
17949     } else if (!FDTy->isDependentType() &&
17950                RequireCompleteSizedType(
17951                    FD->getLocation(), FD->getType(),
17952                    diag::err_field_incomplete_or_sizeless)) {
17953       // Incomplete type
17954       FD->setInvalidDecl();
17955       EnclosingDecl->setInvalidDecl();
17956       continue;
17957     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17958       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17959         // A type which contains a flexible array member is considered to be a
17960         // flexible array member.
17961         Record->setHasFlexibleArrayMember(true);
17962         if (!Record->isUnion()) {
17963           // If this is a struct/class and this is not the last element, reject
17964           // it.  Note that GCC supports variable sized arrays in the middle of
17965           // structures.
17966           if (!IsLastField)
17967             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17968               << FD->getDeclName() << FD->getType();
17969           else {
17970             // We support flexible arrays at the end of structs in
17971             // other structs as an extension.
17972             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17973               << FD->getDeclName();
17974           }
17975         }
17976       }
17977       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17978           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17979                                  diag::err_abstract_type_in_decl,
17980                                  AbstractIvarType)) {
17981         // Ivars can not have abstract class types
17982         FD->setInvalidDecl();
17983       }
17984       if (Record && FDTTy->getDecl()->hasObjectMember())
17985         Record->setHasObjectMember(true);
17986       if (Record && FDTTy->getDecl()->hasVolatileMember())
17987         Record->setHasVolatileMember(true);
17988     } else if (FDTy->isObjCObjectType()) {
17989       /// A field cannot be an Objective-c object
17990       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17991         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17992       QualType T = Context.getObjCObjectPointerType(FD->getType());
17993       FD->setType(T);
17994     } else if (Record && Record->isUnion() &&
17995                FD->getType().hasNonTrivialObjCLifetime() &&
17996                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17997                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17998                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17999                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18000       // For backward compatibility, fields of C unions declared in system
18001       // headers that have non-trivial ObjC ownership qualifications are marked
18002       // as unavailable unless the qualifier is explicit and __strong. This can
18003       // break ABI compatibility between programs compiled with ARC and MRR, but
18004       // is a better option than rejecting programs using those unions under
18005       // ARC.
18006       FD->addAttr(UnavailableAttr::CreateImplicit(
18007           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18008           FD->getLocation()));
18009     } else if (getLangOpts().ObjC &&
18010                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18011                !Record->hasObjectMember()) {
18012       if (FD->getType()->isObjCObjectPointerType() ||
18013           FD->getType().isObjCGCStrong())
18014         Record->setHasObjectMember(true);
18015       else if (Context.getAsArrayType(FD->getType())) {
18016         QualType BaseType = Context.getBaseElementType(FD->getType());
18017         if (BaseType->isRecordType() &&
18018             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18019           Record->setHasObjectMember(true);
18020         else if (BaseType->isObjCObjectPointerType() ||
18021                  BaseType.isObjCGCStrong())
18022                Record->setHasObjectMember(true);
18023       }
18024     }
18025 
18026     if (Record && !getLangOpts().CPlusPlus &&
18027         !shouldIgnoreForRecordTriviality(FD)) {
18028       QualType FT = FD->getType();
18029       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18030         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18031         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18032             Record->isUnion())
18033           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18034       }
18035       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18036       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18037         Record->setNonTrivialToPrimitiveCopy(true);
18038         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18039           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18040       }
18041       if (FT.isDestructedType()) {
18042         Record->setNonTrivialToPrimitiveDestroy(true);
18043         Record->setParamDestroyedInCallee(true);
18044         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18045           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18046       }
18047 
18048       if (const auto *RT = FT->getAs<RecordType>()) {
18049         if (RT->getDecl()->getArgPassingRestrictions() ==
18050             RecordDecl::APK_CanNeverPassInRegs)
18051           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18052       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18053         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18054     }
18055 
18056     if (Record && FD->getType().isVolatileQualified())
18057       Record->setHasVolatileMember(true);
18058     // Keep track of the number of named members.
18059     if (FD->getIdentifier())
18060       ++NumNamedMembers;
18061   }
18062 
18063   // Okay, we successfully defined 'Record'.
18064   if (Record) {
18065     bool Completed = false;
18066     if (CXXRecord) {
18067       if (!CXXRecord->isInvalidDecl()) {
18068         // Set access bits correctly on the directly-declared conversions.
18069         for (CXXRecordDecl::conversion_iterator
18070                I = CXXRecord->conversion_begin(),
18071                E = CXXRecord->conversion_end(); I != E; ++I)
18072           I.setAccess((*I)->getAccess());
18073       }
18074 
18075       // Add any implicitly-declared members to this class.
18076       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18077 
18078       if (!CXXRecord->isDependentType()) {
18079         if (!CXXRecord->isInvalidDecl()) {
18080           // If we have virtual base classes, we may end up finding multiple
18081           // final overriders for a given virtual function. Check for this
18082           // problem now.
18083           if (CXXRecord->getNumVBases()) {
18084             CXXFinalOverriderMap FinalOverriders;
18085             CXXRecord->getFinalOverriders(FinalOverriders);
18086 
18087             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18088                                              MEnd = FinalOverriders.end();
18089                  M != MEnd; ++M) {
18090               for (OverridingMethods::iterator SO = M->second.begin(),
18091                                             SOEnd = M->second.end();
18092                    SO != SOEnd; ++SO) {
18093                 assert(SO->second.size() > 0 &&
18094                        "Virtual function without overriding functions?");
18095                 if (SO->second.size() == 1)
18096                   continue;
18097 
18098                 // C++ [class.virtual]p2:
18099                 //   In a derived class, if a virtual member function of a base
18100                 //   class subobject has more than one final overrider the
18101                 //   program is ill-formed.
18102                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18103                   << (const NamedDecl *)M->first << Record;
18104                 Diag(M->first->getLocation(),
18105                      diag::note_overridden_virtual_function);
18106                 for (OverridingMethods::overriding_iterator
18107                           OM = SO->second.begin(),
18108                        OMEnd = SO->second.end();
18109                      OM != OMEnd; ++OM)
18110                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18111                     << (const NamedDecl *)M->first << OM->Method->getParent();
18112 
18113                 Record->setInvalidDecl();
18114               }
18115             }
18116             CXXRecord->completeDefinition(&FinalOverriders);
18117             Completed = true;
18118           }
18119         }
18120       }
18121     }
18122 
18123     if (!Completed)
18124       Record->completeDefinition();
18125 
18126     // Handle attributes before checking the layout.
18127     ProcessDeclAttributeList(S, Record, Attrs);
18128 
18129     // Check to see if a FieldDecl is a pointer to a function.
18130     auto IsFunctionPointer = [&](const Decl *D) {
18131       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18132       if (!FD)
18133         return false;
18134       QualType FieldType = FD->getType().getDesugaredType(Context);
18135       if (isa<PointerType>(FieldType)) {
18136         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18137         return PointeeType.getDesugaredType(Context)->isFunctionType();
18138       }
18139       return false;
18140     };
18141 
18142     // Maybe randomize the record's decls. We automatically randomize a record
18143     // of function pointers, unless it has the "no_randomize_layout" attribute.
18144     if (!getLangOpts().CPlusPlus &&
18145         (Record->hasAttr<RandomizeLayoutAttr>() ||
18146          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18147           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18148         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18149         !Record->isRandomized()) {
18150       SmallVector<Decl *, 32> NewDeclOrdering;
18151       if (randstruct::randomizeStructureLayout(Context, Record,
18152                                                NewDeclOrdering))
18153         Record->reorderDecls(NewDeclOrdering);
18154     }
18155 
18156     // We may have deferred checking for a deleted destructor. Check now.
18157     if (CXXRecord) {
18158       auto *Dtor = CXXRecord->getDestructor();
18159       if (Dtor && Dtor->isImplicit() &&
18160           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18161         CXXRecord->setImplicitDestructorIsDeleted();
18162         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18163       }
18164     }
18165 
18166     if (Record->hasAttrs()) {
18167       CheckAlignasUnderalignment(Record);
18168 
18169       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18170         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18171                                            IA->getRange(), IA->getBestCase(),
18172                                            IA->getInheritanceModel());
18173     }
18174 
18175     // Check if the structure/union declaration is a type that can have zero
18176     // size in C. For C this is a language extension, for C++ it may cause
18177     // compatibility problems.
18178     bool CheckForZeroSize;
18179     if (!getLangOpts().CPlusPlus) {
18180       CheckForZeroSize = true;
18181     } else {
18182       // For C++ filter out types that cannot be referenced in C code.
18183       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18184       CheckForZeroSize =
18185           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18186           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18187           CXXRecord->isCLike();
18188     }
18189     if (CheckForZeroSize) {
18190       bool ZeroSize = true;
18191       bool IsEmpty = true;
18192       unsigned NonBitFields = 0;
18193       for (RecordDecl::field_iterator I = Record->field_begin(),
18194                                       E = Record->field_end();
18195            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18196         IsEmpty = false;
18197         if (I->isUnnamedBitfield()) {
18198           if (!I->isZeroLengthBitField(Context))
18199             ZeroSize = false;
18200         } else {
18201           ++NonBitFields;
18202           QualType FieldType = I->getType();
18203           if (FieldType->isIncompleteType() ||
18204               !Context.getTypeSizeInChars(FieldType).isZero())
18205             ZeroSize = false;
18206         }
18207       }
18208 
18209       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18210       // allowed in C++, but warn if its declaration is inside
18211       // extern "C" block.
18212       if (ZeroSize) {
18213         Diag(RecLoc, getLangOpts().CPlusPlus ?
18214                          diag::warn_zero_size_struct_union_in_extern_c :
18215                          diag::warn_zero_size_struct_union_compat)
18216           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18217       }
18218 
18219       // Structs without named members are extension in C (C99 6.7.2.1p7),
18220       // but are accepted by GCC.
18221       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18222         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18223                                diag::ext_no_named_members_in_struct_union)
18224           << Record->isUnion();
18225       }
18226     }
18227   } else {
18228     ObjCIvarDecl **ClsFields =
18229       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18230     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18231       ID->setEndOfDefinitionLoc(RBrac);
18232       // Add ivar's to class's DeclContext.
18233       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18234         ClsFields[i]->setLexicalDeclContext(ID);
18235         ID->addDecl(ClsFields[i]);
18236       }
18237       // Must enforce the rule that ivars in the base classes may not be
18238       // duplicates.
18239       if (ID->getSuperClass())
18240         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18241     } else if (ObjCImplementationDecl *IMPDecl =
18242                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18243       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18244       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18245         // Ivar declared in @implementation never belongs to the implementation.
18246         // Only it is in implementation's lexical context.
18247         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18248       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18249       IMPDecl->setIvarLBraceLoc(LBrac);
18250       IMPDecl->setIvarRBraceLoc(RBrac);
18251     } else if (ObjCCategoryDecl *CDecl =
18252                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18253       // case of ivars in class extension; all other cases have been
18254       // reported as errors elsewhere.
18255       // FIXME. Class extension does not have a LocEnd field.
18256       // CDecl->setLocEnd(RBrac);
18257       // Add ivar's to class extension's DeclContext.
18258       // Diagnose redeclaration of private ivars.
18259       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18260       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18261         if (IDecl) {
18262           if (const ObjCIvarDecl *ClsIvar =
18263               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18264             Diag(ClsFields[i]->getLocation(),
18265                  diag::err_duplicate_ivar_declaration);
18266             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18267             continue;
18268           }
18269           for (const auto *Ext : IDecl->known_extensions()) {
18270             if (const ObjCIvarDecl *ClsExtIvar
18271                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18272               Diag(ClsFields[i]->getLocation(),
18273                    diag::err_duplicate_ivar_declaration);
18274               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18275               continue;
18276             }
18277           }
18278         }
18279         ClsFields[i]->setLexicalDeclContext(CDecl);
18280         CDecl->addDecl(ClsFields[i]);
18281       }
18282       CDecl->setIvarLBraceLoc(LBrac);
18283       CDecl->setIvarRBraceLoc(RBrac);
18284     }
18285   }
18286 }
18287 
18288 /// Determine whether the given integral value is representable within
18289 /// the given type T.
18290 static bool isRepresentableIntegerValue(ASTContext &Context,
18291                                         llvm::APSInt &Value,
18292                                         QualType T) {
18293   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18294          "Integral type required!");
18295   unsigned BitWidth = Context.getIntWidth(T);
18296 
18297   if (Value.isUnsigned() || Value.isNonNegative()) {
18298     if (T->isSignedIntegerOrEnumerationType())
18299       --BitWidth;
18300     return Value.getActiveBits() <= BitWidth;
18301   }
18302   return Value.getMinSignedBits() <= BitWidth;
18303 }
18304 
18305 // Given an integral type, return the next larger integral type
18306 // (or a NULL type of no such type exists).
18307 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18308   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18309   // enum checking below.
18310   assert((T->isIntegralType(Context) ||
18311          T->isEnumeralType()) && "Integral type required!");
18312   const unsigned NumTypes = 4;
18313   QualType SignedIntegralTypes[NumTypes] = {
18314     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18315   };
18316   QualType UnsignedIntegralTypes[NumTypes] = {
18317     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18318     Context.UnsignedLongLongTy
18319   };
18320 
18321   unsigned BitWidth = Context.getTypeSize(T);
18322   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18323                                                         : UnsignedIntegralTypes;
18324   for (unsigned I = 0; I != NumTypes; ++I)
18325     if (Context.getTypeSize(Types[I]) > BitWidth)
18326       return Types[I];
18327 
18328   return QualType();
18329 }
18330 
18331 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18332                                           EnumConstantDecl *LastEnumConst,
18333                                           SourceLocation IdLoc,
18334                                           IdentifierInfo *Id,
18335                                           Expr *Val) {
18336   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18337   llvm::APSInt EnumVal(IntWidth);
18338   QualType EltTy;
18339 
18340   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18341     Val = nullptr;
18342 
18343   if (Val)
18344     Val = DefaultLvalueConversion(Val).get();
18345 
18346   if (Val) {
18347     if (Enum->isDependentType() || Val->isTypeDependent() ||
18348         Val->containsErrors())
18349       EltTy = Context.DependentTy;
18350     else {
18351       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18352       // underlying type, but do allow it in all other contexts.
18353       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18354         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18355         // constant-expression in the enumerator-definition shall be a converted
18356         // constant expression of the underlying type.
18357         EltTy = Enum->getIntegerType();
18358         ExprResult Converted =
18359           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18360                                            CCEK_Enumerator);
18361         if (Converted.isInvalid())
18362           Val = nullptr;
18363         else
18364           Val = Converted.get();
18365       } else if (!Val->isValueDependent() &&
18366                  !(Val =
18367                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18368                            .get())) {
18369         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18370       } else {
18371         if (Enum->isComplete()) {
18372           EltTy = Enum->getIntegerType();
18373 
18374           // In Obj-C and Microsoft mode, require the enumeration value to be
18375           // representable in the underlying type of the enumeration. In C++11,
18376           // we perform a non-narrowing conversion as part of converted constant
18377           // expression checking.
18378           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18379             if (Context.getTargetInfo()
18380                     .getTriple()
18381                     .isWindowsMSVCEnvironment()) {
18382               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18383             } else {
18384               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18385             }
18386           }
18387 
18388           // Cast to the underlying type.
18389           Val = ImpCastExprToType(Val, EltTy,
18390                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18391                                                          : CK_IntegralCast)
18392                     .get();
18393         } else if (getLangOpts().CPlusPlus) {
18394           // C++11 [dcl.enum]p5:
18395           //   If the underlying type is not fixed, the type of each enumerator
18396           //   is the type of its initializing value:
18397           //     - If an initializer is specified for an enumerator, the
18398           //       initializing value has the same type as the expression.
18399           EltTy = Val->getType();
18400         } else {
18401           // C99 6.7.2.2p2:
18402           //   The expression that defines the value of an enumeration constant
18403           //   shall be an integer constant expression that has a value
18404           //   representable as an int.
18405 
18406           // Complain if the value is not representable in an int.
18407           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18408             Diag(IdLoc, diag::ext_enum_value_not_int)
18409               << toString(EnumVal, 10) << Val->getSourceRange()
18410               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18411           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18412             // Force the type of the expression to 'int'.
18413             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18414           }
18415           EltTy = Val->getType();
18416         }
18417       }
18418     }
18419   }
18420 
18421   if (!Val) {
18422     if (Enum->isDependentType())
18423       EltTy = Context.DependentTy;
18424     else if (!LastEnumConst) {
18425       // C++0x [dcl.enum]p5:
18426       //   If the underlying type is not fixed, the type of each enumerator
18427       //   is the type of its initializing value:
18428       //     - If no initializer is specified for the first enumerator, the
18429       //       initializing value has an unspecified integral type.
18430       //
18431       // GCC uses 'int' for its unspecified integral type, as does
18432       // C99 6.7.2.2p3.
18433       if (Enum->isFixed()) {
18434         EltTy = Enum->getIntegerType();
18435       }
18436       else {
18437         EltTy = Context.IntTy;
18438       }
18439     } else {
18440       // Assign the last value + 1.
18441       EnumVal = LastEnumConst->getInitVal();
18442       ++EnumVal;
18443       EltTy = LastEnumConst->getType();
18444 
18445       // Check for overflow on increment.
18446       if (EnumVal < LastEnumConst->getInitVal()) {
18447         // C++0x [dcl.enum]p5:
18448         //   If the underlying type is not fixed, the type of each enumerator
18449         //   is the type of its initializing value:
18450         //
18451         //     - Otherwise the type of the initializing value is the same as
18452         //       the type of the initializing value of the preceding enumerator
18453         //       unless the incremented value is not representable in that type,
18454         //       in which case the type is an unspecified integral type
18455         //       sufficient to contain the incremented value. If no such type
18456         //       exists, the program is ill-formed.
18457         QualType T = getNextLargerIntegralType(Context, EltTy);
18458         if (T.isNull() || Enum->isFixed()) {
18459           // There is no integral type larger enough to represent this
18460           // value. Complain, then allow the value to wrap around.
18461           EnumVal = LastEnumConst->getInitVal();
18462           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18463           ++EnumVal;
18464           if (Enum->isFixed())
18465             // When the underlying type is fixed, this is ill-formed.
18466             Diag(IdLoc, diag::err_enumerator_wrapped)
18467               << toString(EnumVal, 10)
18468               << EltTy;
18469           else
18470             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18471               << toString(EnumVal, 10);
18472         } else {
18473           EltTy = T;
18474         }
18475 
18476         // Retrieve the last enumerator's value, extent that type to the
18477         // type that is supposed to be large enough to represent the incremented
18478         // value, then increment.
18479         EnumVal = LastEnumConst->getInitVal();
18480         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18481         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18482         ++EnumVal;
18483 
18484         // If we're not in C++, diagnose the overflow of enumerator values,
18485         // which in C99 means that the enumerator value is not representable in
18486         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18487         // permits enumerator values that are representable in some larger
18488         // integral type.
18489         if (!getLangOpts().CPlusPlus && !T.isNull())
18490           Diag(IdLoc, diag::warn_enum_value_overflow);
18491       } else if (!getLangOpts().CPlusPlus &&
18492                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18493         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18494         Diag(IdLoc, diag::ext_enum_value_not_int)
18495           << toString(EnumVal, 10) << 1;
18496       }
18497     }
18498   }
18499 
18500   if (!EltTy->isDependentType()) {
18501     // Make the enumerator value match the signedness and size of the
18502     // enumerator's type.
18503     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18504     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18505   }
18506 
18507   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18508                                   Val, EnumVal);
18509 }
18510 
18511 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18512                                                 SourceLocation IILoc) {
18513   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18514       !getLangOpts().CPlusPlus)
18515     return SkipBodyInfo();
18516 
18517   // We have an anonymous enum definition. Look up the first enumerator to
18518   // determine if we should merge the definition with an existing one and
18519   // skip the body.
18520   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18521                                          forRedeclarationInCurContext());
18522   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18523   if (!PrevECD)
18524     return SkipBodyInfo();
18525 
18526   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18527   NamedDecl *Hidden;
18528   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18529     SkipBodyInfo Skip;
18530     Skip.Previous = Hidden;
18531     return Skip;
18532   }
18533 
18534   return SkipBodyInfo();
18535 }
18536 
18537 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18538                               SourceLocation IdLoc, IdentifierInfo *Id,
18539                               const ParsedAttributesView &Attrs,
18540                               SourceLocation EqualLoc, Expr *Val) {
18541   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18542   EnumConstantDecl *LastEnumConst =
18543     cast_or_null<EnumConstantDecl>(lastEnumConst);
18544 
18545   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18546   // we find one that is.
18547   S = getNonFieldDeclScope(S);
18548 
18549   // Verify that there isn't already something declared with this name in this
18550   // scope.
18551   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18552   LookupName(R, S);
18553   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18554 
18555   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18556     // Maybe we will complain about the shadowed template parameter.
18557     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18558     // Just pretend that we didn't see the previous declaration.
18559     PrevDecl = nullptr;
18560   }
18561 
18562   // C++ [class.mem]p15:
18563   // If T is the name of a class, then each of the following shall have a name
18564   // different from T:
18565   // - every enumerator of every member of class T that is an unscoped
18566   // enumerated type
18567   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18568     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18569                             DeclarationNameInfo(Id, IdLoc));
18570 
18571   EnumConstantDecl *New =
18572     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18573   if (!New)
18574     return nullptr;
18575 
18576   if (PrevDecl) {
18577     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18578       // Check for other kinds of shadowing not already handled.
18579       CheckShadow(New, PrevDecl, R);
18580     }
18581 
18582     // When in C++, we may get a TagDecl with the same name; in this case the
18583     // enum constant will 'hide' the tag.
18584     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18585            "Received TagDecl when not in C++!");
18586     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18587       if (isa<EnumConstantDecl>(PrevDecl))
18588         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18589       else
18590         Diag(IdLoc, diag::err_redefinition) << Id;
18591       notePreviousDefinition(PrevDecl, IdLoc);
18592       return nullptr;
18593     }
18594   }
18595 
18596   // Process attributes.
18597   ProcessDeclAttributeList(S, New, Attrs);
18598   AddPragmaAttributes(S, New);
18599 
18600   // Register this decl in the current scope stack.
18601   New->setAccess(TheEnumDecl->getAccess());
18602   PushOnScopeChains(New, S);
18603 
18604   ActOnDocumentableDecl(New);
18605 
18606   return New;
18607 }
18608 
18609 // Returns true when the enum initial expression does not trigger the
18610 // duplicate enum warning.  A few common cases are exempted as follows:
18611 // Element2 = Element1
18612 // Element2 = Element1 + 1
18613 // Element2 = Element1 - 1
18614 // Where Element2 and Element1 are from the same enum.
18615 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18616   Expr *InitExpr = ECD->getInitExpr();
18617   if (!InitExpr)
18618     return true;
18619   InitExpr = InitExpr->IgnoreImpCasts();
18620 
18621   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18622     if (!BO->isAdditiveOp())
18623       return true;
18624     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18625     if (!IL)
18626       return true;
18627     if (IL->getValue() != 1)
18628       return true;
18629 
18630     InitExpr = BO->getLHS();
18631   }
18632 
18633   // This checks if the elements are from the same enum.
18634   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18635   if (!DRE)
18636     return true;
18637 
18638   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18639   if (!EnumConstant)
18640     return true;
18641 
18642   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18643       Enum)
18644     return true;
18645 
18646   return false;
18647 }
18648 
18649 // Emits a warning when an element is implicitly set a value that
18650 // a previous element has already been set to.
18651 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18652                                         EnumDecl *Enum, QualType EnumType) {
18653   // Avoid anonymous enums
18654   if (!Enum->getIdentifier())
18655     return;
18656 
18657   // Only check for small enums.
18658   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18659     return;
18660 
18661   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18662     return;
18663 
18664   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18665   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18666 
18667   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18668 
18669   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18670   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18671 
18672   // Use int64_t as a key to avoid needing special handling for map keys.
18673   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18674     llvm::APSInt Val = D->getInitVal();
18675     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18676   };
18677 
18678   DuplicatesVector DupVector;
18679   ValueToVectorMap EnumMap;
18680 
18681   // Populate the EnumMap with all values represented by enum constants without
18682   // an initializer.
18683   for (auto *Element : Elements) {
18684     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18685 
18686     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18687     // this constant.  Skip this enum since it may be ill-formed.
18688     if (!ECD) {
18689       return;
18690     }
18691 
18692     // Constants with initalizers are handled in the next loop.
18693     if (ECD->getInitExpr())
18694       continue;
18695 
18696     // Duplicate values are handled in the next loop.
18697     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18698   }
18699 
18700   if (EnumMap.size() == 0)
18701     return;
18702 
18703   // Create vectors for any values that has duplicates.
18704   for (auto *Element : Elements) {
18705     // The last loop returned if any constant was null.
18706     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18707     if (!ValidDuplicateEnum(ECD, Enum))
18708       continue;
18709 
18710     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18711     if (Iter == EnumMap.end())
18712       continue;
18713 
18714     DeclOrVector& Entry = Iter->second;
18715     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18716       // Ensure constants are different.
18717       if (D == ECD)
18718         continue;
18719 
18720       // Create new vector and push values onto it.
18721       auto Vec = std::make_unique<ECDVector>();
18722       Vec->push_back(D);
18723       Vec->push_back(ECD);
18724 
18725       // Update entry to point to the duplicates vector.
18726       Entry = Vec.get();
18727 
18728       // Store the vector somewhere we can consult later for quick emission of
18729       // diagnostics.
18730       DupVector.emplace_back(std::move(Vec));
18731       continue;
18732     }
18733 
18734     ECDVector *Vec = Entry.get<ECDVector*>();
18735     // Make sure constants are not added more than once.
18736     if (*Vec->begin() == ECD)
18737       continue;
18738 
18739     Vec->push_back(ECD);
18740   }
18741 
18742   // Emit diagnostics.
18743   for (const auto &Vec : DupVector) {
18744     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18745 
18746     // Emit warning for one enum constant.
18747     auto *FirstECD = Vec->front();
18748     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18749       << FirstECD << toString(FirstECD->getInitVal(), 10)
18750       << FirstECD->getSourceRange();
18751 
18752     // Emit one note for each of the remaining enum constants with
18753     // the same value.
18754     for (auto *ECD : llvm::drop_begin(*Vec))
18755       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18756         << ECD << toString(ECD->getInitVal(), 10)
18757         << ECD->getSourceRange();
18758   }
18759 }
18760 
18761 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18762                              bool AllowMask) const {
18763   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18764   assert(ED->isCompleteDefinition() && "expected enum definition");
18765 
18766   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18767   llvm::APInt &FlagBits = R.first->second;
18768 
18769   if (R.second) {
18770     for (auto *E : ED->enumerators()) {
18771       const auto &EVal = E->getInitVal();
18772       // Only single-bit enumerators introduce new flag values.
18773       if (EVal.isPowerOf2())
18774         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18775     }
18776   }
18777 
18778   // A value is in a flag enum if either its bits are a subset of the enum's
18779   // flag bits (the first condition) or we are allowing masks and the same is
18780   // true of its complement (the second condition). When masks are allowed, we
18781   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18782   //
18783   // While it's true that any value could be used as a mask, the assumption is
18784   // that a mask will have all of the insignificant bits set. Anything else is
18785   // likely a logic error.
18786   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18787   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18788 }
18789 
18790 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18791                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18792                          const ParsedAttributesView &Attrs) {
18793   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18794   QualType EnumType = Context.getTypeDeclType(Enum);
18795 
18796   ProcessDeclAttributeList(S, Enum, Attrs);
18797 
18798   if (Enum->isDependentType()) {
18799     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18800       EnumConstantDecl *ECD =
18801         cast_or_null<EnumConstantDecl>(Elements[i]);
18802       if (!ECD) continue;
18803 
18804       ECD->setType(EnumType);
18805     }
18806 
18807     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18808     return;
18809   }
18810 
18811   // TODO: If the result value doesn't fit in an int, it must be a long or long
18812   // long value.  ISO C does not support this, but GCC does as an extension,
18813   // emit a warning.
18814   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18815   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18816   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18817 
18818   // Verify that all the values are okay, compute the size of the values, and
18819   // reverse the list.
18820   unsigned NumNegativeBits = 0;
18821   unsigned NumPositiveBits = 0;
18822 
18823   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18824     EnumConstantDecl *ECD =
18825       cast_or_null<EnumConstantDecl>(Elements[i]);
18826     if (!ECD) continue;  // Already issued a diagnostic.
18827 
18828     const llvm::APSInt &InitVal = ECD->getInitVal();
18829 
18830     // Keep track of the size of positive and negative values.
18831     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18832       NumPositiveBits = std::max(NumPositiveBits,
18833                                  (unsigned)InitVal.getActiveBits());
18834     else
18835       NumNegativeBits = std::max(NumNegativeBits,
18836                                  (unsigned)InitVal.getMinSignedBits());
18837   }
18838 
18839   // Figure out the type that should be used for this enum.
18840   QualType BestType;
18841   unsigned BestWidth;
18842 
18843   // C++0x N3000 [conv.prom]p3:
18844   //   An rvalue of an unscoped enumeration type whose underlying
18845   //   type is not fixed can be converted to an rvalue of the first
18846   //   of the following types that can represent all the values of
18847   //   the enumeration: int, unsigned int, long int, unsigned long
18848   //   int, long long int, or unsigned long long int.
18849   // C99 6.4.4.3p2:
18850   //   An identifier declared as an enumeration constant has type int.
18851   // The C99 rule is modified by a gcc extension
18852   QualType BestPromotionType;
18853 
18854   bool Packed = Enum->hasAttr<PackedAttr>();
18855   // -fshort-enums is the equivalent to specifying the packed attribute on all
18856   // enum definitions.
18857   if (LangOpts.ShortEnums)
18858     Packed = true;
18859 
18860   // If the enum already has a type because it is fixed or dictated by the
18861   // target, promote that type instead of analyzing the enumerators.
18862   if (Enum->isComplete()) {
18863     BestType = Enum->getIntegerType();
18864     if (BestType->isPromotableIntegerType())
18865       BestPromotionType = Context.getPromotedIntegerType(BestType);
18866     else
18867       BestPromotionType = BestType;
18868 
18869     BestWidth = Context.getIntWidth(BestType);
18870   }
18871   else if (NumNegativeBits) {
18872     // If there is a negative value, figure out the smallest integer type (of
18873     // int/long/longlong) that fits.
18874     // If it's packed, check also if it fits a char or a short.
18875     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18876       BestType = Context.SignedCharTy;
18877       BestWidth = CharWidth;
18878     } else if (Packed && NumNegativeBits <= ShortWidth &&
18879                NumPositiveBits < ShortWidth) {
18880       BestType = Context.ShortTy;
18881       BestWidth = ShortWidth;
18882     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18883       BestType = Context.IntTy;
18884       BestWidth = IntWidth;
18885     } else {
18886       BestWidth = Context.getTargetInfo().getLongWidth();
18887 
18888       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18889         BestType = Context.LongTy;
18890       } else {
18891         BestWidth = Context.getTargetInfo().getLongLongWidth();
18892 
18893         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18894           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18895         BestType = Context.LongLongTy;
18896       }
18897     }
18898     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18899   } else {
18900     // If there is no negative value, figure out the smallest type that fits
18901     // all of the enumerator values.
18902     // If it's packed, check also if it fits a char or a short.
18903     if (Packed && NumPositiveBits <= CharWidth) {
18904       BestType = Context.UnsignedCharTy;
18905       BestPromotionType = Context.IntTy;
18906       BestWidth = CharWidth;
18907     } else if (Packed && NumPositiveBits <= ShortWidth) {
18908       BestType = Context.UnsignedShortTy;
18909       BestPromotionType = Context.IntTy;
18910       BestWidth = ShortWidth;
18911     } else if (NumPositiveBits <= IntWidth) {
18912       BestType = Context.UnsignedIntTy;
18913       BestWidth = IntWidth;
18914       BestPromotionType
18915         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18916                            ? Context.UnsignedIntTy : Context.IntTy;
18917     } else if (NumPositiveBits <=
18918                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18919       BestType = Context.UnsignedLongTy;
18920       BestPromotionType
18921         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18922                            ? Context.UnsignedLongTy : Context.LongTy;
18923     } else {
18924       BestWidth = Context.getTargetInfo().getLongLongWidth();
18925       assert(NumPositiveBits <= BestWidth &&
18926              "How could an initializer get larger than ULL?");
18927       BestType = Context.UnsignedLongLongTy;
18928       BestPromotionType
18929         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18930                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18931     }
18932   }
18933 
18934   // Loop over all of the enumerator constants, changing their types to match
18935   // the type of the enum if needed.
18936   for (auto *D : Elements) {
18937     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18938     if (!ECD) continue;  // Already issued a diagnostic.
18939 
18940     // Standard C says the enumerators have int type, but we allow, as an
18941     // extension, the enumerators to be larger than int size.  If each
18942     // enumerator value fits in an int, type it as an int, otherwise type it the
18943     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18944     // that X has type 'int', not 'unsigned'.
18945 
18946     // Determine whether the value fits into an int.
18947     llvm::APSInt InitVal = ECD->getInitVal();
18948 
18949     // If it fits into an integer type, force it.  Otherwise force it to match
18950     // the enum decl type.
18951     QualType NewTy;
18952     unsigned NewWidth;
18953     bool NewSign;
18954     if (!getLangOpts().CPlusPlus &&
18955         !Enum->isFixed() &&
18956         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18957       NewTy = Context.IntTy;
18958       NewWidth = IntWidth;
18959       NewSign = true;
18960     } else if (ECD->getType() == BestType) {
18961       // Already the right type!
18962       if (getLangOpts().CPlusPlus)
18963         // C++ [dcl.enum]p4: Following the closing brace of an
18964         // enum-specifier, each enumerator has the type of its
18965         // enumeration.
18966         ECD->setType(EnumType);
18967       continue;
18968     } else {
18969       NewTy = BestType;
18970       NewWidth = BestWidth;
18971       NewSign = BestType->isSignedIntegerOrEnumerationType();
18972     }
18973 
18974     // Adjust the APSInt value.
18975     InitVal = InitVal.extOrTrunc(NewWidth);
18976     InitVal.setIsSigned(NewSign);
18977     ECD->setInitVal(InitVal);
18978 
18979     // Adjust the Expr initializer and type.
18980     if (ECD->getInitExpr() &&
18981         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18982       ECD->setInitExpr(ImplicitCastExpr::Create(
18983           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18984           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18985     if (getLangOpts().CPlusPlus)
18986       // C++ [dcl.enum]p4: Following the closing brace of an
18987       // enum-specifier, each enumerator has the type of its
18988       // enumeration.
18989       ECD->setType(EnumType);
18990     else
18991       ECD->setType(NewTy);
18992   }
18993 
18994   Enum->completeDefinition(BestType, BestPromotionType,
18995                            NumPositiveBits, NumNegativeBits);
18996 
18997   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18998 
18999   if (Enum->isClosedFlag()) {
19000     for (Decl *D : Elements) {
19001       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19002       if (!ECD) continue;  // Already issued a diagnostic.
19003 
19004       llvm::APSInt InitVal = ECD->getInitVal();
19005       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19006           !IsValueInFlagEnum(Enum, InitVal, true))
19007         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19008           << ECD << Enum;
19009     }
19010   }
19011 
19012   // Now that the enum type is defined, ensure it's not been underaligned.
19013   if (Enum->hasAttrs())
19014     CheckAlignasUnderalignment(Enum);
19015 }
19016 
19017 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19018                                   SourceLocation StartLoc,
19019                                   SourceLocation EndLoc) {
19020   StringLiteral *AsmString = cast<StringLiteral>(expr);
19021 
19022   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19023                                                    AsmString, StartLoc,
19024                                                    EndLoc);
19025   CurContext->addDecl(New);
19026   return New;
19027 }
19028 
19029 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19030                                       IdentifierInfo* AliasName,
19031                                       SourceLocation PragmaLoc,
19032                                       SourceLocation NameLoc,
19033                                       SourceLocation AliasNameLoc) {
19034   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19035                                          LookupOrdinaryName);
19036   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19037                            AttributeCommonInfo::AS_Pragma);
19038   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19039       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19040 
19041   // If a declaration that:
19042   // 1) declares a function or a variable
19043   // 2) has external linkage
19044   // already exists, add a label attribute to it.
19045   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19046     if (isDeclExternC(PrevDecl))
19047       PrevDecl->addAttr(Attr);
19048     else
19049       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19050           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19051   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19052   } else
19053     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19054 }
19055 
19056 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19057                              SourceLocation PragmaLoc,
19058                              SourceLocation NameLoc) {
19059   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19060 
19061   if (PrevDecl) {
19062     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19063   } else {
19064     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19065   }
19066 }
19067 
19068 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19069                                 IdentifierInfo* AliasName,
19070                                 SourceLocation PragmaLoc,
19071                                 SourceLocation NameLoc,
19072                                 SourceLocation AliasNameLoc) {
19073   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19074                                     LookupOrdinaryName);
19075   WeakInfo W = WeakInfo(Name, NameLoc);
19076 
19077   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19078     if (!PrevDecl->hasAttr<AliasAttr>())
19079       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19080         DeclApplyPragmaWeak(TUScope, ND, W);
19081   } else {
19082     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19083   }
19084 }
19085 
19086 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19087   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19088 }
19089 
19090 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19091                                                      bool Final) {
19092   assert(FD && "Expected non-null FunctionDecl");
19093 
19094   // SYCL functions can be template, so we check if they have appropriate
19095   // attribute prior to checking if it is a template.
19096   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19097     return FunctionEmissionStatus::Emitted;
19098 
19099   // Templates are emitted when they're instantiated.
19100   if (FD->isDependentContext())
19101     return FunctionEmissionStatus::TemplateDiscarded;
19102 
19103   // Check whether this function is an externally visible definition.
19104   auto IsEmittedForExternalSymbol = [this, FD]() {
19105     // We have to check the GVA linkage of the function's *definition* -- if we
19106     // only have a declaration, we don't know whether or not the function will
19107     // be emitted, because (say) the definition could include "inline".
19108     FunctionDecl *Def = FD->getDefinition();
19109 
19110     return Def && !isDiscardableGVALinkage(
19111                       getASTContext().GetGVALinkageForFunction(Def));
19112   };
19113 
19114   if (LangOpts.OpenMPIsDevice) {
19115     // In OpenMP device mode we will not emit host only functions, or functions
19116     // we don't need due to their linkage.
19117     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19118         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19119     // DevTy may be changed later by
19120     //  #pragma omp declare target to(*) device_type(*).
19121     // Therefore DevTy having no value does not imply host. The emission status
19122     // will be checked again at the end of compilation unit with Final = true.
19123     if (DevTy)
19124       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19125         return FunctionEmissionStatus::OMPDiscarded;
19126     // If we have an explicit value for the device type, or we are in a target
19127     // declare context, we need to emit all extern and used symbols.
19128     if (isInOpenMPDeclareTargetContext() || DevTy)
19129       if (IsEmittedForExternalSymbol())
19130         return FunctionEmissionStatus::Emitted;
19131     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19132     // we'll omit it.
19133     if (Final)
19134       return FunctionEmissionStatus::OMPDiscarded;
19135   } else if (LangOpts.OpenMP > 45) {
19136     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19137     // function. In 5.0, no_host was introduced which might cause a function to
19138     // be ommitted.
19139     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19140         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19141     if (DevTy)
19142       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19143         return FunctionEmissionStatus::OMPDiscarded;
19144   }
19145 
19146   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19147     return FunctionEmissionStatus::Emitted;
19148 
19149   if (LangOpts.CUDA) {
19150     // When compiling for device, host functions are never emitted.  Similarly,
19151     // when compiling for host, device and global functions are never emitted.
19152     // (Technically, we do emit a host-side stub for global functions, but this
19153     // doesn't count for our purposes here.)
19154     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19155     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19156       return FunctionEmissionStatus::CUDADiscarded;
19157     if (!LangOpts.CUDAIsDevice &&
19158         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19159       return FunctionEmissionStatus::CUDADiscarded;
19160 
19161     if (IsEmittedForExternalSymbol())
19162       return FunctionEmissionStatus::Emitted;
19163   }
19164 
19165   // Otherwise, the function is known-emitted if it's in our set of
19166   // known-emitted functions.
19167   return FunctionEmissionStatus::Unknown;
19168 }
19169 
19170 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19171   // Host-side references to a __global__ function refer to the stub, so the
19172   // function itself is never emitted and therefore should not be marked.
19173   // If we have host fn calls kernel fn calls host+device, the HD function
19174   // does not get instantiated on the host. We model this by omitting at the
19175   // call to the kernel from the callgraph. This ensures that, when compiling
19176   // for host, only HD functions actually called from the host get marked as
19177   // known-emitted.
19178   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19179          IdentifyCUDATarget(Callee) == CFT_Global;
19180 }
19181