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       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3915       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3916       return true;
3917     }
3918 
3919     // If we are merging two functions where only one of them has a prototype,
3920     // we may have enough information to decide to issue a diagnostic that the
3921     // function without a protoype will change behavior in C2x. This handles
3922     // cases like:
3923     //   void i(); void i(int j);
3924     //   void i(int j); void i();
3925     //   void i(); void i(int j) {}
3926     // See ActOnFinishFunctionBody() for other cases of the behavior change
3927     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3928     // type without a prototype.
3929     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3930         !New->isImplicit() && !Old->isImplicit()) {
3931       const FunctionDecl *WithProto, *WithoutProto;
3932       if (New->hasWrittenPrototype()) {
3933         WithProto = New;
3934         WithoutProto = Old;
3935       } else {
3936         WithProto = Old;
3937         WithoutProto = New;
3938       }
3939 
3940       if (WithProto->getNumParams() != 0) {
3941         // The function definition has parameters, so this will change
3942         // behavior in C2x.
3943         //
3944         // If we already warned about about the function without a prototype
3945         // being deprecated, add a note that it also changes behavior. If we
3946         // didn't warn about it being deprecated (because the diagnostic is
3947         // not enabled), warn now that it is deprecated and changes behavior.
3948         bool AddNote = false;
3949         if (Diags.isIgnored(diag::warn_strict_prototypes,
3950                             WithoutProto->getLocation())) {
3951           if (WithoutProto->getBuiltinID() == 0 &&
3952               !WithoutProto->isImplicit() &&
3953               SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(),
3954                                                   WithProto->getLocation())) {
3955             PartialDiagnostic PD =
3956                 PDiag(diag::warn_non_prototype_changes_behavior);
3957             if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) {
3958               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
3959                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
3960             }
3961             Diag(WithoutProto->getLocation(), PD);
3962           }
3963         } else {
3964           AddNote = true;
3965         }
3966 
3967         // Because the function with a prototype has parameters but a previous
3968         // declaration had none, the function with the prototype will also
3969         // change behavior in C2x.
3970         if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) {
3971           if (SourceMgr.isBeforeInTranslationUnit(
3972                   WithProto->getLocation(), WithoutProto->getLocation())) {
3973             // If the function with the prototype comes before the function
3974             // without the prototype, we only want to diagnose the one without
3975             // the prototype.
3976             Diag(WithoutProto->getLocation(),
3977                  diag::warn_non_prototype_changes_behavior);
3978           } else {
3979             // Otherwise, diagnose the one with the prototype, and potentially
3980             // attach a note to the one without a prototype if needed.
3981             Diag(WithProto->getLocation(),
3982                  diag::warn_non_prototype_changes_behavior);
3983             if (AddNote && WithoutProto->getBuiltinID() == 0)
3984               Diag(WithoutProto->getLocation(),
3985                    diag::note_func_decl_changes_behavior);
3986           }
3987         } else if (AddNote && WithoutProto->getBuiltinID() == 0 &&
3988                    !WithoutProto->isImplicit()) {
3989           // If we were supposed to add a note but the function with a
3990           // prototype is a builtin or was implicitly declared, which means we
3991           // have nothing to attach the note to, so we issue a warning instead.
3992           Diag(WithoutProto->getLocation(),
3993                diag::warn_non_prototype_changes_behavior);
3994         }
3995       }
3996     }
3997 
3998     if (Context.typesAreCompatible(OldQType, NewQType)) {
3999       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4000       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4001       const FunctionProtoType *OldProto = nullptr;
4002       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4003           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4004         // The old declaration provided a function prototype, but the
4005         // new declaration does not. Merge in the prototype.
4006         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4007         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4008         NewQType =
4009             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4010                                     OldProto->getExtProtoInfo());
4011         New->setType(NewQType);
4012         New->setHasInheritedPrototype();
4013 
4014         // Synthesize parameters with the same types.
4015         SmallVector<ParmVarDecl *, 16> Params;
4016         for (const auto &ParamType : OldProto->param_types()) {
4017           ParmVarDecl *Param = ParmVarDecl::Create(
4018               Context, New, SourceLocation(), SourceLocation(), nullptr,
4019               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4020           Param->setScopeInfo(0, Params.size());
4021           Param->setImplicit();
4022           Params.push_back(Param);
4023         }
4024 
4025         New->setParams(Params);
4026       }
4027 
4028       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4029     }
4030   }
4031 
4032   // Check if the function types are compatible when pointer size address
4033   // spaces are ignored.
4034   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4035     return false;
4036 
4037   // GNU C permits a K&R definition to follow a prototype declaration
4038   // if the declared types of the parameters in the K&R definition
4039   // match the types in the prototype declaration, even when the
4040   // promoted types of the parameters from the K&R definition differ
4041   // from the types in the prototype. GCC then keeps the types from
4042   // the prototype.
4043   //
4044   // If a variadic prototype is followed by a non-variadic K&R definition,
4045   // the K&R definition becomes variadic.  This is sort of an edge case, but
4046   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4047   // C99 6.9.1p8.
4048   if (!getLangOpts().CPlusPlus &&
4049       Old->hasPrototype() && !New->hasPrototype() &&
4050       New->getType()->getAs<FunctionProtoType>() &&
4051       Old->getNumParams() == New->getNumParams()) {
4052     SmallVector<QualType, 16> ArgTypes;
4053     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4054     const FunctionProtoType *OldProto
4055       = Old->getType()->getAs<FunctionProtoType>();
4056     const FunctionProtoType *NewProto
4057       = New->getType()->getAs<FunctionProtoType>();
4058 
4059     // Determine whether this is the GNU C extension.
4060     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4061                                                NewProto->getReturnType());
4062     bool LooseCompatible = !MergedReturn.isNull();
4063     for (unsigned Idx = 0, End = Old->getNumParams();
4064          LooseCompatible && Idx != End; ++Idx) {
4065       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4066       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4067       if (Context.typesAreCompatible(OldParm->getType(),
4068                                      NewProto->getParamType(Idx))) {
4069         ArgTypes.push_back(NewParm->getType());
4070       } else if (Context.typesAreCompatible(OldParm->getType(),
4071                                             NewParm->getType(),
4072                                             /*CompareUnqualified=*/true)) {
4073         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4074                                            NewProto->getParamType(Idx) };
4075         Warnings.push_back(Warn);
4076         ArgTypes.push_back(NewParm->getType());
4077       } else
4078         LooseCompatible = false;
4079     }
4080 
4081     if (LooseCompatible) {
4082       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4083         Diag(Warnings[Warn].NewParm->getLocation(),
4084              diag::ext_param_promoted_not_compatible_with_prototype)
4085           << Warnings[Warn].PromotedType
4086           << Warnings[Warn].OldParm->getType();
4087         if (Warnings[Warn].OldParm->getLocation().isValid())
4088           Diag(Warnings[Warn].OldParm->getLocation(),
4089                diag::note_previous_declaration);
4090       }
4091 
4092       if (MergeTypeWithOld)
4093         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4094                                              OldProto->getExtProtoInfo()));
4095       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4096     }
4097 
4098     // Fall through to diagnose conflicting types.
4099   }
4100 
4101   // A function that has already been declared has been redeclared or
4102   // defined with a different type; show an appropriate diagnostic.
4103 
4104   // If the previous declaration was an implicitly-generated builtin
4105   // declaration, then at the very least we should use a specialized note.
4106   unsigned BuiltinID;
4107   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4108     // If it's actually a library-defined builtin function like 'malloc'
4109     // or 'printf', just warn about the incompatible redeclaration.
4110     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4111       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4112       Diag(OldLocation, diag::note_previous_builtin_declaration)
4113         << Old << Old->getType();
4114       return false;
4115     }
4116 
4117     PrevDiag = diag::note_previous_builtin_declaration;
4118   }
4119 
4120   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4121   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4122   return true;
4123 }
4124 
4125 /// Completes the merge of two function declarations that are
4126 /// known to be compatible.
4127 ///
4128 /// This routine handles the merging of attributes and other
4129 /// properties of function declarations from the old declaration to
4130 /// the new declaration, once we know that New is in fact a
4131 /// redeclaration of Old.
4132 ///
4133 /// \returns false
4134 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4135                                         Scope *S, bool MergeTypeWithOld) {
4136   // Merge the attributes
4137   mergeDeclAttributes(New, Old);
4138 
4139   // Merge "pure" flag.
4140   if (Old->isPure())
4141     New->setPure();
4142 
4143   // Merge "used" flag.
4144   if (Old->getMostRecentDecl()->isUsed(false))
4145     New->setIsUsed();
4146 
4147   // Merge attributes from the parameters.  These can mismatch with K&R
4148   // declarations.
4149   if (New->getNumParams() == Old->getNumParams())
4150       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4151         ParmVarDecl *NewParam = New->getParamDecl(i);
4152         ParmVarDecl *OldParam = Old->getParamDecl(i);
4153         mergeParamDeclAttributes(NewParam, OldParam, *this);
4154         mergeParamDeclTypes(NewParam, OldParam, *this);
4155       }
4156 
4157   if (getLangOpts().CPlusPlus)
4158     return MergeCXXFunctionDecl(New, Old, S);
4159 
4160   // Merge the function types so the we get the composite types for the return
4161   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4162   // was visible.
4163   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4164   if (!Merged.isNull() && MergeTypeWithOld)
4165     New->setType(Merged);
4166 
4167   return false;
4168 }
4169 
4170 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4171                                 ObjCMethodDecl *oldMethod) {
4172   // Merge the attributes, including deprecated/unavailable
4173   AvailabilityMergeKind MergeKind =
4174       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4175           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4176                                      : AMK_ProtocolImplementation)
4177           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4178                                                            : AMK_Override;
4179 
4180   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4181 
4182   // Merge attributes from the parameters.
4183   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4184                                        oe = oldMethod->param_end();
4185   for (ObjCMethodDecl::param_iterator
4186          ni = newMethod->param_begin(), ne = newMethod->param_end();
4187        ni != ne && oi != oe; ++ni, ++oi)
4188     mergeParamDeclAttributes(*ni, *oi, *this);
4189 
4190   CheckObjCMethodOverride(newMethod, oldMethod);
4191 }
4192 
4193 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4194   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4195 
4196   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4197          ? diag::err_redefinition_different_type
4198          : diag::err_redeclaration_different_type)
4199     << New->getDeclName() << New->getType() << Old->getType();
4200 
4201   diag::kind PrevDiag;
4202   SourceLocation OldLocation;
4203   std::tie(PrevDiag, OldLocation)
4204     = getNoteDiagForInvalidRedeclaration(Old, New);
4205   S.Diag(OldLocation, PrevDiag);
4206   New->setInvalidDecl();
4207 }
4208 
4209 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4210 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4211 /// emitting diagnostics as appropriate.
4212 ///
4213 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4214 /// to here in AddInitializerToDecl. We can't check them before the initializer
4215 /// is attached.
4216 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4217                              bool MergeTypeWithOld) {
4218   if (New->isInvalidDecl() || Old->isInvalidDecl())
4219     return;
4220 
4221   QualType MergedT;
4222   if (getLangOpts().CPlusPlus) {
4223     if (New->getType()->isUndeducedType()) {
4224       // We don't know what the new type is until the initializer is attached.
4225       return;
4226     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4227       // These could still be something that needs exception specs checked.
4228       return MergeVarDeclExceptionSpecs(New, Old);
4229     }
4230     // C++ [basic.link]p10:
4231     //   [...] the types specified by all declarations referring to a given
4232     //   object or function shall be identical, except that declarations for an
4233     //   array object can specify array types that differ by the presence or
4234     //   absence of a major array bound (8.3.4).
4235     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4236       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4237       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4238 
4239       // We are merging a variable declaration New into Old. If it has an array
4240       // bound, and that bound differs from Old's bound, we should diagnose the
4241       // mismatch.
4242       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4243         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4244              PrevVD = PrevVD->getPreviousDecl()) {
4245           QualType PrevVDTy = PrevVD->getType();
4246           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4247             continue;
4248 
4249           if (!Context.hasSameType(New->getType(), PrevVDTy))
4250             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4251         }
4252       }
4253 
4254       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4255         if (Context.hasSameType(OldArray->getElementType(),
4256                                 NewArray->getElementType()))
4257           MergedT = New->getType();
4258       }
4259       // FIXME: Check visibility. New is hidden but has a complete type. If New
4260       // has no array bound, it should not inherit one from Old, if Old is not
4261       // visible.
4262       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4263         if (Context.hasSameType(OldArray->getElementType(),
4264                                 NewArray->getElementType()))
4265           MergedT = Old->getType();
4266       }
4267     }
4268     else if (New->getType()->isObjCObjectPointerType() &&
4269                Old->getType()->isObjCObjectPointerType()) {
4270       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4271                                               Old->getType());
4272     }
4273   } else {
4274     // C 6.2.7p2:
4275     //   All declarations that refer to the same object or function shall have
4276     //   compatible type.
4277     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4278   }
4279   if (MergedT.isNull()) {
4280     // It's OK if we couldn't merge types if either type is dependent, for a
4281     // block-scope variable. In other cases (static data members of class
4282     // templates, variable templates, ...), we require the types to be
4283     // equivalent.
4284     // FIXME: The C++ standard doesn't say anything about this.
4285     if ((New->getType()->isDependentType() ||
4286          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4287       // If the old type was dependent, we can't merge with it, so the new type
4288       // becomes dependent for now. We'll reproduce the original type when we
4289       // instantiate the TypeSourceInfo for the variable.
4290       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4291         New->setType(Context.DependentTy);
4292       return;
4293     }
4294     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4295   }
4296 
4297   // Don't actually update the type on the new declaration if the old
4298   // declaration was an extern declaration in a different scope.
4299   if (MergeTypeWithOld)
4300     New->setType(MergedT);
4301 }
4302 
4303 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4304                                   LookupResult &Previous) {
4305   // C11 6.2.7p4:
4306   //   For an identifier with internal or external linkage declared
4307   //   in a scope in which a prior declaration of that identifier is
4308   //   visible, if the prior declaration specifies internal or
4309   //   external linkage, the type of the identifier at the later
4310   //   declaration becomes the composite type.
4311   //
4312   // If the variable isn't visible, we do not merge with its type.
4313   if (Previous.isShadowed())
4314     return false;
4315 
4316   if (S.getLangOpts().CPlusPlus) {
4317     // C++11 [dcl.array]p3:
4318     //   If there is a preceding declaration of the entity in the same
4319     //   scope in which the bound was specified, an omitted array bound
4320     //   is taken to be the same as in that earlier declaration.
4321     return NewVD->isPreviousDeclInSameBlockScope() ||
4322            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4323             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4324   } else {
4325     // If the old declaration was function-local, don't merge with its
4326     // type unless we're in the same function.
4327     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4328            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4329   }
4330 }
4331 
4332 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4333 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4334 /// situation, merging decls or emitting diagnostics as appropriate.
4335 ///
4336 /// Tentative definition rules (C99 6.9.2p2) are checked by
4337 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4338 /// definitions here, since the initializer hasn't been attached.
4339 ///
4340 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4341   // If the new decl is already invalid, don't do any other checking.
4342   if (New->isInvalidDecl())
4343     return;
4344 
4345   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4346     return;
4347 
4348   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4349 
4350   // Verify the old decl was also a variable or variable template.
4351   VarDecl *Old = nullptr;
4352   VarTemplateDecl *OldTemplate = nullptr;
4353   if (Previous.isSingleResult()) {
4354     if (NewTemplate) {
4355       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4356       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4357 
4358       if (auto *Shadow =
4359               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4360         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4361           return New->setInvalidDecl();
4362     } else {
4363       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4364 
4365       if (auto *Shadow =
4366               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4367         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4368           return New->setInvalidDecl();
4369     }
4370   }
4371   if (!Old) {
4372     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4373         << New->getDeclName();
4374     notePreviousDefinition(Previous.getRepresentativeDecl(),
4375                            New->getLocation());
4376     return New->setInvalidDecl();
4377   }
4378 
4379   // If the old declaration was found in an inline namespace and the new
4380   // declaration was qualified, update the DeclContext to match.
4381   adjustDeclContextForDeclaratorDecl(New, Old);
4382 
4383   // Ensure the template parameters are compatible.
4384   if (NewTemplate &&
4385       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4386                                       OldTemplate->getTemplateParameters(),
4387                                       /*Complain=*/true, TPL_TemplateMatch))
4388     return New->setInvalidDecl();
4389 
4390   // C++ [class.mem]p1:
4391   //   A member shall not be declared twice in the member-specification [...]
4392   //
4393   // Here, we need only consider static data members.
4394   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4395     Diag(New->getLocation(), diag::err_duplicate_member)
4396       << New->getIdentifier();
4397     Diag(Old->getLocation(), diag::note_previous_declaration);
4398     New->setInvalidDecl();
4399   }
4400 
4401   mergeDeclAttributes(New, Old);
4402   // Warn if an already-declared variable is made a weak_import in a subsequent
4403   // declaration
4404   if (New->hasAttr<WeakImportAttr>() &&
4405       Old->getStorageClass() == SC_None &&
4406       !Old->hasAttr<WeakImportAttr>()) {
4407     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4408     Diag(Old->getLocation(), diag::note_previous_declaration);
4409     // Remove weak_import attribute on new declaration.
4410     New->dropAttr<WeakImportAttr>();
4411   }
4412 
4413   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4414     if (!Old->hasAttr<InternalLinkageAttr>()) {
4415       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4416           << ILA;
4417       Diag(Old->getLocation(), diag::note_previous_declaration);
4418       New->dropAttr<InternalLinkageAttr>();
4419     }
4420 
4421   // Merge the types.
4422   VarDecl *MostRecent = Old->getMostRecentDecl();
4423   if (MostRecent != Old) {
4424     MergeVarDeclTypes(New, MostRecent,
4425                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4426     if (New->isInvalidDecl())
4427       return;
4428   }
4429 
4430   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4431   if (New->isInvalidDecl())
4432     return;
4433 
4434   diag::kind PrevDiag;
4435   SourceLocation OldLocation;
4436   std::tie(PrevDiag, OldLocation) =
4437       getNoteDiagForInvalidRedeclaration(Old, New);
4438 
4439   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4440   if (New->getStorageClass() == SC_Static &&
4441       !New->isStaticDataMember() &&
4442       Old->hasExternalFormalLinkage()) {
4443     if (getLangOpts().MicrosoftExt) {
4444       Diag(New->getLocation(), diag::ext_static_non_static)
4445           << New->getDeclName();
4446       Diag(OldLocation, PrevDiag);
4447     } else {
4448       Diag(New->getLocation(), diag::err_static_non_static)
4449           << New->getDeclName();
4450       Diag(OldLocation, PrevDiag);
4451       return New->setInvalidDecl();
4452     }
4453   }
4454   // C99 6.2.2p4:
4455   //   For an identifier declared with the storage-class specifier
4456   //   extern in a scope in which a prior declaration of that
4457   //   identifier is visible,23) if the prior declaration specifies
4458   //   internal or external linkage, the linkage of the identifier at
4459   //   the later declaration is the same as the linkage specified at
4460   //   the prior declaration. If no prior declaration is visible, or
4461   //   if the prior declaration specifies no linkage, then the
4462   //   identifier has external linkage.
4463   if (New->hasExternalStorage() && Old->hasLinkage())
4464     /* Okay */;
4465   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4466            !New->isStaticDataMember() &&
4467            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4468     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4469     Diag(OldLocation, PrevDiag);
4470     return New->setInvalidDecl();
4471   }
4472 
4473   // Check if extern is followed by non-extern and vice-versa.
4474   if (New->hasExternalStorage() &&
4475       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4476     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4477     Diag(OldLocation, PrevDiag);
4478     return New->setInvalidDecl();
4479   }
4480   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4481       !New->hasExternalStorage()) {
4482     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4483     Diag(OldLocation, PrevDiag);
4484     return New->setInvalidDecl();
4485   }
4486 
4487   if (CheckRedeclarationInModule(New, Old))
4488     return;
4489 
4490   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4491 
4492   // FIXME: The test for external storage here seems wrong? We still
4493   // need to check for mismatches.
4494   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4495       // Don't complain about out-of-line definitions of static members.
4496       !(Old->getLexicalDeclContext()->isRecord() &&
4497         !New->getLexicalDeclContext()->isRecord())) {
4498     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4499     Diag(OldLocation, PrevDiag);
4500     return New->setInvalidDecl();
4501   }
4502 
4503   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4504     if (VarDecl *Def = Old->getDefinition()) {
4505       // C++1z [dcl.fcn.spec]p4:
4506       //   If the definition of a variable appears in a translation unit before
4507       //   its first declaration as inline, the program is ill-formed.
4508       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4509       Diag(Def->getLocation(), diag::note_previous_definition);
4510     }
4511   }
4512 
4513   // If this redeclaration makes the variable inline, we may need to add it to
4514   // UndefinedButUsed.
4515   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4516       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4517     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4518                                            SourceLocation()));
4519 
4520   if (New->getTLSKind() != Old->getTLSKind()) {
4521     if (!Old->getTLSKind()) {
4522       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4523       Diag(OldLocation, PrevDiag);
4524     } else if (!New->getTLSKind()) {
4525       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4526       Diag(OldLocation, PrevDiag);
4527     } else {
4528       // Do not allow redeclaration to change the variable between requiring
4529       // static and dynamic initialization.
4530       // FIXME: GCC allows this, but uses the TLS keyword on the first
4531       // declaration to determine the kind. Do we need to be compatible here?
4532       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4533         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4534       Diag(OldLocation, PrevDiag);
4535     }
4536   }
4537 
4538   // C++ doesn't have tentative definitions, so go right ahead and check here.
4539   if (getLangOpts().CPlusPlus &&
4540       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4541     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4542         Old->getCanonicalDecl()->isConstexpr()) {
4543       // This definition won't be a definition any more once it's been merged.
4544       Diag(New->getLocation(),
4545            diag::warn_deprecated_redundant_constexpr_static_def);
4546     } else if (VarDecl *Def = Old->getDefinition()) {
4547       if (checkVarDeclRedefinition(Def, New))
4548         return;
4549     }
4550   }
4551 
4552   if (haveIncompatibleLanguageLinkages(Old, New)) {
4553     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4554     Diag(OldLocation, PrevDiag);
4555     New->setInvalidDecl();
4556     return;
4557   }
4558 
4559   // Merge "used" flag.
4560   if (Old->getMostRecentDecl()->isUsed(false))
4561     New->setIsUsed();
4562 
4563   // Keep a chain of previous declarations.
4564   New->setPreviousDecl(Old);
4565   if (NewTemplate)
4566     NewTemplate->setPreviousDecl(OldTemplate);
4567 
4568   // Inherit access appropriately.
4569   New->setAccess(Old->getAccess());
4570   if (NewTemplate)
4571     NewTemplate->setAccess(New->getAccess());
4572 
4573   if (Old->isInline())
4574     New->setImplicitlyInline();
4575 }
4576 
4577 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4578   SourceManager &SrcMgr = getSourceManager();
4579   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4580   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4581   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4582   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4583   auto &HSI = PP.getHeaderSearchInfo();
4584   StringRef HdrFilename =
4585       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4586 
4587   auto noteFromModuleOrInclude = [&](Module *Mod,
4588                                      SourceLocation IncLoc) -> bool {
4589     // Redefinition errors with modules are common with non modular mapped
4590     // headers, example: a non-modular header H in module A that also gets
4591     // included directly in a TU. Pointing twice to the same header/definition
4592     // is confusing, try to get better diagnostics when modules is on.
4593     if (IncLoc.isValid()) {
4594       if (Mod) {
4595         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4596             << HdrFilename.str() << Mod->getFullModuleName();
4597         if (!Mod->DefinitionLoc.isInvalid())
4598           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4599               << Mod->getFullModuleName();
4600       } else {
4601         Diag(IncLoc, diag::note_redefinition_include_same_file)
4602             << HdrFilename.str();
4603       }
4604       return true;
4605     }
4606 
4607     return false;
4608   };
4609 
4610   // Is it the same file and same offset? Provide more information on why
4611   // this leads to a redefinition error.
4612   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4613     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4614     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4615     bool EmittedDiag =
4616         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4617     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4618 
4619     // If the header has no guards, emit a note suggesting one.
4620     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4621       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4622 
4623     if (EmittedDiag)
4624       return;
4625   }
4626 
4627   // Redefinition coming from different files or couldn't do better above.
4628   if (Old->getLocation().isValid())
4629     Diag(Old->getLocation(), diag::note_previous_definition);
4630 }
4631 
4632 /// We've just determined that \p Old and \p New both appear to be definitions
4633 /// of the same variable. Either diagnose or fix the problem.
4634 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4635   if (!hasVisibleDefinition(Old) &&
4636       (New->getFormalLinkage() == InternalLinkage ||
4637        New->isInline() ||
4638        New->getDescribedVarTemplate() ||
4639        New->getNumTemplateParameterLists() ||
4640        New->getDeclContext()->isDependentContext())) {
4641     // The previous definition is hidden, and multiple definitions are
4642     // permitted (in separate TUs). Demote this to a declaration.
4643     New->demoteThisDefinitionToDeclaration();
4644 
4645     // Make the canonical definition visible.
4646     if (auto *OldTD = Old->getDescribedVarTemplate())
4647       makeMergedDefinitionVisible(OldTD);
4648     makeMergedDefinitionVisible(Old);
4649     return false;
4650   } else {
4651     Diag(New->getLocation(), diag::err_redefinition) << New;
4652     notePreviousDefinition(Old, New->getLocation());
4653     New->setInvalidDecl();
4654     return true;
4655   }
4656 }
4657 
4658 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4659 /// no declarator (e.g. "struct foo;") is parsed.
4660 Decl *
4661 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4662                                  RecordDecl *&AnonRecord) {
4663   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4664                                     AnonRecord);
4665 }
4666 
4667 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4668 // disambiguate entities defined in different scopes.
4669 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4670 // compatibility.
4671 // We will pick our mangling number depending on which version of MSVC is being
4672 // targeted.
4673 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4674   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4675              ? S->getMSCurManglingNumber()
4676              : S->getMSLastManglingNumber();
4677 }
4678 
4679 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4680   if (!Context.getLangOpts().CPlusPlus)
4681     return;
4682 
4683   if (isa<CXXRecordDecl>(Tag->getParent())) {
4684     // If this tag is the direct child of a class, number it if
4685     // it is anonymous.
4686     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4687       return;
4688     MangleNumberingContext &MCtx =
4689         Context.getManglingNumberContext(Tag->getParent());
4690     Context.setManglingNumber(
4691         Tag, MCtx.getManglingNumber(
4692                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4693     return;
4694   }
4695 
4696   // If this tag isn't a direct child of a class, number it if it is local.
4697   MangleNumberingContext *MCtx;
4698   Decl *ManglingContextDecl;
4699   std::tie(MCtx, ManglingContextDecl) =
4700       getCurrentMangleNumberContext(Tag->getDeclContext());
4701   if (MCtx) {
4702     Context.setManglingNumber(
4703         Tag, MCtx->getManglingNumber(
4704                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4705   }
4706 }
4707 
4708 namespace {
4709 struct NonCLikeKind {
4710   enum {
4711     None,
4712     BaseClass,
4713     DefaultMemberInit,
4714     Lambda,
4715     Friend,
4716     OtherMember,
4717     Invalid,
4718   } Kind = None;
4719   SourceRange Range;
4720 
4721   explicit operator bool() { return Kind != None; }
4722 };
4723 }
4724 
4725 /// Determine whether a class is C-like, according to the rules of C++
4726 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4727 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4728   if (RD->isInvalidDecl())
4729     return {NonCLikeKind::Invalid, {}};
4730 
4731   // C++ [dcl.typedef]p9: [P1766R1]
4732   //   An unnamed class with a typedef name for linkage purposes shall not
4733   //
4734   //    -- have any base classes
4735   if (RD->getNumBases())
4736     return {NonCLikeKind::BaseClass,
4737             SourceRange(RD->bases_begin()->getBeginLoc(),
4738                         RD->bases_end()[-1].getEndLoc())};
4739   bool Invalid = false;
4740   for (Decl *D : RD->decls()) {
4741     // Don't complain about things we already diagnosed.
4742     if (D->isInvalidDecl()) {
4743       Invalid = true;
4744       continue;
4745     }
4746 
4747     //  -- have any [...] default member initializers
4748     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4749       if (FD->hasInClassInitializer()) {
4750         auto *Init = FD->getInClassInitializer();
4751         return {NonCLikeKind::DefaultMemberInit,
4752                 Init ? Init->getSourceRange() : D->getSourceRange()};
4753       }
4754       continue;
4755     }
4756 
4757     // FIXME: We don't allow friend declarations. This violates the wording of
4758     // P1766, but not the intent.
4759     if (isa<FriendDecl>(D))
4760       return {NonCLikeKind::Friend, D->getSourceRange()};
4761 
4762     //  -- declare any members other than non-static data members, member
4763     //     enumerations, or member classes,
4764     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4765         isa<EnumDecl>(D))
4766       continue;
4767     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4768     if (!MemberRD) {
4769       if (D->isImplicit())
4770         continue;
4771       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4772     }
4773 
4774     //  -- contain a lambda-expression,
4775     if (MemberRD->isLambda())
4776       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4777 
4778     //  and all member classes shall also satisfy these requirements
4779     //  (recursively).
4780     if (MemberRD->isThisDeclarationADefinition()) {
4781       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4782         return Kind;
4783     }
4784   }
4785 
4786   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4787 }
4788 
4789 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4790                                         TypedefNameDecl *NewTD) {
4791   if (TagFromDeclSpec->isInvalidDecl())
4792     return;
4793 
4794   // Do nothing if the tag already has a name for linkage purposes.
4795   if (TagFromDeclSpec->hasNameForLinkage())
4796     return;
4797 
4798   // A well-formed anonymous tag must always be a TUK_Definition.
4799   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4800 
4801   // The type must match the tag exactly;  no qualifiers allowed.
4802   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4803                            Context.getTagDeclType(TagFromDeclSpec))) {
4804     if (getLangOpts().CPlusPlus)
4805       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4806     return;
4807   }
4808 
4809   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4810   //   An unnamed class with a typedef name for linkage purposes shall [be
4811   //   C-like].
4812   //
4813   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4814   // shouldn't happen, but there are constructs that the language rule doesn't
4815   // disallow for which we can't reasonably avoid computing linkage early.
4816   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4817   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4818                              : NonCLikeKind();
4819   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4820   if (NonCLike || ChangesLinkage) {
4821     if (NonCLike.Kind == NonCLikeKind::Invalid)
4822       return;
4823 
4824     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4825     if (ChangesLinkage) {
4826       // If the linkage changes, we can't accept this as an extension.
4827       if (NonCLike.Kind == NonCLikeKind::None)
4828         DiagID = diag::err_typedef_changes_linkage;
4829       else
4830         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4831     }
4832 
4833     SourceLocation FixitLoc =
4834         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4835     llvm::SmallString<40> TextToInsert;
4836     TextToInsert += ' ';
4837     TextToInsert += NewTD->getIdentifier()->getName();
4838 
4839     Diag(FixitLoc, DiagID)
4840       << isa<TypeAliasDecl>(NewTD)
4841       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4842     if (NonCLike.Kind != NonCLikeKind::None) {
4843       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4844         << NonCLike.Kind - 1 << NonCLike.Range;
4845     }
4846     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4847       << NewTD << isa<TypeAliasDecl>(NewTD);
4848 
4849     if (ChangesLinkage)
4850       return;
4851   }
4852 
4853   // Otherwise, set this as the anon-decl typedef for the tag.
4854   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4855 }
4856 
4857 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4858   switch (T) {
4859   case DeclSpec::TST_class:
4860     return 0;
4861   case DeclSpec::TST_struct:
4862     return 1;
4863   case DeclSpec::TST_interface:
4864     return 2;
4865   case DeclSpec::TST_union:
4866     return 3;
4867   case DeclSpec::TST_enum:
4868     return 4;
4869   default:
4870     llvm_unreachable("unexpected type specifier");
4871   }
4872 }
4873 
4874 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4875 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4876 /// parameters to cope with template friend declarations.
4877 Decl *
4878 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4879                                  MultiTemplateParamsArg TemplateParams,
4880                                  bool IsExplicitInstantiation,
4881                                  RecordDecl *&AnonRecord) {
4882   Decl *TagD = nullptr;
4883   TagDecl *Tag = nullptr;
4884   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4885       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4886       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4887       DS.getTypeSpecType() == DeclSpec::TST_union ||
4888       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4889     TagD = DS.getRepAsDecl();
4890 
4891     if (!TagD) // We probably had an error
4892       return nullptr;
4893 
4894     // Note that the above type specs guarantee that the
4895     // type rep is a Decl, whereas in many of the others
4896     // it's a Type.
4897     if (isa<TagDecl>(TagD))
4898       Tag = cast<TagDecl>(TagD);
4899     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4900       Tag = CTD->getTemplatedDecl();
4901   }
4902 
4903   if (Tag) {
4904     handleTagNumbering(Tag, S);
4905     Tag->setFreeStanding();
4906     if (Tag->isInvalidDecl())
4907       return Tag;
4908   }
4909 
4910   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4911     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4912     // or incomplete types shall not be restrict-qualified."
4913     if (TypeQuals & DeclSpec::TQ_restrict)
4914       Diag(DS.getRestrictSpecLoc(),
4915            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4916            << DS.getSourceRange();
4917   }
4918 
4919   if (DS.isInlineSpecified())
4920     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4921         << getLangOpts().CPlusPlus17;
4922 
4923   if (DS.hasConstexprSpecifier()) {
4924     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4925     // and definitions of functions and variables.
4926     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4927     // the declaration of a function or function template
4928     if (Tag)
4929       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4930           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4931           << static_cast<int>(DS.getConstexprSpecifier());
4932     else
4933       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4934           << static_cast<int>(DS.getConstexprSpecifier());
4935     // Don't emit warnings after this error.
4936     return TagD;
4937   }
4938 
4939   DiagnoseFunctionSpecifiers(DS);
4940 
4941   if (DS.isFriendSpecified()) {
4942     // If we're dealing with a decl but not a TagDecl, assume that
4943     // whatever routines created it handled the friendship aspect.
4944     if (TagD && !Tag)
4945       return nullptr;
4946     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4947   }
4948 
4949   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4950   bool IsExplicitSpecialization =
4951     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4952   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4953       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4954       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4955     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4956     // nested-name-specifier unless it is an explicit instantiation
4957     // or an explicit specialization.
4958     //
4959     // FIXME: We allow class template partial specializations here too, per the
4960     // obvious intent of DR1819.
4961     //
4962     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4963     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4964         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4965     return nullptr;
4966   }
4967 
4968   // Track whether this decl-specifier declares anything.
4969   bool DeclaresAnything = true;
4970 
4971   // Handle anonymous struct definitions.
4972   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4973     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4974         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4975       if (getLangOpts().CPlusPlus ||
4976           Record->getDeclContext()->isRecord()) {
4977         // If CurContext is a DeclContext that can contain statements,
4978         // RecursiveASTVisitor won't visit the decls that
4979         // BuildAnonymousStructOrUnion() will put into CurContext.
4980         // Also store them here so that they can be part of the
4981         // DeclStmt that gets created in this case.
4982         // FIXME: Also return the IndirectFieldDecls created by
4983         // BuildAnonymousStructOr union, for the same reason?
4984         if (CurContext->isFunctionOrMethod())
4985           AnonRecord = Record;
4986         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4987                                            Context.getPrintingPolicy());
4988       }
4989 
4990       DeclaresAnything = false;
4991     }
4992   }
4993 
4994   // C11 6.7.2.1p2:
4995   //   A struct-declaration that does not declare an anonymous structure or
4996   //   anonymous union shall contain a struct-declarator-list.
4997   //
4998   // This rule also existed in C89 and C99; the grammar for struct-declaration
4999   // did not permit a struct-declaration without a struct-declarator-list.
5000   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5001       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5002     // Check for Microsoft C extension: anonymous struct/union member.
5003     // Handle 2 kinds of anonymous struct/union:
5004     //   struct STRUCT;
5005     //   union UNION;
5006     // and
5007     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5008     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5009     if ((Tag && Tag->getDeclName()) ||
5010         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5011       RecordDecl *Record = nullptr;
5012       if (Tag)
5013         Record = dyn_cast<RecordDecl>(Tag);
5014       else if (const RecordType *RT =
5015                    DS.getRepAsType().get()->getAsStructureType())
5016         Record = RT->getDecl();
5017       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5018         Record = UT->getDecl();
5019 
5020       if (Record && getLangOpts().MicrosoftExt) {
5021         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5022             << Record->isUnion() << DS.getSourceRange();
5023         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5024       }
5025 
5026       DeclaresAnything = false;
5027     }
5028   }
5029 
5030   // Skip all the checks below if we have a type error.
5031   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5032       (TagD && TagD->isInvalidDecl()))
5033     return TagD;
5034 
5035   if (getLangOpts().CPlusPlus &&
5036       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5037     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5038       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5039           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5040         DeclaresAnything = false;
5041 
5042   if (!DS.isMissingDeclaratorOk()) {
5043     // Customize diagnostic for a typedef missing a name.
5044     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5045       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5046           << DS.getSourceRange();
5047     else
5048       DeclaresAnything = false;
5049   }
5050 
5051   if (DS.isModulePrivateSpecified() &&
5052       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5053     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5054       << Tag->getTagKind()
5055       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5056 
5057   ActOnDocumentableDecl(TagD);
5058 
5059   // C 6.7/2:
5060   //   A declaration [...] shall declare at least a declarator [...], a tag,
5061   //   or the members of an enumeration.
5062   // C++ [dcl.dcl]p3:
5063   //   [If there are no declarators], and except for the declaration of an
5064   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5065   //   names into the program, or shall redeclare a name introduced by a
5066   //   previous declaration.
5067   if (!DeclaresAnything) {
5068     // In C, we allow this as a (popular) extension / bug. Don't bother
5069     // producing further diagnostics for redundant qualifiers after this.
5070     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5071                                ? diag::err_no_declarators
5072                                : diag::ext_no_declarators)
5073         << DS.getSourceRange();
5074     return TagD;
5075   }
5076 
5077   // C++ [dcl.stc]p1:
5078   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5079   //   init-declarator-list of the declaration shall not be empty.
5080   // C++ [dcl.fct.spec]p1:
5081   //   If a cv-qualifier appears in a decl-specifier-seq, the
5082   //   init-declarator-list of the declaration shall not be empty.
5083   //
5084   // Spurious qualifiers here appear to be valid in C.
5085   unsigned DiagID = diag::warn_standalone_specifier;
5086   if (getLangOpts().CPlusPlus)
5087     DiagID = diag::ext_standalone_specifier;
5088 
5089   // Note that a linkage-specification sets a storage class, but
5090   // 'extern "C" struct foo;' is actually valid and not theoretically
5091   // useless.
5092   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5093     if (SCS == DeclSpec::SCS_mutable)
5094       // Since mutable is not a viable storage class specifier in C, there is
5095       // no reason to treat it as an extension. Instead, diagnose as an error.
5096       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5097     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5098       Diag(DS.getStorageClassSpecLoc(), DiagID)
5099         << DeclSpec::getSpecifierName(SCS);
5100   }
5101 
5102   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5103     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5104       << DeclSpec::getSpecifierName(TSCS);
5105   if (DS.getTypeQualifiers()) {
5106     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5107       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5108     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5109       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5110     // Restrict is covered above.
5111     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5112       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5113     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5114       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5115   }
5116 
5117   // Warn about ignored type attributes, for example:
5118   // __attribute__((aligned)) struct A;
5119   // Attributes should be placed after tag to apply to type declaration.
5120   if (!DS.getAttributes().empty()) {
5121     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5122     if (TypeSpecType == DeclSpec::TST_class ||
5123         TypeSpecType == DeclSpec::TST_struct ||
5124         TypeSpecType == DeclSpec::TST_interface ||
5125         TypeSpecType == DeclSpec::TST_union ||
5126         TypeSpecType == DeclSpec::TST_enum) {
5127       for (const ParsedAttr &AL : DS.getAttributes())
5128         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5129             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5130     }
5131   }
5132 
5133   return TagD;
5134 }
5135 
5136 /// We are trying to inject an anonymous member into the given scope;
5137 /// check if there's an existing declaration that can't be overloaded.
5138 ///
5139 /// \return true if this is a forbidden redeclaration
5140 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5141                                          Scope *S,
5142                                          DeclContext *Owner,
5143                                          DeclarationName Name,
5144                                          SourceLocation NameLoc,
5145                                          bool IsUnion) {
5146   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5147                  Sema::ForVisibleRedeclaration);
5148   if (!SemaRef.LookupName(R, S)) return false;
5149 
5150   // Pick a representative declaration.
5151   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5152   assert(PrevDecl && "Expected a non-null Decl");
5153 
5154   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5155     return false;
5156 
5157   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5158     << IsUnion << Name;
5159   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5160 
5161   return true;
5162 }
5163 
5164 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5165 /// anonymous struct or union AnonRecord into the owning context Owner
5166 /// and scope S. This routine will be invoked just after we realize
5167 /// that an unnamed union or struct is actually an anonymous union or
5168 /// struct, e.g.,
5169 ///
5170 /// @code
5171 /// union {
5172 ///   int i;
5173 ///   float f;
5174 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5175 ///    // f into the surrounding scope.x
5176 /// @endcode
5177 ///
5178 /// This routine is recursive, injecting the names of nested anonymous
5179 /// structs/unions into the owning context and scope as well.
5180 static bool
5181 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5182                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5183                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5184   bool Invalid = false;
5185 
5186   // Look every FieldDecl and IndirectFieldDecl with a name.
5187   for (auto *D : AnonRecord->decls()) {
5188     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5189         cast<NamedDecl>(D)->getDeclName()) {
5190       ValueDecl *VD = cast<ValueDecl>(D);
5191       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5192                                        VD->getLocation(),
5193                                        AnonRecord->isUnion())) {
5194         // C++ [class.union]p2:
5195         //   The names of the members of an anonymous union shall be
5196         //   distinct from the names of any other entity in the
5197         //   scope in which the anonymous union is declared.
5198         Invalid = true;
5199       } else {
5200         // C++ [class.union]p2:
5201         //   For the purpose of name lookup, after the anonymous union
5202         //   definition, the members of the anonymous union are
5203         //   considered to have been defined in the scope in which the
5204         //   anonymous union is declared.
5205         unsigned OldChainingSize = Chaining.size();
5206         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5207           Chaining.append(IF->chain_begin(), IF->chain_end());
5208         else
5209           Chaining.push_back(VD);
5210 
5211         assert(Chaining.size() >= 2);
5212         NamedDecl **NamedChain =
5213           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5214         for (unsigned i = 0; i < Chaining.size(); i++)
5215           NamedChain[i] = Chaining[i];
5216 
5217         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5218             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5219             VD->getType(), {NamedChain, Chaining.size()});
5220 
5221         for (const auto *Attr : VD->attrs())
5222           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5223 
5224         IndirectField->setAccess(AS);
5225         IndirectField->setImplicit();
5226         SemaRef.PushOnScopeChains(IndirectField, S);
5227 
5228         // That includes picking up the appropriate access specifier.
5229         if (AS != AS_none) IndirectField->setAccess(AS);
5230 
5231         Chaining.resize(OldChainingSize);
5232       }
5233     }
5234   }
5235 
5236   return Invalid;
5237 }
5238 
5239 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5240 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5241 /// illegal input values are mapped to SC_None.
5242 static StorageClass
5243 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5244   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5245   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5246          "Parser allowed 'typedef' as storage class VarDecl.");
5247   switch (StorageClassSpec) {
5248   case DeclSpec::SCS_unspecified:    return SC_None;
5249   case DeclSpec::SCS_extern:
5250     if (DS.isExternInLinkageSpec())
5251       return SC_None;
5252     return SC_Extern;
5253   case DeclSpec::SCS_static:         return SC_Static;
5254   case DeclSpec::SCS_auto:           return SC_Auto;
5255   case DeclSpec::SCS_register:       return SC_Register;
5256   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5257     // Illegal SCSs map to None: error reporting is up to the caller.
5258   case DeclSpec::SCS_mutable:        // Fall through.
5259   case DeclSpec::SCS_typedef:        return SC_None;
5260   }
5261   llvm_unreachable("unknown storage class specifier");
5262 }
5263 
5264 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5265   assert(Record->hasInClassInitializer());
5266 
5267   for (const auto *I : Record->decls()) {
5268     const auto *FD = dyn_cast<FieldDecl>(I);
5269     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5270       FD = IFD->getAnonField();
5271     if (FD && FD->hasInClassInitializer())
5272       return FD->getLocation();
5273   }
5274 
5275   llvm_unreachable("couldn't find in-class initializer");
5276 }
5277 
5278 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5279                                       SourceLocation DefaultInitLoc) {
5280   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5281     return;
5282 
5283   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5284   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5285 }
5286 
5287 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5288                                       CXXRecordDecl *AnonUnion) {
5289   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5290     return;
5291 
5292   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5293 }
5294 
5295 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5296 /// anonymous structure or union. Anonymous unions are a C++ feature
5297 /// (C++ [class.union]) and a C11 feature; anonymous structures
5298 /// are a C11 feature and GNU C++ extension.
5299 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5300                                         AccessSpecifier AS,
5301                                         RecordDecl *Record,
5302                                         const PrintingPolicy &Policy) {
5303   DeclContext *Owner = Record->getDeclContext();
5304 
5305   // Diagnose whether this anonymous struct/union is an extension.
5306   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5307     Diag(Record->getLocation(), diag::ext_anonymous_union);
5308   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5309     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5310   else if (!Record->isUnion() && !getLangOpts().C11)
5311     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5312 
5313   // C and C++ require different kinds of checks for anonymous
5314   // structs/unions.
5315   bool Invalid = false;
5316   if (getLangOpts().CPlusPlus) {
5317     const char *PrevSpec = nullptr;
5318     if (Record->isUnion()) {
5319       // C++ [class.union]p6:
5320       // C++17 [class.union.anon]p2:
5321       //   Anonymous unions declared in a named namespace or in the
5322       //   global namespace shall be declared static.
5323       unsigned DiagID;
5324       DeclContext *OwnerScope = Owner->getRedeclContext();
5325       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5326           (OwnerScope->isTranslationUnit() ||
5327            (OwnerScope->isNamespace() &&
5328             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5329         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5330           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5331 
5332         // Recover by adding 'static'.
5333         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5334                                PrevSpec, DiagID, Policy);
5335       }
5336       // C++ [class.union]p6:
5337       //   A storage class is not allowed in a declaration of an
5338       //   anonymous union in a class scope.
5339       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5340                isa<RecordDecl>(Owner)) {
5341         Diag(DS.getStorageClassSpecLoc(),
5342              diag::err_anonymous_union_with_storage_spec)
5343           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5344 
5345         // Recover by removing the storage specifier.
5346         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5347                                SourceLocation(),
5348                                PrevSpec, DiagID, Context.getPrintingPolicy());
5349       }
5350     }
5351 
5352     // Ignore const/volatile/restrict qualifiers.
5353     if (DS.getTypeQualifiers()) {
5354       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5355         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5356           << Record->isUnion() << "const"
5357           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5358       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5359         Diag(DS.getVolatileSpecLoc(),
5360              diag::ext_anonymous_struct_union_qualified)
5361           << Record->isUnion() << "volatile"
5362           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5363       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5364         Diag(DS.getRestrictSpecLoc(),
5365              diag::ext_anonymous_struct_union_qualified)
5366           << Record->isUnion() << "restrict"
5367           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5368       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5369         Diag(DS.getAtomicSpecLoc(),
5370              diag::ext_anonymous_struct_union_qualified)
5371           << Record->isUnion() << "_Atomic"
5372           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5373       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5374         Diag(DS.getUnalignedSpecLoc(),
5375              diag::ext_anonymous_struct_union_qualified)
5376           << Record->isUnion() << "__unaligned"
5377           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5378 
5379       DS.ClearTypeQualifiers();
5380     }
5381 
5382     // C++ [class.union]p2:
5383     //   The member-specification of an anonymous union shall only
5384     //   define non-static data members. [Note: nested types and
5385     //   functions cannot be declared within an anonymous union. ]
5386     for (auto *Mem : Record->decls()) {
5387       // Ignore invalid declarations; we already diagnosed them.
5388       if (Mem->isInvalidDecl())
5389         continue;
5390 
5391       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5392         // C++ [class.union]p3:
5393         //   An anonymous union shall not have private or protected
5394         //   members (clause 11).
5395         assert(FD->getAccess() != AS_none);
5396         if (FD->getAccess() != AS_public) {
5397           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5398             << Record->isUnion() << (FD->getAccess() == AS_protected);
5399           Invalid = true;
5400         }
5401 
5402         // C++ [class.union]p1
5403         //   An object of a class with a non-trivial constructor, a non-trivial
5404         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5405         //   assignment operator cannot be a member of a union, nor can an
5406         //   array of such objects.
5407         if (CheckNontrivialField(FD))
5408           Invalid = true;
5409       } else if (Mem->isImplicit()) {
5410         // Any implicit members are fine.
5411       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5412         // This is a type that showed up in an
5413         // elaborated-type-specifier inside the anonymous struct or
5414         // union, but which actually declares a type outside of the
5415         // anonymous struct or union. It's okay.
5416       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5417         if (!MemRecord->isAnonymousStructOrUnion() &&
5418             MemRecord->getDeclName()) {
5419           // Visual C++ allows type definition in anonymous struct or union.
5420           if (getLangOpts().MicrosoftExt)
5421             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5422               << Record->isUnion();
5423           else {
5424             // This is a nested type declaration.
5425             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5426               << Record->isUnion();
5427             Invalid = true;
5428           }
5429         } else {
5430           // This is an anonymous type definition within another anonymous type.
5431           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5432           // not part of standard C++.
5433           Diag(MemRecord->getLocation(),
5434                diag::ext_anonymous_record_with_anonymous_type)
5435             << Record->isUnion();
5436         }
5437       } else if (isa<AccessSpecDecl>(Mem)) {
5438         // Any access specifier is fine.
5439       } else if (isa<StaticAssertDecl>(Mem)) {
5440         // In C++1z, static_assert declarations are also fine.
5441       } else {
5442         // We have something that isn't a non-static data
5443         // member. Complain about it.
5444         unsigned DK = diag::err_anonymous_record_bad_member;
5445         if (isa<TypeDecl>(Mem))
5446           DK = diag::err_anonymous_record_with_type;
5447         else if (isa<FunctionDecl>(Mem))
5448           DK = diag::err_anonymous_record_with_function;
5449         else if (isa<VarDecl>(Mem))
5450           DK = diag::err_anonymous_record_with_static;
5451 
5452         // Visual C++ allows type definition in anonymous struct or union.
5453         if (getLangOpts().MicrosoftExt &&
5454             DK == diag::err_anonymous_record_with_type)
5455           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5456             << Record->isUnion();
5457         else {
5458           Diag(Mem->getLocation(), DK) << Record->isUnion();
5459           Invalid = true;
5460         }
5461       }
5462     }
5463 
5464     // C++11 [class.union]p8 (DR1460):
5465     //   At most one variant member of a union may have a
5466     //   brace-or-equal-initializer.
5467     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5468         Owner->isRecord())
5469       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5470                                 cast<CXXRecordDecl>(Record));
5471   }
5472 
5473   if (!Record->isUnion() && !Owner->isRecord()) {
5474     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5475       << getLangOpts().CPlusPlus;
5476     Invalid = true;
5477   }
5478 
5479   // C++ [dcl.dcl]p3:
5480   //   [If there are no declarators], and except for the declaration of an
5481   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5482   //   names into the program
5483   // C++ [class.mem]p2:
5484   //   each such member-declaration shall either declare at least one member
5485   //   name of the class or declare at least one unnamed bit-field
5486   //
5487   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5488   if (getLangOpts().CPlusPlus && Record->field_empty())
5489     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5490 
5491   // Mock up a declarator.
5492   Declarator Dc(DS, DeclaratorContext::Member);
5493   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5494   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5495 
5496   // Create a declaration for this anonymous struct/union.
5497   NamedDecl *Anon = nullptr;
5498   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5499     Anon = FieldDecl::Create(
5500         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5501         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5502         /*BitWidth=*/nullptr, /*Mutable=*/false,
5503         /*InitStyle=*/ICIS_NoInit);
5504     Anon->setAccess(AS);
5505     ProcessDeclAttributes(S, Anon, Dc);
5506 
5507     if (getLangOpts().CPlusPlus)
5508       FieldCollector->Add(cast<FieldDecl>(Anon));
5509   } else {
5510     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5511     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5512     if (SCSpec == DeclSpec::SCS_mutable) {
5513       // mutable can only appear on non-static class members, so it's always
5514       // an error here
5515       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5516       Invalid = true;
5517       SC = SC_None;
5518     }
5519 
5520     assert(DS.getAttributes().empty() && "No attribute expected");
5521     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5522                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5523                            Context.getTypeDeclType(Record), TInfo, SC);
5524 
5525     // Default-initialize the implicit variable. This initialization will be
5526     // trivial in almost all cases, except if a union member has an in-class
5527     // initializer:
5528     //   union { int n = 0; };
5529     ActOnUninitializedDecl(Anon);
5530   }
5531   Anon->setImplicit();
5532 
5533   // Mark this as an anonymous struct/union type.
5534   Record->setAnonymousStructOrUnion(true);
5535 
5536   // Add the anonymous struct/union object to the current
5537   // context. We'll be referencing this object when we refer to one of
5538   // its members.
5539   Owner->addDecl(Anon);
5540 
5541   // Inject the members of the anonymous struct/union into the owning
5542   // context and into the identifier resolver chain for name lookup
5543   // purposes.
5544   SmallVector<NamedDecl*, 2> Chain;
5545   Chain.push_back(Anon);
5546 
5547   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5548     Invalid = true;
5549 
5550   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5551     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5552       MangleNumberingContext *MCtx;
5553       Decl *ManglingContextDecl;
5554       std::tie(MCtx, ManglingContextDecl) =
5555           getCurrentMangleNumberContext(NewVD->getDeclContext());
5556       if (MCtx) {
5557         Context.setManglingNumber(
5558             NewVD, MCtx->getManglingNumber(
5559                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5560         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5561       }
5562     }
5563   }
5564 
5565   if (Invalid)
5566     Anon->setInvalidDecl();
5567 
5568   return Anon;
5569 }
5570 
5571 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5572 /// Microsoft C anonymous structure.
5573 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5574 /// Example:
5575 ///
5576 /// struct A { int a; };
5577 /// struct B { struct A; int b; };
5578 ///
5579 /// void foo() {
5580 ///   B var;
5581 ///   var.a = 3;
5582 /// }
5583 ///
5584 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5585                                            RecordDecl *Record) {
5586   assert(Record && "expected a record!");
5587 
5588   // Mock up a declarator.
5589   Declarator Dc(DS, DeclaratorContext::TypeName);
5590   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5591   assert(TInfo && "couldn't build declarator info for anonymous struct");
5592 
5593   auto *ParentDecl = cast<RecordDecl>(CurContext);
5594   QualType RecTy = Context.getTypeDeclType(Record);
5595 
5596   // Create a declaration for this anonymous struct.
5597   NamedDecl *Anon =
5598       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5599                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5600                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5601                         /*InitStyle=*/ICIS_NoInit);
5602   Anon->setImplicit();
5603 
5604   // Add the anonymous struct object to the current context.
5605   CurContext->addDecl(Anon);
5606 
5607   // Inject the members of the anonymous struct into the current
5608   // context and into the identifier resolver chain for name lookup
5609   // purposes.
5610   SmallVector<NamedDecl*, 2> Chain;
5611   Chain.push_back(Anon);
5612 
5613   RecordDecl *RecordDef = Record->getDefinition();
5614   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5615                                diag::err_field_incomplete_or_sizeless) ||
5616       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5617                                           AS_none, Chain)) {
5618     Anon->setInvalidDecl();
5619     ParentDecl->setInvalidDecl();
5620   }
5621 
5622   return Anon;
5623 }
5624 
5625 /// GetNameForDeclarator - Determine the full declaration name for the
5626 /// given Declarator.
5627 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5628   return GetNameFromUnqualifiedId(D.getName());
5629 }
5630 
5631 /// Retrieves the declaration name from a parsed unqualified-id.
5632 DeclarationNameInfo
5633 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5634   DeclarationNameInfo NameInfo;
5635   NameInfo.setLoc(Name.StartLocation);
5636 
5637   switch (Name.getKind()) {
5638 
5639   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5640   case UnqualifiedIdKind::IK_Identifier:
5641     NameInfo.setName(Name.Identifier);
5642     return NameInfo;
5643 
5644   case UnqualifiedIdKind::IK_DeductionGuideName: {
5645     // C++ [temp.deduct.guide]p3:
5646     //   The simple-template-id shall name a class template specialization.
5647     //   The template-name shall be the same identifier as the template-name
5648     //   of the simple-template-id.
5649     // These together intend to imply that the template-name shall name a
5650     // class template.
5651     // FIXME: template<typename T> struct X {};
5652     //        template<typename T> using Y = X<T>;
5653     //        Y(int) -> Y<int>;
5654     //   satisfies these rules but does not name a class template.
5655     TemplateName TN = Name.TemplateName.get().get();
5656     auto *Template = TN.getAsTemplateDecl();
5657     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5658       Diag(Name.StartLocation,
5659            diag::err_deduction_guide_name_not_class_template)
5660         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5661       if (Template)
5662         Diag(Template->getLocation(), diag::note_template_decl_here);
5663       return DeclarationNameInfo();
5664     }
5665 
5666     NameInfo.setName(
5667         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5668     return NameInfo;
5669   }
5670 
5671   case UnqualifiedIdKind::IK_OperatorFunctionId:
5672     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5673                                            Name.OperatorFunctionId.Operator));
5674     NameInfo.setCXXOperatorNameRange(SourceRange(
5675         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5676     return NameInfo;
5677 
5678   case UnqualifiedIdKind::IK_LiteralOperatorId:
5679     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5680                                                            Name.Identifier));
5681     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5682     return NameInfo;
5683 
5684   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5685     TypeSourceInfo *TInfo;
5686     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5687     if (Ty.isNull())
5688       return DeclarationNameInfo();
5689     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5690                                                Context.getCanonicalType(Ty)));
5691     NameInfo.setNamedTypeInfo(TInfo);
5692     return NameInfo;
5693   }
5694 
5695   case UnqualifiedIdKind::IK_ConstructorName: {
5696     TypeSourceInfo *TInfo;
5697     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5698     if (Ty.isNull())
5699       return DeclarationNameInfo();
5700     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5701                                               Context.getCanonicalType(Ty)));
5702     NameInfo.setNamedTypeInfo(TInfo);
5703     return NameInfo;
5704   }
5705 
5706   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5707     // In well-formed code, we can only have a constructor
5708     // template-id that refers to the current context, so go there
5709     // to find the actual type being constructed.
5710     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5711     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5712       return DeclarationNameInfo();
5713 
5714     // Determine the type of the class being constructed.
5715     QualType CurClassType = Context.getTypeDeclType(CurClass);
5716 
5717     // FIXME: Check two things: that the template-id names the same type as
5718     // CurClassType, and that the template-id does not occur when the name
5719     // was qualified.
5720 
5721     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5722                                     Context.getCanonicalType(CurClassType)));
5723     // FIXME: should we retrieve TypeSourceInfo?
5724     NameInfo.setNamedTypeInfo(nullptr);
5725     return NameInfo;
5726   }
5727 
5728   case UnqualifiedIdKind::IK_DestructorName: {
5729     TypeSourceInfo *TInfo;
5730     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5731     if (Ty.isNull())
5732       return DeclarationNameInfo();
5733     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5734                                               Context.getCanonicalType(Ty)));
5735     NameInfo.setNamedTypeInfo(TInfo);
5736     return NameInfo;
5737   }
5738 
5739   case UnqualifiedIdKind::IK_TemplateId: {
5740     TemplateName TName = Name.TemplateId->Template.get();
5741     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5742     return Context.getNameForTemplate(TName, TNameLoc);
5743   }
5744 
5745   } // switch (Name.getKind())
5746 
5747   llvm_unreachable("Unknown name kind");
5748 }
5749 
5750 static QualType getCoreType(QualType Ty) {
5751   do {
5752     if (Ty->isPointerType() || Ty->isReferenceType())
5753       Ty = Ty->getPointeeType();
5754     else if (Ty->isArrayType())
5755       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5756     else
5757       return Ty.withoutLocalFastQualifiers();
5758   } while (true);
5759 }
5760 
5761 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5762 /// and Definition have "nearly" matching parameters. This heuristic is
5763 /// used to improve diagnostics in the case where an out-of-line function
5764 /// definition doesn't match any declaration within the class or namespace.
5765 /// Also sets Params to the list of indices to the parameters that differ
5766 /// between the declaration and the definition. If hasSimilarParameters
5767 /// returns true and Params is empty, then all of the parameters match.
5768 static bool hasSimilarParameters(ASTContext &Context,
5769                                      FunctionDecl *Declaration,
5770                                      FunctionDecl *Definition,
5771                                      SmallVectorImpl<unsigned> &Params) {
5772   Params.clear();
5773   if (Declaration->param_size() != Definition->param_size())
5774     return false;
5775   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5776     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5777     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5778 
5779     // The parameter types are identical
5780     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5781       continue;
5782 
5783     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5784     QualType DefParamBaseTy = getCoreType(DefParamTy);
5785     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5786     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5787 
5788     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5789         (DeclTyName && DeclTyName == DefTyName))
5790       Params.push_back(Idx);
5791     else  // The two parameters aren't even close
5792       return false;
5793   }
5794 
5795   return true;
5796 }
5797 
5798 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5799 /// declarator needs to be rebuilt in the current instantiation.
5800 /// Any bits of declarator which appear before the name are valid for
5801 /// consideration here.  That's specifically the type in the decl spec
5802 /// and the base type in any member-pointer chunks.
5803 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5804                                                     DeclarationName Name) {
5805   // The types we specifically need to rebuild are:
5806   //   - typenames, typeofs, and decltypes
5807   //   - types which will become injected class names
5808   // Of course, we also need to rebuild any type referencing such a
5809   // type.  It's safest to just say "dependent", but we call out a
5810   // few cases here.
5811 
5812   DeclSpec &DS = D.getMutableDeclSpec();
5813   switch (DS.getTypeSpecType()) {
5814   case DeclSpec::TST_typename:
5815   case DeclSpec::TST_typeofType:
5816   case DeclSpec::TST_underlyingType:
5817   case DeclSpec::TST_atomic: {
5818     // Grab the type from the parser.
5819     TypeSourceInfo *TSI = nullptr;
5820     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5821     if (T.isNull() || !T->isInstantiationDependentType()) break;
5822 
5823     // Make sure there's a type source info.  This isn't really much
5824     // of a waste; most dependent types should have type source info
5825     // attached already.
5826     if (!TSI)
5827       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5828 
5829     // Rebuild the type in the current instantiation.
5830     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5831     if (!TSI) return true;
5832 
5833     // Store the new type back in the decl spec.
5834     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5835     DS.UpdateTypeRep(LocType);
5836     break;
5837   }
5838 
5839   case DeclSpec::TST_decltype:
5840   case DeclSpec::TST_typeofExpr: {
5841     Expr *E = DS.getRepAsExpr();
5842     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5843     if (Result.isInvalid()) return true;
5844     DS.UpdateExprRep(Result.get());
5845     break;
5846   }
5847 
5848   default:
5849     // Nothing to do for these decl specs.
5850     break;
5851   }
5852 
5853   // It doesn't matter what order we do this in.
5854   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5855     DeclaratorChunk &Chunk = D.getTypeObject(I);
5856 
5857     // The only type information in the declarator which can come
5858     // before the declaration name is the base type of a member
5859     // pointer.
5860     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5861       continue;
5862 
5863     // Rebuild the scope specifier in-place.
5864     CXXScopeSpec &SS = Chunk.Mem.Scope();
5865     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5866       return true;
5867   }
5868 
5869   return false;
5870 }
5871 
5872 /// Returns true if the declaration is declared in a system header or from a
5873 /// system macro.
5874 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5875   return SM.isInSystemHeader(D->getLocation()) ||
5876          SM.isInSystemMacro(D->getLocation());
5877 }
5878 
5879 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5880   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5881   // of system decl.
5882   if (D->getPreviousDecl() || D->isImplicit())
5883     return;
5884   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5885   if (Status != ReservedIdentifierStatus::NotReserved &&
5886       !isFromSystemHeader(Context.getSourceManager(), D)) {
5887     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5888         << D << static_cast<int>(Status);
5889   }
5890 }
5891 
5892 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5893   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5894   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5895 
5896   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5897       Dcl && Dcl->getDeclContext()->isFileContext())
5898     Dcl->setTopLevelDeclInObjCContainer();
5899 
5900   return Dcl;
5901 }
5902 
5903 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5904 ///   If T is the name of a class, then each of the following shall have a
5905 ///   name different from T:
5906 ///     - every static data member of class T;
5907 ///     - every member function of class T
5908 ///     - every member of class T that is itself a type;
5909 /// \returns true if the declaration name violates these rules.
5910 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5911                                    DeclarationNameInfo NameInfo) {
5912   DeclarationName Name = NameInfo.getName();
5913 
5914   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5915   while (Record && Record->isAnonymousStructOrUnion())
5916     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5917   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5918     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5919     return true;
5920   }
5921 
5922   return false;
5923 }
5924 
5925 /// Diagnose a declaration whose declarator-id has the given
5926 /// nested-name-specifier.
5927 ///
5928 /// \param SS The nested-name-specifier of the declarator-id.
5929 ///
5930 /// \param DC The declaration context to which the nested-name-specifier
5931 /// resolves.
5932 ///
5933 /// \param Name The name of the entity being declared.
5934 ///
5935 /// \param Loc The location of the name of the entity being declared.
5936 ///
5937 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5938 /// we're declaring an explicit / partial specialization / instantiation.
5939 ///
5940 /// \returns true if we cannot safely recover from this error, false otherwise.
5941 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5942                                         DeclarationName Name,
5943                                         SourceLocation Loc, bool IsTemplateId) {
5944   DeclContext *Cur = CurContext;
5945   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5946     Cur = Cur->getParent();
5947 
5948   // If the user provided a superfluous scope specifier that refers back to the
5949   // class in which the entity is already declared, diagnose and ignore it.
5950   //
5951   // class X {
5952   //   void X::f();
5953   // };
5954   //
5955   // Note, it was once ill-formed to give redundant qualification in all
5956   // contexts, but that rule was removed by DR482.
5957   if (Cur->Equals(DC)) {
5958     if (Cur->isRecord()) {
5959       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5960                                       : diag::err_member_extra_qualification)
5961         << Name << FixItHint::CreateRemoval(SS.getRange());
5962       SS.clear();
5963     } else {
5964       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5965     }
5966     return false;
5967   }
5968 
5969   // Check whether the qualifying scope encloses the scope of the original
5970   // declaration. For a template-id, we perform the checks in
5971   // CheckTemplateSpecializationScope.
5972   if (!Cur->Encloses(DC) && !IsTemplateId) {
5973     if (Cur->isRecord())
5974       Diag(Loc, diag::err_member_qualification)
5975         << Name << SS.getRange();
5976     else if (isa<TranslationUnitDecl>(DC))
5977       Diag(Loc, diag::err_invalid_declarator_global_scope)
5978         << Name << SS.getRange();
5979     else if (isa<FunctionDecl>(Cur))
5980       Diag(Loc, diag::err_invalid_declarator_in_function)
5981         << Name << SS.getRange();
5982     else if (isa<BlockDecl>(Cur))
5983       Diag(Loc, diag::err_invalid_declarator_in_block)
5984         << Name << SS.getRange();
5985     else if (isa<ExportDecl>(Cur)) {
5986       if (!isa<NamespaceDecl>(DC))
5987         Diag(Loc, diag::err_export_non_namespace_scope_name)
5988             << Name << SS.getRange();
5989       else
5990         // The cases that DC is not NamespaceDecl should be handled in
5991         // CheckRedeclarationExported.
5992         return false;
5993     } else
5994       Diag(Loc, diag::err_invalid_declarator_scope)
5995       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5996 
5997     return true;
5998   }
5999 
6000   if (Cur->isRecord()) {
6001     // Cannot qualify members within a class.
6002     Diag(Loc, diag::err_member_qualification)
6003       << Name << SS.getRange();
6004     SS.clear();
6005 
6006     // C++ constructors and destructors with incorrect scopes can break
6007     // our AST invariants by having the wrong underlying types. If
6008     // that's the case, then drop this declaration entirely.
6009     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6010          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6011         !Context.hasSameType(Name.getCXXNameType(),
6012                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6013       return true;
6014 
6015     return false;
6016   }
6017 
6018   // C++11 [dcl.meaning]p1:
6019   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6020   //   not begin with a decltype-specifer"
6021   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6022   while (SpecLoc.getPrefix())
6023     SpecLoc = SpecLoc.getPrefix();
6024   if (isa_and_nonnull<DecltypeType>(
6025           SpecLoc.getNestedNameSpecifier()->getAsType()))
6026     Diag(Loc, diag::err_decltype_in_declarator)
6027       << SpecLoc.getTypeLoc().getSourceRange();
6028 
6029   return false;
6030 }
6031 
6032 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6033                                   MultiTemplateParamsArg TemplateParamLists) {
6034   // TODO: consider using NameInfo for diagnostic.
6035   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6036   DeclarationName Name = NameInfo.getName();
6037 
6038   // All of these full declarators require an identifier.  If it doesn't have
6039   // one, the ParsedFreeStandingDeclSpec action should be used.
6040   if (D.isDecompositionDeclarator()) {
6041     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6042   } else if (!Name) {
6043     if (!D.isInvalidType())  // Reject this if we think it is valid.
6044       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6045           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6046     return nullptr;
6047   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6048     return nullptr;
6049 
6050   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6051   // we find one that is.
6052   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6053          (S->getFlags() & Scope::TemplateParamScope) != 0)
6054     S = S->getParent();
6055 
6056   DeclContext *DC = CurContext;
6057   if (D.getCXXScopeSpec().isInvalid())
6058     D.setInvalidType();
6059   else if (D.getCXXScopeSpec().isSet()) {
6060     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6061                                         UPPC_DeclarationQualifier))
6062       return nullptr;
6063 
6064     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6065     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6066     if (!DC || isa<EnumDecl>(DC)) {
6067       // If we could not compute the declaration context, it's because the
6068       // declaration context is dependent but does not refer to a class,
6069       // class template, or class template partial specialization. Complain
6070       // and return early, to avoid the coming semantic disaster.
6071       Diag(D.getIdentifierLoc(),
6072            diag::err_template_qualified_declarator_no_match)
6073         << D.getCXXScopeSpec().getScopeRep()
6074         << D.getCXXScopeSpec().getRange();
6075       return nullptr;
6076     }
6077     bool IsDependentContext = DC->isDependentContext();
6078 
6079     if (!IsDependentContext &&
6080         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6081       return nullptr;
6082 
6083     // If a class is incomplete, do not parse entities inside it.
6084     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6085       Diag(D.getIdentifierLoc(),
6086            diag::err_member_def_undefined_record)
6087         << Name << DC << D.getCXXScopeSpec().getRange();
6088       return nullptr;
6089     }
6090     if (!D.getDeclSpec().isFriendSpecified()) {
6091       if (diagnoseQualifiedDeclaration(
6092               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6093               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6094         if (DC->isRecord())
6095           return nullptr;
6096 
6097         D.setInvalidType();
6098       }
6099     }
6100 
6101     // Check whether we need to rebuild the type of the given
6102     // declaration in the current instantiation.
6103     if (EnteringContext && IsDependentContext &&
6104         TemplateParamLists.size() != 0) {
6105       ContextRAII SavedContext(*this, DC);
6106       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6107         D.setInvalidType();
6108     }
6109   }
6110 
6111   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6112   QualType R = TInfo->getType();
6113 
6114   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6115                                       UPPC_DeclarationType))
6116     D.setInvalidType();
6117 
6118   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6119                         forRedeclarationInCurContext());
6120 
6121   // See if this is a redefinition of a variable in the same scope.
6122   if (!D.getCXXScopeSpec().isSet()) {
6123     bool IsLinkageLookup = false;
6124     bool CreateBuiltins = false;
6125 
6126     // If the declaration we're planning to build will be a function
6127     // or object with linkage, then look for another declaration with
6128     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6129     //
6130     // If the declaration we're planning to build will be declared with
6131     // external linkage in the translation unit, create any builtin with
6132     // the same name.
6133     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6134       /* Do nothing*/;
6135     else if (CurContext->isFunctionOrMethod() &&
6136              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6137               R->isFunctionType())) {
6138       IsLinkageLookup = true;
6139       CreateBuiltins =
6140           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6141     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6142                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6143       CreateBuiltins = true;
6144 
6145     if (IsLinkageLookup) {
6146       Previous.clear(LookupRedeclarationWithLinkage);
6147       Previous.setRedeclarationKind(ForExternalRedeclaration);
6148     }
6149 
6150     LookupName(Previous, S, CreateBuiltins);
6151   } else { // Something like "int foo::x;"
6152     LookupQualifiedName(Previous, DC);
6153 
6154     // C++ [dcl.meaning]p1:
6155     //   When the declarator-id is qualified, the declaration shall refer to a
6156     //  previously declared member of the class or namespace to which the
6157     //  qualifier refers (or, in the case of a namespace, of an element of the
6158     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6159     //  thereof; [...]
6160     //
6161     // Note that we already checked the context above, and that we do not have
6162     // enough information to make sure that Previous contains the declaration
6163     // we want to match. For example, given:
6164     //
6165     //   class X {
6166     //     void f();
6167     //     void f(float);
6168     //   };
6169     //
6170     //   void X::f(int) { } // ill-formed
6171     //
6172     // In this case, Previous will point to the overload set
6173     // containing the two f's declared in X, but neither of them
6174     // matches.
6175 
6176     // C++ [dcl.meaning]p1:
6177     //   [...] the member shall not merely have been introduced by a
6178     //   using-declaration in the scope of the class or namespace nominated by
6179     //   the nested-name-specifier of the declarator-id.
6180     RemoveUsingDecls(Previous);
6181   }
6182 
6183   if (Previous.isSingleResult() &&
6184       Previous.getFoundDecl()->isTemplateParameter()) {
6185     // Maybe we will complain about the shadowed template parameter.
6186     if (!D.isInvalidType())
6187       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6188                                       Previous.getFoundDecl());
6189 
6190     // Just pretend that we didn't see the previous declaration.
6191     Previous.clear();
6192   }
6193 
6194   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6195     // Forget that the previous declaration is the injected-class-name.
6196     Previous.clear();
6197 
6198   // In C++, the previous declaration we find might be a tag type
6199   // (class or enum). In this case, the new declaration will hide the
6200   // tag type. Note that this applies to functions, function templates, and
6201   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6202   if (Previous.isSingleTagDecl() &&
6203       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6204       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6205     Previous.clear();
6206 
6207   // Check that there are no default arguments other than in the parameters
6208   // of a function declaration (C++ only).
6209   if (getLangOpts().CPlusPlus)
6210     CheckExtraCXXDefaultArguments(D);
6211 
6212   NamedDecl *New;
6213 
6214   bool AddToScope = true;
6215   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6216     if (TemplateParamLists.size()) {
6217       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6218       return nullptr;
6219     }
6220 
6221     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6222   } else if (R->isFunctionType()) {
6223     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6224                                   TemplateParamLists,
6225                                   AddToScope);
6226   } else {
6227     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6228                                   AddToScope);
6229   }
6230 
6231   if (!New)
6232     return nullptr;
6233 
6234   // If this has an identifier and is not a function template specialization,
6235   // add it to the scope stack.
6236   if (New->getDeclName() && AddToScope)
6237     PushOnScopeChains(New, S);
6238 
6239   if (isInOpenMPDeclareTargetContext())
6240     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6241 
6242   return New;
6243 }
6244 
6245 /// Helper method to turn variable array types into constant array
6246 /// types in certain situations which would otherwise be errors (for
6247 /// GCC compatibility).
6248 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6249                                                     ASTContext &Context,
6250                                                     bool &SizeIsNegative,
6251                                                     llvm::APSInt &Oversized) {
6252   // This method tries to turn a variable array into a constant
6253   // array even when the size isn't an ICE.  This is necessary
6254   // for compatibility with code that depends on gcc's buggy
6255   // constant expression folding, like struct {char x[(int)(char*)2];}
6256   SizeIsNegative = false;
6257   Oversized = 0;
6258 
6259   if (T->isDependentType())
6260     return QualType();
6261 
6262   QualifierCollector Qs;
6263   const Type *Ty = Qs.strip(T);
6264 
6265   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6266     QualType Pointee = PTy->getPointeeType();
6267     QualType FixedType =
6268         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6269                                             Oversized);
6270     if (FixedType.isNull()) return FixedType;
6271     FixedType = Context.getPointerType(FixedType);
6272     return Qs.apply(Context, FixedType);
6273   }
6274   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6275     QualType Inner = PTy->getInnerType();
6276     QualType FixedType =
6277         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6278                                             Oversized);
6279     if (FixedType.isNull()) return FixedType;
6280     FixedType = Context.getParenType(FixedType);
6281     return Qs.apply(Context, FixedType);
6282   }
6283 
6284   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6285   if (!VLATy)
6286     return QualType();
6287 
6288   QualType ElemTy = VLATy->getElementType();
6289   if (ElemTy->isVariablyModifiedType()) {
6290     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6291                                                  SizeIsNegative, Oversized);
6292     if (ElemTy.isNull())
6293       return QualType();
6294   }
6295 
6296   Expr::EvalResult Result;
6297   if (!VLATy->getSizeExpr() ||
6298       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6299     return QualType();
6300 
6301   llvm::APSInt Res = Result.Val.getInt();
6302 
6303   // Check whether the array size is negative.
6304   if (Res.isSigned() && Res.isNegative()) {
6305     SizeIsNegative = true;
6306     return QualType();
6307   }
6308 
6309   // Check whether the array is too large to be addressed.
6310   unsigned ActiveSizeBits =
6311       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6312        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6313           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6314           : Res.getActiveBits();
6315   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6316     Oversized = Res;
6317     return QualType();
6318   }
6319 
6320   QualType FoldedArrayType = Context.getConstantArrayType(
6321       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6322   return Qs.apply(Context, FoldedArrayType);
6323 }
6324 
6325 static void
6326 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6327   SrcTL = SrcTL.getUnqualifiedLoc();
6328   DstTL = DstTL.getUnqualifiedLoc();
6329   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6330     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6331     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6332                                       DstPTL.getPointeeLoc());
6333     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6334     return;
6335   }
6336   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6337     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6338     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6339                                       DstPTL.getInnerLoc());
6340     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6341     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6342     return;
6343   }
6344   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6345   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6346   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6347   TypeLoc DstElemTL = DstATL.getElementLoc();
6348   if (VariableArrayTypeLoc SrcElemATL =
6349           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6350     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6351     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6352   } else {
6353     DstElemTL.initializeFullCopy(SrcElemTL);
6354   }
6355   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6356   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6357   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6358 }
6359 
6360 /// Helper method to turn variable array types into constant array
6361 /// types in certain situations which would otherwise be errors (for
6362 /// GCC compatibility).
6363 static TypeSourceInfo*
6364 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6365                                               ASTContext &Context,
6366                                               bool &SizeIsNegative,
6367                                               llvm::APSInt &Oversized) {
6368   QualType FixedTy
6369     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6370                                           SizeIsNegative, Oversized);
6371   if (FixedTy.isNull())
6372     return nullptr;
6373   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6374   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6375                                     FixedTInfo->getTypeLoc());
6376   return FixedTInfo;
6377 }
6378 
6379 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6380 /// true if we were successful.
6381 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6382                                            QualType &T, SourceLocation Loc,
6383                                            unsigned FailedFoldDiagID) {
6384   bool SizeIsNegative;
6385   llvm::APSInt Oversized;
6386   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6387       TInfo, Context, SizeIsNegative, Oversized);
6388   if (FixedTInfo) {
6389     Diag(Loc, diag::ext_vla_folded_to_constant);
6390     TInfo = FixedTInfo;
6391     T = FixedTInfo->getType();
6392     return true;
6393   }
6394 
6395   if (SizeIsNegative)
6396     Diag(Loc, diag::err_typecheck_negative_array_size);
6397   else if (Oversized.getBoolValue())
6398     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6399   else if (FailedFoldDiagID)
6400     Diag(Loc, FailedFoldDiagID);
6401   return false;
6402 }
6403 
6404 /// Register the given locally-scoped extern "C" declaration so
6405 /// that it can be found later for redeclarations. We include any extern "C"
6406 /// declaration that is not visible in the translation unit here, not just
6407 /// function-scope declarations.
6408 void
6409 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6410   if (!getLangOpts().CPlusPlus &&
6411       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6412     // Don't need to track declarations in the TU in C.
6413     return;
6414 
6415   // Note that we have a locally-scoped external with this name.
6416   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6417 }
6418 
6419 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6420   // FIXME: We can have multiple results via __attribute__((overloadable)).
6421   auto Result = Context.getExternCContextDecl()->lookup(Name);
6422   return Result.empty() ? nullptr : *Result.begin();
6423 }
6424 
6425 /// Diagnose function specifiers on a declaration of an identifier that
6426 /// does not identify a function.
6427 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6428   // FIXME: We should probably indicate the identifier in question to avoid
6429   // confusion for constructs like "virtual int a(), b;"
6430   if (DS.isVirtualSpecified())
6431     Diag(DS.getVirtualSpecLoc(),
6432          diag::err_virtual_non_function);
6433 
6434   if (DS.hasExplicitSpecifier())
6435     Diag(DS.getExplicitSpecLoc(),
6436          diag::err_explicit_non_function);
6437 
6438   if (DS.isNoreturnSpecified())
6439     Diag(DS.getNoreturnSpecLoc(),
6440          diag::err_noreturn_non_function);
6441 }
6442 
6443 NamedDecl*
6444 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6445                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6446   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6447   if (D.getCXXScopeSpec().isSet()) {
6448     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6449       << D.getCXXScopeSpec().getRange();
6450     D.setInvalidType();
6451     // Pretend we didn't see the scope specifier.
6452     DC = CurContext;
6453     Previous.clear();
6454   }
6455 
6456   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6457 
6458   if (D.getDeclSpec().isInlineSpecified())
6459     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6460         << getLangOpts().CPlusPlus17;
6461   if (D.getDeclSpec().hasConstexprSpecifier())
6462     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6463         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6464 
6465   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6466     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6467       Diag(D.getName().StartLocation,
6468            diag::err_deduction_guide_invalid_specifier)
6469           << "typedef";
6470     else
6471       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6472           << D.getName().getSourceRange();
6473     return nullptr;
6474   }
6475 
6476   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6477   if (!NewTD) return nullptr;
6478 
6479   // Handle attributes prior to checking for duplicates in MergeVarDecl
6480   ProcessDeclAttributes(S, NewTD, D);
6481 
6482   CheckTypedefForVariablyModifiedType(S, NewTD);
6483 
6484   bool Redeclaration = D.isRedeclaration();
6485   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6486   D.setRedeclaration(Redeclaration);
6487   return ND;
6488 }
6489 
6490 void
6491 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6492   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6493   // then it shall have block scope.
6494   // Note that variably modified types must be fixed before merging the decl so
6495   // that redeclarations will match.
6496   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6497   QualType T = TInfo->getType();
6498   if (T->isVariablyModifiedType()) {
6499     setFunctionHasBranchProtectedScope();
6500 
6501     if (S->getFnParent() == nullptr) {
6502       bool SizeIsNegative;
6503       llvm::APSInt Oversized;
6504       TypeSourceInfo *FixedTInfo =
6505         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6506                                                       SizeIsNegative,
6507                                                       Oversized);
6508       if (FixedTInfo) {
6509         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6510         NewTD->setTypeSourceInfo(FixedTInfo);
6511       } else {
6512         if (SizeIsNegative)
6513           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6514         else if (T->isVariableArrayType())
6515           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6516         else if (Oversized.getBoolValue())
6517           Diag(NewTD->getLocation(), diag::err_array_too_large)
6518             << toString(Oversized, 10);
6519         else
6520           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6521         NewTD->setInvalidDecl();
6522       }
6523     }
6524   }
6525 }
6526 
6527 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6528 /// declares a typedef-name, either using the 'typedef' type specifier or via
6529 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6530 NamedDecl*
6531 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6532                            LookupResult &Previous, bool &Redeclaration) {
6533 
6534   // Find the shadowed declaration before filtering for scope.
6535   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6536 
6537   // Merge the decl with the existing one if appropriate. If the decl is
6538   // in an outer scope, it isn't the same thing.
6539   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6540                        /*AllowInlineNamespace*/false);
6541   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6542   if (!Previous.empty()) {
6543     Redeclaration = true;
6544     MergeTypedefNameDecl(S, NewTD, Previous);
6545   } else {
6546     inferGslPointerAttribute(NewTD);
6547   }
6548 
6549   if (ShadowedDecl && !Redeclaration)
6550     CheckShadow(NewTD, ShadowedDecl, Previous);
6551 
6552   // If this is the C FILE type, notify the AST context.
6553   if (IdentifierInfo *II = NewTD->getIdentifier())
6554     if (!NewTD->isInvalidDecl() &&
6555         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6556       if (II->isStr("FILE"))
6557         Context.setFILEDecl(NewTD);
6558       else if (II->isStr("jmp_buf"))
6559         Context.setjmp_bufDecl(NewTD);
6560       else if (II->isStr("sigjmp_buf"))
6561         Context.setsigjmp_bufDecl(NewTD);
6562       else if (II->isStr("ucontext_t"))
6563         Context.setucontext_tDecl(NewTD);
6564     }
6565 
6566   return NewTD;
6567 }
6568 
6569 /// Determines whether the given declaration is an out-of-scope
6570 /// previous declaration.
6571 ///
6572 /// This routine should be invoked when name lookup has found a
6573 /// previous declaration (PrevDecl) that is not in the scope where a
6574 /// new declaration by the same name is being introduced. If the new
6575 /// declaration occurs in a local scope, previous declarations with
6576 /// linkage may still be considered previous declarations (C99
6577 /// 6.2.2p4-5, C++ [basic.link]p6).
6578 ///
6579 /// \param PrevDecl the previous declaration found by name
6580 /// lookup
6581 ///
6582 /// \param DC the context in which the new declaration is being
6583 /// declared.
6584 ///
6585 /// \returns true if PrevDecl is an out-of-scope previous declaration
6586 /// for a new delcaration with the same name.
6587 static bool
6588 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6589                                 ASTContext &Context) {
6590   if (!PrevDecl)
6591     return false;
6592 
6593   if (!PrevDecl->hasLinkage())
6594     return false;
6595 
6596   if (Context.getLangOpts().CPlusPlus) {
6597     // C++ [basic.link]p6:
6598     //   If there is a visible declaration of an entity with linkage
6599     //   having the same name and type, ignoring entities declared
6600     //   outside the innermost enclosing namespace scope, the block
6601     //   scope declaration declares that same entity and receives the
6602     //   linkage of the previous declaration.
6603     DeclContext *OuterContext = DC->getRedeclContext();
6604     if (!OuterContext->isFunctionOrMethod())
6605       // This rule only applies to block-scope declarations.
6606       return false;
6607 
6608     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6609     if (PrevOuterContext->isRecord())
6610       // We found a member function: ignore it.
6611       return false;
6612 
6613     // Find the innermost enclosing namespace for the new and
6614     // previous declarations.
6615     OuterContext = OuterContext->getEnclosingNamespaceContext();
6616     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6617 
6618     // The previous declaration is in a different namespace, so it
6619     // isn't the same function.
6620     if (!OuterContext->Equals(PrevOuterContext))
6621       return false;
6622   }
6623 
6624   return true;
6625 }
6626 
6627 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6628   CXXScopeSpec &SS = D.getCXXScopeSpec();
6629   if (!SS.isSet()) return;
6630   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6631 }
6632 
6633 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6634   QualType type = decl->getType();
6635   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6636   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6637     // Various kinds of declaration aren't allowed to be __autoreleasing.
6638     unsigned kind = -1U;
6639     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6640       if (var->hasAttr<BlocksAttr>())
6641         kind = 0; // __block
6642       else if (!var->hasLocalStorage())
6643         kind = 1; // global
6644     } else if (isa<ObjCIvarDecl>(decl)) {
6645       kind = 3; // ivar
6646     } else if (isa<FieldDecl>(decl)) {
6647       kind = 2; // field
6648     }
6649 
6650     if (kind != -1U) {
6651       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6652         << kind;
6653     }
6654   } else if (lifetime == Qualifiers::OCL_None) {
6655     // Try to infer lifetime.
6656     if (!type->isObjCLifetimeType())
6657       return false;
6658 
6659     lifetime = type->getObjCARCImplicitLifetime();
6660     type = Context.getLifetimeQualifiedType(type, lifetime);
6661     decl->setType(type);
6662   }
6663 
6664   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6665     // Thread-local variables cannot have lifetime.
6666     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6667         var->getTLSKind()) {
6668       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6669         << var->getType();
6670       return true;
6671     }
6672   }
6673 
6674   return false;
6675 }
6676 
6677 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6678   if (Decl->getType().hasAddressSpace())
6679     return;
6680   if (Decl->getType()->isDependentType())
6681     return;
6682   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6683     QualType Type = Var->getType();
6684     if (Type->isSamplerT() || Type->isVoidType())
6685       return;
6686     LangAS ImplAS = LangAS::opencl_private;
6687     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6688     // __opencl_c_program_scope_global_variables feature, the address space
6689     // for a variable at program scope or a static or extern variable inside
6690     // a function are inferred to be __global.
6691     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6692         Var->hasGlobalStorage())
6693       ImplAS = LangAS::opencl_global;
6694     // If the original type from a decayed type is an array type and that array
6695     // type has no address space yet, deduce it now.
6696     if (auto DT = dyn_cast<DecayedType>(Type)) {
6697       auto OrigTy = DT->getOriginalType();
6698       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6699         // Add the address space to the original array type and then propagate
6700         // that to the element type through `getAsArrayType`.
6701         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6702         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6703         // Re-generate the decayed type.
6704         Type = Context.getDecayedType(OrigTy);
6705       }
6706     }
6707     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6708     // Apply any qualifiers (including address space) from the array type to
6709     // the element type. This implements C99 6.7.3p8: "If the specification of
6710     // an array type includes any type qualifiers, the element type is so
6711     // qualified, not the array type."
6712     if (Type->isArrayType())
6713       Type = QualType(Context.getAsArrayType(Type), 0);
6714     Decl->setType(Type);
6715   }
6716 }
6717 
6718 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6719   // Ensure that an auto decl is deduced otherwise the checks below might cache
6720   // the wrong linkage.
6721   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6722 
6723   // 'weak' only applies to declarations with external linkage.
6724   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6725     if (!ND.isExternallyVisible()) {
6726       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6727       ND.dropAttr<WeakAttr>();
6728     }
6729   }
6730   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6731     if (ND.isExternallyVisible()) {
6732       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6733       ND.dropAttr<WeakRefAttr>();
6734       ND.dropAttr<AliasAttr>();
6735     }
6736   }
6737 
6738   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6739     if (VD->hasInit()) {
6740       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6741         assert(VD->isThisDeclarationADefinition() &&
6742                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6743         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6744         VD->dropAttr<AliasAttr>();
6745       }
6746     }
6747   }
6748 
6749   // 'selectany' only applies to externally visible variable declarations.
6750   // It does not apply to functions.
6751   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6752     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6753       S.Diag(Attr->getLocation(),
6754              diag::err_attribute_selectany_non_extern_data);
6755       ND.dropAttr<SelectAnyAttr>();
6756     }
6757   }
6758 
6759   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6760     auto *VD = dyn_cast<VarDecl>(&ND);
6761     bool IsAnonymousNS = false;
6762     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6763     if (VD) {
6764       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6765       while (NS && !IsAnonymousNS) {
6766         IsAnonymousNS = NS->isAnonymousNamespace();
6767         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6768       }
6769     }
6770     // dll attributes require external linkage. Static locals may have external
6771     // linkage but still cannot be explicitly imported or exported.
6772     // In Microsoft mode, a variable defined in anonymous namespace must have
6773     // external linkage in order to be exported.
6774     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6775     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6776         (!AnonNSInMicrosoftMode &&
6777          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6778       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6779         << &ND << Attr;
6780       ND.setInvalidDecl();
6781     }
6782   }
6783 
6784   // Check the attributes on the function type, if any.
6785   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6786     // Don't declare this variable in the second operand of the for-statement;
6787     // GCC miscompiles that by ending its lifetime before evaluating the
6788     // third operand. See gcc.gnu.org/PR86769.
6789     AttributedTypeLoc ATL;
6790     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6791          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6792          TL = ATL.getModifiedLoc()) {
6793       // The [[lifetimebound]] attribute can be applied to the implicit object
6794       // parameter of a non-static member function (other than a ctor or dtor)
6795       // by applying it to the function type.
6796       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6797         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6798         if (!MD || MD->isStatic()) {
6799           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6800               << !MD << A->getRange();
6801         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6802           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6803               << isa<CXXDestructorDecl>(MD) << A->getRange();
6804         }
6805       }
6806     }
6807   }
6808 }
6809 
6810 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6811                                            NamedDecl *NewDecl,
6812                                            bool IsSpecialization,
6813                                            bool IsDefinition) {
6814   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6815     return;
6816 
6817   bool IsTemplate = false;
6818   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6819     OldDecl = OldTD->getTemplatedDecl();
6820     IsTemplate = true;
6821     if (!IsSpecialization)
6822       IsDefinition = false;
6823   }
6824   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6825     NewDecl = NewTD->getTemplatedDecl();
6826     IsTemplate = true;
6827   }
6828 
6829   if (!OldDecl || !NewDecl)
6830     return;
6831 
6832   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6833   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6834   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6835   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6836 
6837   // dllimport and dllexport are inheritable attributes so we have to exclude
6838   // inherited attribute instances.
6839   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6840                     (NewExportAttr && !NewExportAttr->isInherited());
6841 
6842   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6843   // the only exception being explicit specializations.
6844   // Implicitly generated declarations are also excluded for now because there
6845   // is no other way to switch these to use dllimport or dllexport.
6846   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6847 
6848   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6849     // Allow with a warning for free functions and global variables.
6850     bool JustWarn = false;
6851     if (!OldDecl->isCXXClassMember()) {
6852       auto *VD = dyn_cast<VarDecl>(OldDecl);
6853       if (VD && !VD->getDescribedVarTemplate())
6854         JustWarn = true;
6855       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6856       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6857         JustWarn = true;
6858     }
6859 
6860     // We cannot change a declaration that's been used because IR has already
6861     // been emitted. Dllimported functions will still work though (modulo
6862     // address equality) as they can use the thunk.
6863     if (OldDecl->isUsed())
6864       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6865         JustWarn = false;
6866 
6867     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6868                                : diag::err_attribute_dll_redeclaration;
6869     S.Diag(NewDecl->getLocation(), DiagID)
6870         << NewDecl
6871         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6872     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6873     if (!JustWarn) {
6874       NewDecl->setInvalidDecl();
6875       return;
6876     }
6877   }
6878 
6879   // A redeclaration is not allowed to drop a dllimport attribute, the only
6880   // exceptions being inline function definitions (except for function
6881   // templates), local extern declarations, qualified friend declarations or
6882   // special MSVC extension: in the last case, the declaration is treated as if
6883   // it were marked dllexport.
6884   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6885   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6886   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6887     // Ignore static data because out-of-line definitions are diagnosed
6888     // separately.
6889     IsStaticDataMember = VD->isStaticDataMember();
6890     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6891                    VarDecl::DeclarationOnly;
6892   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6893     IsInline = FD->isInlined();
6894     IsQualifiedFriend = FD->getQualifier() &&
6895                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6896   }
6897 
6898   if (OldImportAttr && !HasNewAttr &&
6899       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6900       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6901     if (IsMicrosoftABI && IsDefinition) {
6902       S.Diag(NewDecl->getLocation(),
6903              diag::warn_redeclaration_without_import_attribute)
6904           << NewDecl;
6905       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6906       NewDecl->dropAttr<DLLImportAttr>();
6907       NewDecl->addAttr(
6908           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6909     } else {
6910       S.Diag(NewDecl->getLocation(),
6911              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6912           << NewDecl << OldImportAttr;
6913       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6914       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6915       OldDecl->dropAttr<DLLImportAttr>();
6916       NewDecl->dropAttr<DLLImportAttr>();
6917     }
6918   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6919     // In MinGW, seeing a function declared inline drops the dllimport
6920     // attribute.
6921     OldDecl->dropAttr<DLLImportAttr>();
6922     NewDecl->dropAttr<DLLImportAttr>();
6923     S.Diag(NewDecl->getLocation(),
6924            diag::warn_dllimport_dropped_from_inline_function)
6925         << NewDecl << OldImportAttr;
6926   }
6927 
6928   // A specialization of a class template member function is processed here
6929   // since it's a redeclaration. If the parent class is dllexport, the
6930   // specialization inherits that attribute. This doesn't happen automatically
6931   // since the parent class isn't instantiated until later.
6932   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6933     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6934         !NewImportAttr && !NewExportAttr) {
6935       if (const DLLExportAttr *ParentExportAttr =
6936               MD->getParent()->getAttr<DLLExportAttr>()) {
6937         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6938         NewAttr->setInherited(true);
6939         NewDecl->addAttr(NewAttr);
6940       }
6941     }
6942   }
6943 }
6944 
6945 /// Given that we are within the definition of the given function,
6946 /// will that definition behave like C99's 'inline', where the
6947 /// definition is discarded except for optimization purposes?
6948 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6949   // Try to avoid calling GetGVALinkageForFunction.
6950 
6951   // All cases of this require the 'inline' keyword.
6952   if (!FD->isInlined()) return false;
6953 
6954   // This is only possible in C++ with the gnu_inline attribute.
6955   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6956     return false;
6957 
6958   // Okay, go ahead and call the relatively-more-expensive function.
6959   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6960 }
6961 
6962 /// Determine whether a variable is extern "C" prior to attaching
6963 /// an initializer. We can't just call isExternC() here, because that
6964 /// will also compute and cache whether the declaration is externally
6965 /// visible, which might change when we attach the initializer.
6966 ///
6967 /// This can only be used if the declaration is known to not be a
6968 /// redeclaration of an internal linkage declaration.
6969 ///
6970 /// For instance:
6971 ///
6972 ///   auto x = []{};
6973 ///
6974 /// Attaching the initializer here makes this declaration not externally
6975 /// visible, because its type has internal linkage.
6976 ///
6977 /// FIXME: This is a hack.
6978 template<typename T>
6979 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6980   if (S.getLangOpts().CPlusPlus) {
6981     // In C++, the overloadable attribute negates the effects of extern "C".
6982     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6983       return false;
6984 
6985     // So do CUDA's host/device attributes.
6986     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6987                                  D->template hasAttr<CUDAHostAttr>()))
6988       return false;
6989   }
6990   return D->isExternC();
6991 }
6992 
6993 static bool shouldConsiderLinkage(const VarDecl *VD) {
6994   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6995   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6996       isa<OMPDeclareMapperDecl>(DC))
6997     return VD->hasExternalStorage();
6998   if (DC->isFileContext())
6999     return true;
7000   if (DC->isRecord())
7001     return false;
7002   if (isa<RequiresExprBodyDecl>(DC))
7003     return false;
7004   llvm_unreachable("Unexpected context");
7005 }
7006 
7007 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7008   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7009   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7010       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7011     return true;
7012   if (DC->isRecord())
7013     return false;
7014   llvm_unreachable("Unexpected context");
7015 }
7016 
7017 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7018                           ParsedAttr::Kind Kind) {
7019   // Check decl attributes on the DeclSpec.
7020   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7021     return true;
7022 
7023   // Walk the declarator structure, checking decl attributes that were in a type
7024   // position to the decl itself.
7025   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7026     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7027       return true;
7028   }
7029 
7030   // Finally, check attributes on the decl itself.
7031   return PD.getAttributes().hasAttribute(Kind);
7032 }
7033 
7034 /// Adjust the \c DeclContext for a function or variable that might be a
7035 /// function-local external declaration.
7036 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7037   if (!DC->isFunctionOrMethod())
7038     return false;
7039 
7040   // If this is a local extern function or variable declared within a function
7041   // template, don't add it into the enclosing namespace scope until it is
7042   // instantiated; it might have a dependent type right now.
7043   if (DC->isDependentContext())
7044     return true;
7045 
7046   // C++11 [basic.link]p7:
7047   //   When a block scope declaration of an entity with linkage is not found to
7048   //   refer to some other declaration, then that entity is a member of the
7049   //   innermost enclosing namespace.
7050   //
7051   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7052   // semantically-enclosing namespace, not a lexically-enclosing one.
7053   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7054     DC = DC->getParent();
7055   return true;
7056 }
7057 
7058 /// Returns true if given declaration has external C language linkage.
7059 static bool isDeclExternC(const Decl *D) {
7060   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7061     return FD->isExternC();
7062   if (const auto *VD = dyn_cast<VarDecl>(D))
7063     return VD->isExternC();
7064 
7065   llvm_unreachable("Unknown type of decl!");
7066 }
7067 
7068 /// Returns true if there hasn't been any invalid type diagnosed.
7069 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7070   DeclContext *DC = NewVD->getDeclContext();
7071   QualType R = NewVD->getType();
7072 
7073   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7074   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7075   // argument.
7076   if (R->isImageType() || R->isPipeType()) {
7077     Se.Diag(NewVD->getLocation(),
7078             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7079         << R;
7080     NewVD->setInvalidDecl();
7081     return false;
7082   }
7083 
7084   // OpenCL v1.2 s6.9.r:
7085   // The event type cannot be used to declare a program scope variable.
7086   // OpenCL v2.0 s6.9.q:
7087   // The clk_event_t and reserve_id_t types cannot be declared in program
7088   // scope.
7089   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7090     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7091       Se.Diag(NewVD->getLocation(),
7092               diag::err_invalid_type_for_program_scope_var)
7093           << R;
7094       NewVD->setInvalidDecl();
7095       return false;
7096     }
7097   }
7098 
7099   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7100   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7101                                                Se.getLangOpts())) {
7102     QualType NR = R.getCanonicalType();
7103     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7104            NR->isReferenceType()) {
7105       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7106           NR->isFunctionReferenceType()) {
7107         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7108             << NR->isReferenceType();
7109         NewVD->setInvalidDecl();
7110         return false;
7111       }
7112       NR = NR->getPointeeType();
7113     }
7114   }
7115 
7116   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7117                                                Se.getLangOpts())) {
7118     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7119     // half array type (unless the cl_khr_fp16 extension is enabled).
7120     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7121       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7122       NewVD->setInvalidDecl();
7123       return false;
7124     }
7125   }
7126 
7127   // OpenCL v1.2 s6.9.r:
7128   // The event type cannot be used with the __local, __constant and __global
7129   // address space qualifiers.
7130   if (R->isEventT()) {
7131     if (R.getAddressSpace() != LangAS::opencl_private) {
7132       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7133       NewVD->setInvalidDecl();
7134       return false;
7135     }
7136   }
7137 
7138   if (R->isSamplerT()) {
7139     // OpenCL v1.2 s6.9.b p4:
7140     // The sampler type cannot be used with the __local and __global address
7141     // space qualifiers.
7142     if (R.getAddressSpace() == LangAS::opencl_local ||
7143         R.getAddressSpace() == LangAS::opencl_global) {
7144       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7145       NewVD->setInvalidDecl();
7146     }
7147 
7148     // OpenCL v1.2 s6.12.14.1:
7149     // A global sampler must be declared with either the constant address
7150     // space qualifier or with the const qualifier.
7151     if (DC->isTranslationUnit() &&
7152         !(R.getAddressSpace() == LangAS::opencl_constant ||
7153           R.isConstQualified())) {
7154       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7155       NewVD->setInvalidDecl();
7156     }
7157     if (NewVD->isInvalidDecl())
7158       return false;
7159   }
7160 
7161   return true;
7162 }
7163 
7164 template <typename AttrTy>
7165 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7166   const TypedefNameDecl *TND = TT->getDecl();
7167   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7168     AttrTy *Clone = Attribute->clone(S.Context);
7169     Clone->setInherited(true);
7170     D->addAttr(Clone);
7171   }
7172 }
7173 
7174 NamedDecl *Sema::ActOnVariableDeclarator(
7175     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7176     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7177     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7178   QualType R = TInfo->getType();
7179   DeclarationName Name = GetNameForDeclarator(D).getName();
7180 
7181   IdentifierInfo *II = Name.getAsIdentifierInfo();
7182 
7183   if (D.isDecompositionDeclarator()) {
7184     // Take the name of the first declarator as our name for diagnostic
7185     // purposes.
7186     auto &Decomp = D.getDecompositionDeclarator();
7187     if (!Decomp.bindings().empty()) {
7188       II = Decomp.bindings()[0].Name;
7189       Name = II;
7190     }
7191   } else if (!II) {
7192     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7193     return nullptr;
7194   }
7195 
7196 
7197   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7198   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7199 
7200   // dllimport globals without explicit storage class are treated as extern. We
7201   // have to change the storage class this early to get the right DeclContext.
7202   if (SC == SC_None && !DC->isRecord() &&
7203       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7204       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7205     SC = SC_Extern;
7206 
7207   DeclContext *OriginalDC = DC;
7208   bool IsLocalExternDecl = SC == SC_Extern &&
7209                            adjustContextForLocalExternDecl(DC);
7210 
7211   if (SCSpec == DeclSpec::SCS_mutable) {
7212     // mutable can only appear on non-static class members, so it's always
7213     // an error here
7214     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7215     D.setInvalidType();
7216     SC = SC_None;
7217   }
7218 
7219   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7220       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7221                               D.getDeclSpec().getStorageClassSpecLoc())) {
7222     // In C++11, the 'register' storage class specifier is deprecated.
7223     // Suppress the warning in system macros, it's used in macros in some
7224     // popular C system headers, such as in glibc's htonl() macro.
7225     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7226          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7227                                    : diag::warn_deprecated_register)
7228       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7229   }
7230 
7231   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7232 
7233   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7234     // C99 6.9p2: The storage-class specifiers auto and register shall not
7235     // appear in the declaration specifiers in an external declaration.
7236     // Global Register+Asm is a GNU extension we support.
7237     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7238       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7239       D.setInvalidType();
7240     }
7241   }
7242 
7243   // If this variable has a VLA type and an initializer, try to
7244   // fold to a constant-sized type. This is otherwise invalid.
7245   if (D.hasInitializer() && R->isVariableArrayType())
7246     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7247                                     /*DiagID=*/0);
7248 
7249   bool IsMemberSpecialization = false;
7250   bool IsVariableTemplateSpecialization = false;
7251   bool IsPartialSpecialization = false;
7252   bool IsVariableTemplate = false;
7253   VarDecl *NewVD = nullptr;
7254   VarTemplateDecl *NewTemplate = nullptr;
7255   TemplateParameterList *TemplateParams = nullptr;
7256   if (!getLangOpts().CPlusPlus) {
7257     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7258                             II, R, TInfo, SC);
7259 
7260     if (R->getContainedDeducedType())
7261       ParsingInitForAutoVars.insert(NewVD);
7262 
7263     if (D.isInvalidType())
7264       NewVD->setInvalidDecl();
7265 
7266     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7267         NewVD->hasLocalStorage())
7268       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7269                             NTCUC_AutoVar, NTCUK_Destruct);
7270   } else {
7271     bool Invalid = false;
7272 
7273     if (DC->isRecord() && !CurContext->isRecord()) {
7274       // This is an out-of-line definition of a static data member.
7275       switch (SC) {
7276       case SC_None:
7277         break;
7278       case SC_Static:
7279         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7280              diag::err_static_out_of_line)
7281           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7282         break;
7283       case SC_Auto:
7284       case SC_Register:
7285       case SC_Extern:
7286         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7287         // to names of variables declared in a block or to function parameters.
7288         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7289         // of class members
7290 
7291         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7292              diag::err_storage_class_for_static_member)
7293           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7294         break;
7295       case SC_PrivateExtern:
7296         llvm_unreachable("C storage class in c++!");
7297       }
7298     }
7299 
7300     if (SC == SC_Static && CurContext->isRecord()) {
7301       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7302         // Walk up the enclosing DeclContexts to check for any that are
7303         // incompatible with static data members.
7304         const DeclContext *FunctionOrMethod = nullptr;
7305         const CXXRecordDecl *AnonStruct = nullptr;
7306         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7307           if (Ctxt->isFunctionOrMethod()) {
7308             FunctionOrMethod = Ctxt;
7309             break;
7310           }
7311           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7312           if (ParentDecl && !ParentDecl->getDeclName()) {
7313             AnonStruct = ParentDecl;
7314             break;
7315           }
7316         }
7317         if (FunctionOrMethod) {
7318           // C++ [class.static.data]p5: A local class shall not have static data
7319           // members.
7320           Diag(D.getIdentifierLoc(),
7321                diag::err_static_data_member_not_allowed_in_local_class)
7322             << Name << RD->getDeclName() << RD->getTagKind();
7323         } else if (AnonStruct) {
7324           // C++ [class.static.data]p4: Unnamed classes and classes contained
7325           // directly or indirectly within unnamed classes shall not contain
7326           // static data members.
7327           Diag(D.getIdentifierLoc(),
7328                diag::err_static_data_member_not_allowed_in_anon_struct)
7329             << Name << AnonStruct->getTagKind();
7330           Invalid = true;
7331         } else if (RD->isUnion()) {
7332           // C++98 [class.union]p1: If a union contains a static data member,
7333           // the program is ill-formed. C++11 drops this restriction.
7334           Diag(D.getIdentifierLoc(),
7335                getLangOpts().CPlusPlus11
7336                  ? diag::warn_cxx98_compat_static_data_member_in_union
7337                  : diag::ext_static_data_member_in_union) << Name;
7338         }
7339       }
7340     }
7341 
7342     // Match up the template parameter lists with the scope specifier, then
7343     // determine whether we have a template or a template specialization.
7344     bool InvalidScope = false;
7345     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7346         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7347         D.getCXXScopeSpec(),
7348         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7349             ? D.getName().TemplateId
7350             : nullptr,
7351         TemplateParamLists,
7352         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7353     Invalid |= InvalidScope;
7354 
7355     if (TemplateParams) {
7356       if (!TemplateParams->size() &&
7357           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7358         // There is an extraneous 'template<>' for this variable. Complain
7359         // about it, but allow the declaration of the variable.
7360         Diag(TemplateParams->getTemplateLoc(),
7361              diag::err_template_variable_noparams)
7362           << II
7363           << SourceRange(TemplateParams->getTemplateLoc(),
7364                          TemplateParams->getRAngleLoc());
7365         TemplateParams = nullptr;
7366       } else {
7367         // Check that we can declare a template here.
7368         if (CheckTemplateDeclScope(S, TemplateParams))
7369           return nullptr;
7370 
7371         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7372           // This is an explicit specialization or a partial specialization.
7373           IsVariableTemplateSpecialization = true;
7374           IsPartialSpecialization = TemplateParams->size() > 0;
7375         } else { // if (TemplateParams->size() > 0)
7376           // This is a template declaration.
7377           IsVariableTemplate = true;
7378 
7379           // Only C++1y supports variable templates (N3651).
7380           Diag(D.getIdentifierLoc(),
7381                getLangOpts().CPlusPlus14
7382                    ? diag::warn_cxx11_compat_variable_template
7383                    : diag::ext_variable_template);
7384         }
7385       }
7386     } else {
7387       // Check that we can declare a member specialization here.
7388       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7389           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7390         return nullptr;
7391       assert((Invalid ||
7392               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7393              "should have a 'template<>' for this decl");
7394     }
7395 
7396     if (IsVariableTemplateSpecialization) {
7397       SourceLocation TemplateKWLoc =
7398           TemplateParamLists.size() > 0
7399               ? TemplateParamLists[0]->getTemplateLoc()
7400               : SourceLocation();
7401       DeclResult Res = ActOnVarTemplateSpecialization(
7402           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7403           IsPartialSpecialization);
7404       if (Res.isInvalid())
7405         return nullptr;
7406       NewVD = cast<VarDecl>(Res.get());
7407       AddToScope = false;
7408     } else if (D.isDecompositionDeclarator()) {
7409       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7410                                         D.getIdentifierLoc(), R, TInfo, SC,
7411                                         Bindings);
7412     } else
7413       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7414                               D.getIdentifierLoc(), II, R, TInfo, SC);
7415 
7416     // If this is supposed to be a variable template, create it as such.
7417     if (IsVariableTemplate) {
7418       NewTemplate =
7419           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7420                                   TemplateParams, NewVD);
7421       NewVD->setDescribedVarTemplate(NewTemplate);
7422     }
7423 
7424     // If this decl has an auto type in need of deduction, make a note of the
7425     // Decl so we can diagnose uses of it in its own initializer.
7426     if (R->getContainedDeducedType())
7427       ParsingInitForAutoVars.insert(NewVD);
7428 
7429     if (D.isInvalidType() || Invalid) {
7430       NewVD->setInvalidDecl();
7431       if (NewTemplate)
7432         NewTemplate->setInvalidDecl();
7433     }
7434 
7435     SetNestedNameSpecifier(*this, NewVD, D);
7436 
7437     // If we have any template parameter lists that don't directly belong to
7438     // the variable (matching the scope specifier), store them.
7439     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7440     if (TemplateParamLists.size() > VDTemplateParamLists)
7441       NewVD->setTemplateParameterListsInfo(
7442           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7443   }
7444 
7445   if (D.getDeclSpec().isInlineSpecified()) {
7446     if (!getLangOpts().CPlusPlus) {
7447       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7448           << 0;
7449     } else if (CurContext->isFunctionOrMethod()) {
7450       // 'inline' is not allowed on block scope variable declaration.
7451       Diag(D.getDeclSpec().getInlineSpecLoc(),
7452            diag::err_inline_declaration_block_scope) << Name
7453         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7454     } else {
7455       Diag(D.getDeclSpec().getInlineSpecLoc(),
7456            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7457                                      : diag::ext_inline_variable);
7458       NewVD->setInlineSpecified();
7459     }
7460   }
7461 
7462   // Set the lexical context. If the declarator has a C++ scope specifier, the
7463   // lexical context will be different from the semantic context.
7464   NewVD->setLexicalDeclContext(CurContext);
7465   if (NewTemplate)
7466     NewTemplate->setLexicalDeclContext(CurContext);
7467 
7468   if (IsLocalExternDecl) {
7469     if (D.isDecompositionDeclarator())
7470       for (auto *B : Bindings)
7471         B->setLocalExternDecl();
7472     else
7473       NewVD->setLocalExternDecl();
7474   }
7475 
7476   bool EmitTLSUnsupportedError = false;
7477   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7478     // C++11 [dcl.stc]p4:
7479     //   When thread_local is applied to a variable of block scope the
7480     //   storage-class-specifier static is implied if it does not appear
7481     //   explicitly.
7482     // Core issue: 'static' is not implied if the variable is declared
7483     //   'extern'.
7484     if (NewVD->hasLocalStorage() &&
7485         (SCSpec != DeclSpec::SCS_unspecified ||
7486          TSCS != DeclSpec::TSCS_thread_local ||
7487          !DC->isFunctionOrMethod()))
7488       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7489            diag::err_thread_non_global)
7490         << DeclSpec::getSpecifierName(TSCS);
7491     else if (!Context.getTargetInfo().isTLSSupported()) {
7492       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7493           getLangOpts().SYCLIsDevice) {
7494         // Postpone error emission until we've collected attributes required to
7495         // figure out whether it's a host or device variable and whether the
7496         // error should be ignored.
7497         EmitTLSUnsupportedError = true;
7498         // We still need to mark the variable as TLS so it shows up in AST with
7499         // proper storage class for other tools to use even if we're not going
7500         // to emit any code for it.
7501         NewVD->setTSCSpec(TSCS);
7502       } else
7503         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7504              diag::err_thread_unsupported);
7505     } else
7506       NewVD->setTSCSpec(TSCS);
7507   }
7508 
7509   switch (D.getDeclSpec().getConstexprSpecifier()) {
7510   case ConstexprSpecKind::Unspecified:
7511     break;
7512 
7513   case ConstexprSpecKind::Consteval:
7514     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7515          diag::err_constexpr_wrong_decl_kind)
7516         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7517     LLVM_FALLTHROUGH;
7518 
7519   case ConstexprSpecKind::Constexpr:
7520     NewVD->setConstexpr(true);
7521     // C++1z [dcl.spec.constexpr]p1:
7522     //   A static data member declared with the constexpr specifier is
7523     //   implicitly an inline variable.
7524     if (NewVD->isStaticDataMember() &&
7525         (getLangOpts().CPlusPlus17 ||
7526          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7527       NewVD->setImplicitlyInline();
7528     break;
7529 
7530   case ConstexprSpecKind::Constinit:
7531     if (!NewVD->hasGlobalStorage())
7532       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7533            diag::err_constinit_local_variable);
7534     else
7535       NewVD->addAttr(ConstInitAttr::Create(
7536           Context, D.getDeclSpec().getConstexprSpecLoc(),
7537           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7538     break;
7539   }
7540 
7541   // C99 6.7.4p3
7542   //   An inline definition of a function with external linkage shall
7543   //   not contain a definition of a modifiable object with static or
7544   //   thread storage duration...
7545   // We only apply this when the function is required to be defined
7546   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7547   // that a local variable with thread storage duration still has to
7548   // be marked 'static'.  Also note that it's possible to get these
7549   // semantics in C++ using __attribute__((gnu_inline)).
7550   if (SC == SC_Static && S->getFnParent() != nullptr &&
7551       !NewVD->getType().isConstQualified()) {
7552     FunctionDecl *CurFD = getCurFunctionDecl();
7553     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7554       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7555            diag::warn_static_local_in_extern_inline);
7556       MaybeSuggestAddingStaticToDecl(CurFD);
7557     }
7558   }
7559 
7560   if (D.getDeclSpec().isModulePrivateSpecified()) {
7561     if (IsVariableTemplateSpecialization)
7562       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7563           << (IsPartialSpecialization ? 1 : 0)
7564           << FixItHint::CreateRemoval(
7565                  D.getDeclSpec().getModulePrivateSpecLoc());
7566     else if (IsMemberSpecialization)
7567       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7568         << 2
7569         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7570     else if (NewVD->hasLocalStorage())
7571       Diag(NewVD->getLocation(), diag::err_module_private_local)
7572           << 0 << NewVD
7573           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7574           << FixItHint::CreateRemoval(
7575                  D.getDeclSpec().getModulePrivateSpecLoc());
7576     else {
7577       NewVD->setModulePrivate();
7578       if (NewTemplate)
7579         NewTemplate->setModulePrivate();
7580       for (auto *B : Bindings)
7581         B->setModulePrivate();
7582     }
7583   }
7584 
7585   if (getLangOpts().OpenCL) {
7586     deduceOpenCLAddressSpace(NewVD);
7587 
7588     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7589     if (TSC != TSCS_unspecified) {
7590       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7591            diag::err_opencl_unknown_type_specifier)
7592           << getLangOpts().getOpenCLVersionString()
7593           << DeclSpec::getSpecifierName(TSC) << 1;
7594       NewVD->setInvalidDecl();
7595     }
7596   }
7597 
7598   // Handle attributes prior to checking for duplicates in MergeVarDecl
7599   ProcessDeclAttributes(S, NewVD, D);
7600 
7601   // FIXME: This is probably the wrong location to be doing this and we should
7602   // probably be doing this for more attributes (especially for function
7603   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7604   // the code to copy attributes would be generated by TableGen.
7605   if (R->isFunctionPointerType())
7606     if (const auto *TT = R->getAs<TypedefType>())
7607       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7608 
7609   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7610       getLangOpts().SYCLIsDevice) {
7611     if (EmitTLSUnsupportedError &&
7612         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7613          (getLangOpts().OpenMPIsDevice &&
7614           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7615       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7616            diag::err_thread_unsupported);
7617 
7618     if (EmitTLSUnsupportedError &&
7619         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7620       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7621     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7622     // storage [duration]."
7623     if (SC == SC_None && S->getFnParent() != nullptr &&
7624         (NewVD->hasAttr<CUDASharedAttr>() ||
7625          NewVD->hasAttr<CUDAConstantAttr>())) {
7626       NewVD->setStorageClass(SC_Static);
7627     }
7628   }
7629 
7630   // Ensure that dllimport globals without explicit storage class are treated as
7631   // extern. The storage class is set above using parsed attributes. Now we can
7632   // check the VarDecl itself.
7633   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7634          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7635          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7636 
7637   // In auto-retain/release, infer strong retension for variables of
7638   // retainable type.
7639   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7640     NewVD->setInvalidDecl();
7641 
7642   // Handle GNU asm-label extension (encoded as an attribute).
7643   if (Expr *E = (Expr*)D.getAsmLabel()) {
7644     // The parser guarantees this is a string.
7645     StringLiteral *SE = cast<StringLiteral>(E);
7646     StringRef Label = SE->getString();
7647     if (S->getFnParent() != nullptr) {
7648       switch (SC) {
7649       case SC_None:
7650       case SC_Auto:
7651         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7652         break;
7653       case SC_Register:
7654         // Local Named register
7655         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7656             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7657           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7658         break;
7659       case SC_Static:
7660       case SC_Extern:
7661       case SC_PrivateExtern:
7662         break;
7663       }
7664     } else if (SC == SC_Register) {
7665       // Global Named register
7666       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7667         const auto &TI = Context.getTargetInfo();
7668         bool HasSizeMismatch;
7669 
7670         if (!TI.isValidGCCRegisterName(Label))
7671           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7672         else if (!TI.validateGlobalRegisterVariable(Label,
7673                                                     Context.getTypeSize(R),
7674                                                     HasSizeMismatch))
7675           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7676         else if (HasSizeMismatch)
7677           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7678       }
7679 
7680       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7681         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7682         NewVD->setInvalidDecl(true);
7683       }
7684     }
7685 
7686     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7687                                         /*IsLiteralLabel=*/true,
7688                                         SE->getStrTokenLoc(0)));
7689   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7690     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7691       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7692     if (I != ExtnameUndeclaredIdentifiers.end()) {
7693       if (isDeclExternC(NewVD)) {
7694         NewVD->addAttr(I->second);
7695         ExtnameUndeclaredIdentifiers.erase(I);
7696       } else
7697         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7698             << /*Variable*/1 << NewVD;
7699     }
7700   }
7701 
7702   // Find the shadowed declaration before filtering for scope.
7703   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7704                                 ? getShadowedDeclaration(NewVD, Previous)
7705                                 : nullptr;
7706 
7707   // Don't consider existing declarations that are in a different
7708   // scope and are out-of-semantic-context declarations (if the new
7709   // declaration has linkage).
7710   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7711                        D.getCXXScopeSpec().isNotEmpty() ||
7712                        IsMemberSpecialization ||
7713                        IsVariableTemplateSpecialization);
7714 
7715   // Check whether the previous declaration is in the same block scope. This
7716   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7717   if (getLangOpts().CPlusPlus &&
7718       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7719     NewVD->setPreviousDeclInSameBlockScope(
7720         Previous.isSingleResult() && !Previous.isShadowed() &&
7721         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7722 
7723   if (!getLangOpts().CPlusPlus) {
7724     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7725   } else {
7726     // If this is an explicit specialization of a static data member, check it.
7727     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7728         CheckMemberSpecialization(NewVD, Previous))
7729       NewVD->setInvalidDecl();
7730 
7731     // Merge the decl with the existing one if appropriate.
7732     if (!Previous.empty()) {
7733       if (Previous.isSingleResult() &&
7734           isa<FieldDecl>(Previous.getFoundDecl()) &&
7735           D.getCXXScopeSpec().isSet()) {
7736         // The user tried to define a non-static data member
7737         // out-of-line (C++ [dcl.meaning]p1).
7738         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7739           << D.getCXXScopeSpec().getRange();
7740         Previous.clear();
7741         NewVD->setInvalidDecl();
7742       }
7743     } else if (D.getCXXScopeSpec().isSet()) {
7744       // No previous declaration in the qualifying scope.
7745       Diag(D.getIdentifierLoc(), diag::err_no_member)
7746         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7747         << D.getCXXScopeSpec().getRange();
7748       NewVD->setInvalidDecl();
7749     }
7750 
7751     if (!IsVariableTemplateSpecialization)
7752       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7753 
7754     if (NewTemplate) {
7755       VarTemplateDecl *PrevVarTemplate =
7756           NewVD->getPreviousDecl()
7757               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7758               : nullptr;
7759 
7760       // Check the template parameter list of this declaration, possibly
7761       // merging in the template parameter list from the previous variable
7762       // template declaration.
7763       if (CheckTemplateParameterList(
7764               TemplateParams,
7765               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7766                               : nullptr,
7767               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7768                DC->isDependentContext())
7769                   ? TPC_ClassTemplateMember
7770                   : TPC_VarTemplate))
7771         NewVD->setInvalidDecl();
7772 
7773       // If we are providing an explicit specialization of a static variable
7774       // template, make a note of that.
7775       if (PrevVarTemplate &&
7776           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7777         PrevVarTemplate->setMemberSpecialization();
7778     }
7779   }
7780 
7781   // Diagnose shadowed variables iff this isn't a redeclaration.
7782   if (ShadowedDecl && !D.isRedeclaration())
7783     CheckShadow(NewVD, ShadowedDecl, Previous);
7784 
7785   ProcessPragmaWeak(S, NewVD);
7786 
7787   // If this is the first declaration of an extern C variable, update
7788   // the map of such variables.
7789   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7790       isIncompleteDeclExternC(*this, NewVD))
7791     RegisterLocallyScopedExternCDecl(NewVD, S);
7792 
7793   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7794     MangleNumberingContext *MCtx;
7795     Decl *ManglingContextDecl;
7796     std::tie(MCtx, ManglingContextDecl) =
7797         getCurrentMangleNumberContext(NewVD->getDeclContext());
7798     if (MCtx) {
7799       Context.setManglingNumber(
7800           NewVD, MCtx->getManglingNumber(
7801                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7802       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7803     }
7804   }
7805 
7806   // Special handling of variable named 'main'.
7807   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7808       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7809       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7810 
7811     // C++ [basic.start.main]p3
7812     // A program that declares a variable main at global scope is ill-formed.
7813     if (getLangOpts().CPlusPlus)
7814       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7815 
7816     // In C, and external-linkage variable named main results in undefined
7817     // behavior.
7818     else if (NewVD->hasExternalFormalLinkage())
7819       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7820   }
7821 
7822   if (D.isRedeclaration() && !Previous.empty()) {
7823     NamedDecl *Prev = Previous.getRepresentativeDecl();
7824     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7825                                    D.isFunctionDefinition());
7826   }
7827 
7828   if (NewTemplate) {
7829     if (NewVD->isInvalidDecl())
7830       NewTemplate->setInvalidDecl();
7831     ActOnDocumentableDecl(NewTemplate);
7832     return NewTemplate;
7833   }
7834 
7835   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7836     CompleteMemberSpecialization(NewVD, Previous);
7837 
7838   return NewVD;
7839 }
7840 
7841 /// Enum describing the %select options in diag::warn_decl_shadow.
7842 enum ShadowedDeclKind {
7843   SDK_Local,
7844   SDK_Global,
7845   SDK_StaticMember,
7846   SDK_Field,
7847   SDK_Typedef,
7848   SDK_Using,
7849   SDK_StructuredBinding
7850 };
7851 
7852 /// Determine what kind of declaration we're shadowing.
7853 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7854                                                 const DeclContext *OldDC) {
7855   if (isa<TypeAliasDecl>(ShadowedDecl))
7856     return SDK_Using;
7857   else if (isa<TypedefDecl>(ShadowedDecl))
7858     return SDK_Typedef;
7859   else if (isa<BindingDecl>(ShadowedDecl))
7860     return SDK_StructuredBinding;
7861   else if (isa<RecordDecl>(OldDC))
7862     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7863 
7864   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7865 }
7866 
7867 /// Return the location of the capture if the given lambda captures the given
7868 /// variable \p VD, or an invalid source location otherwise.
7869 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7870                                          const VarDecl *VD) {
7871   for (const Capture &Capture : LSI->Captures) {
7872     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7873       return Capture.getLocation();
7874   }
7875   return SourceLocation();
7876 }
7877 
7878 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7879                                      const LookupResult &R) {
7880   // Only diagnose if we're shadowing an unambiguous field or variable.
7881   if (R.getResultKind() != LookupResult::Found)
7882     return false;
7883 
7884   // Return false if warning is ignored.
7885   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7886 }
7887 
7888 /// Return the declaration shadowed by the given variable \p D, or null
7889 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7890 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7891                                         const LookupResult &R) {
7892   if (!shouldWarnIfShadowedDecl(Diags, R))
7893     return nullptr;
7894 
7895   // Don't diagnose declarations at file scope.
7896   if (D->hasGlobalStorage())
7897     return nullptr;
7898 
7899   NamedDecl *ShadowedDecl = R.getFoundDecl();
7900   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7901                                                             : nullptr;
7902 }
7903 
7904 /// Return the declaration shadowed by the given typedef \p D, or null
7905 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7906 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7907                                         const LookupResult &R) {
7908   // Don't warn if typedef declaration is part of a class
7909   if (D->getDeclContext()->isRecord())
7910     return nullptr;
7911 
7912   if (!shouldWarnIfShadowedDecl(Diags, R))
7913     return nullptr;
7914 
7915   NamedDecl *ShadowedDecl = R.getFoundDecl();
7916   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7917 }
7918 
7919 /// Return the declaration shadowed by the given variable \p D, or null
7920 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7921 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7922                                         const LookupResult &R) {
7923   if (!shouldWarnIfShadowedDecl(Diags, R))
7924     return nullptr;
7925 
7926   NamedDecl *ShadowedDecl = R.getFoundDecl();
7927   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7928                                                             : nullptr;
7929 }
7930 
7931 /// Diagnose variable or built-in function shadowing.  Implements
7932 /// -Wshadow.
7933 ///
7934 /// This method is called whenever a VarDecl is added to a "useful"
7935 /// scope.
7936 ///
7937 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7938 /// \param R the lookup of the name
7939 ///
7940 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7941                        const LookupResult &R) {
7942   DeclContext *NewDC = D->getDeclContext();
7943 
7944   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7945     // Fields are not shadowed by variables in C++ static methods.
7946     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7947       if (MD->isStatic())
7948         return;
7949 
7950     // Fields shadowed by constructor parameters are a special case. Usually
7951     // the constructor initializes the field with the parameter.
7952     if (isa<CXXConstructorDecl>(NewDC))
7953       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7954         // Remember that this was shadowed so we can either warn about its
7955         // modification or its existence depending on warning settings.
7956         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7957         return;
7958       }
7959   }
7960 
7961   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7962     if (shadowedVar->isExternC()) {
7963       // For shadowing external vars, make sure that we point to the global
7964       // declaration, not a locally scoped extern declaration.
7965       for (auto I : shadowedVar->redecls())
7966         if (I->isFileVarDecl()) {
7967           ShadowedDecl = I;
7968           break;
7969         }
7970     }
7971 
7972   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7973 
7974   unsigned WarningDiag = diag::warn_decl_shadow;
7975   SourceLocation CaptureLoc;
7976   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7977       isa<CXXMethodDecl>(NewDC)) {
7978     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7979       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7980         if (RD->getLambdaCaptureDefault() == LCD_None) {
7981           // Try to avoid warnings for lambdas with an explicit capture list.
7982           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7983           // Warn only when the lambda captures the shadowed decl explicitly.
7984           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7985           if (CaptureLoc.isInvalid())
7986             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7987         } else {
7988           // Remember that this was shadowed so we can avoid the warning if the
7989           // shadowed decl isn't captured and the warning settings allow it.
7990           cast<LambdaScopeInfo>(getCurFunction())
7991               ->ShadowingDecls.push_back(
7992                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7993           return;
7994         }
7995       }
7996 
7997       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7998         // A variable can't shadow a local variable in an enclosing scope, if
7999         // they are separated by a non-capturing declaration context.
8000         for (DeclContext *ParentDC = NewDC;
8001              ParentDC && !ParentDC->Equals(OldDC);
8002              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8003           // Only block literals, captured statements, and lambda expressions
8004           // can capture; other scopes don't.
8005           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8006               !isLambdaCallOperator(ParentDC)) {
8007             return;
8008           }
8009         }
8010       }
8011     }
8012   }
8013 
8014   // Only warn about certain kinds of shadowing for class members.
8015   if (NewDC && NewDC->isRecord()) {
8016     // In particular, don't warn about shadowing non-class members.
8017     if (!OldDC->isRecord())
8018       return;
8019 
8020     // TODO: should we warn about static data members shadowing
8021     // static data members from base classes?
8022 
8023     // TODO: don't diagnose for inaccessible shadowed members.
8024     // This is hard to do perfectly because we might friend the
8025     // shadowing context, but that's just a false negative.
8026   }
8027 
8028 
8029   DeclarationName Name = R.getLookupName();
8030 
8031   // Emit warning and note.
8032   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8033   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8034   if (!CaptureLoc.isInvalid())
8035     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8036         << Name << /*explicitly*/ 1;
8037   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8038 }
8039 
8040 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8041 /// when these variables are captured by the lambda.
8042 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8043   for (const auto &Shadow : LSI->ShadowingDecls) {
8044     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8045     // Try to avoid the warning when the shadowed decl isn't captured.
8046     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8047     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8048     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8049                                        ? diag::warn_decl_shadow_uncaptured_local
8050                                        : diag::warn_decl_shadow)
8051         << Shadow.VD->getDeclName()
8052         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8053     if (!CaptureLoc.isInvalid())
8054       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8055           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8056     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8057   }
8058 }
8059 
8060 /// Check -Wshadow without the advantage of a previous lookup.
8061 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8062   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8063     return;
8064 
8065   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8066                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8067   LookupName(R, S);
8068   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8069     CheckShadow(D, ShadowedDecl, R);
8070 }
8071 
8072 /// Check if 'E', which is an expression that is about to be modified, refers
8073 /// to a constructor parameter that shadows a field.
8074 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8075   // Quickly ignore expressions that can't be shadowing ctor parameters.
8076   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8077     return;
8078   E = E->IgnoreParenImpCasts();
8079   auto *DRE = dyn_cast<DeclRefExpr>(E);
8080   if (!DRE)
8081     return;
8082   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8083   auto I = ShadowingDecls.find(D);
8084   if (I == ShadowingDecls.end())
8085     return;
8086   const NamedDecl *ShadowedDecl = I->second;
8087   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8088   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8089   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8090   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8091 
8092   // Avoid issuing multiple warnings about the same decl.
8093   ShadowingDecls.erase(I);
8094 }
8095 
8096 /// Check for conflict between this global or extern "C" declaration and
8097 /// previous global or extern "C" declarations. This is only used in C++.
8098 template<typename T>
8099 static bool checkGlobalOrExternCConflict(
8100     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8101   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8102   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8103 
8104   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8105     // The common case: this global doesn't conflict with any extern "C"
8106     // declaration.
8107     return false;
8108   }
8109 
8110   if (Prev) {
8111     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8112       // Both the old and new declarations have C language linkage. This is a
8113       // redeclaration.
8114       Previous.clear();
8115       Previous.addDecl(Prev);
8116       return true;
8117     }
8118 
8119     // This is a global, non-extern "C" declaration, and there is a previous
8120     // non-global extern "C" declaration. Diagnose if this is a variable
8121     // declaration.
8122     if (!isa<VarDecl>(ND))
8123       return false;
8124   } else {
8125     // The declaration is extern "C". Check for any declaration in the
8126     // translation unit which might conflict.
8127     if (IsGlobal) {
8128       // We have already performed the lookup into the translation unit.
8129       IsGlobal = false;
8130       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8131            I != E; ++I) {
8132         if (isa<VarDecl>(*I)) {
8133           Prev = *I;
8134           break;
8135         }
8136       }
8137     } else {
8138       DeclContext::lookup_result R =
8139           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8140       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8141            I != E; ++I) {
8142         if (isa<VarDecl>(*I)) {
8143           Prev = *I;
8144           break;
8145         }
8146         // FIXME: If we have any other entity with this name in global scope,
8147         // the declaration is ill-formed, but that is a defect: it breaks the
8148         // 'stat' hack, for instance. Only variables can have mangled name
8149         // clashes with extern "C" declarations, so only they deserve a
8150         // diagnostic.
8151       }
8152     }
8153 
8154     if (!Prev)
8155       return false;
8156   }
8157 
8158   // Use the first declaration's location to ensure we point at something which
8159   // is lexically inside an extern "C" linkage-spec.
8160   assert(Prev && "should have found a previous declaration to diagnose");
8161   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8162     Prev = FD->getFirstDecl();
8163   else
8164     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8165 
8166   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8167     << IsGlobal << ND;
8168   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8169     << IsGlobal;
8170   return false;
8171 }
8172 
8173 /// Apply special rules for handling extern "C" declarations. Returns \c true
8174 /// if we have found that this is a redeclaration of some prior entity.
8175 ///
8176 /// Per C++ [dcl.link]p6:
8177 ///   Two declarations [for a function or variable] with C language linkage
8178 ///   with the same name that appear in different scopes refer to the same
8179 ///   [entity]. An entity with C language linkage shall not be declared with
8180 ///   the same name as an entity in global scope.
8181 template<typename T>
8182 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8183                                                   LookupResult &Previous) {
8184   if (!S.getLangOpts().CPlusPlus) {
8185     // In C, when declaring a global variable, look for a corresponding 'extern'
8186     // variable declared in function scope. We don't need this in C++, because
8187     // we find local extern decls in the surrounding file-scope DeclContext.
8188     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8189       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8190         Previous.clear();
8191         Previous.addDecl(Prev);
8192         return true;
8193       }
8194     }
8195     return false;
8196   }
8197 
8198   // A declaration in the translation unit can conflict with an extern "C"
8199   // declaration.
8200   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8201     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8202 
8203   // An extern "C" declaration can conflict with a declaration in the
8204   // translation unit or can be a redeclaration of an extern "C" declaration
8205   // in another scope.
8206   if (isIncompleteDeclExternC(S,ND))
8207     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8208 
8209   // Neither global nor extern "C": nothing to do.
8210   return false;
8211 }
8212 
8213 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8214   // If the decl is already known invalid, don't check it.
8215   if (NewVD->isInvalidDecl())
8216     return;
8217 
8218   QualType T = NewVD->getType();
8219 
8220   // Defer checking an 'auto' type until its initializer is attached.
8221   if (T->isUndeducedType())
8222     return;
8223 
8224   if (NewVD->hasAttrs())
8225     CheckAlignasUnderalignment(NewVD);
8226 
8227   if (T->isObjCObjectType()) {
8228     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8229       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8230     T = Context.getObjCObjectPointerType(T);
8231     NewVD->setType(T);
8232   }
8233 
8234   // Emit an error if an address space was applied to decl with local storage.
8235   // This includes arrays of objects with address space qualifiers, but not
8236   // automatic variables that point to other address spaces.
8237   // ISO/IEC TR 18037 S5.1.2
8238   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8239       T.getAddressSpace() != LangAS::Default) {
8240     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8241     NewVD->setInvalidDecl();
8242     return;
8243   }
8244 
8245   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8246   // scope.
8247   if (getLangOpts().OpenCLVersion == 120 &&
8248       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8249                                             getLangOpts()) &&
8250       NewVD->isStaticLocal()) {
8251     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8252     NewVD->setInvalidDecl();
8253     return;
8254   }
8255 
8256   if (getLangOpts().OpenCL) {
8257     if (!diagnoseOpenCLTypes(*this, NewVD))
8258       return;
8259 
8260     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8261     if (NewVD->hasAttr<BlocksAttr>()) {
8262       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8263       return;
8264     }
8265 
8266     if (T->isBlockPointerType()) {
8267       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8268       // can't use 'extern' storage class.
8269       if (!T.isConstQualified()) {
8270         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8271             << 0 /*const*/;
8272         NewVD->setInvalidDecl();
8273         return;
8274       }
8275       if (NewVD->hasExternalStorage()) {
8276         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8277         NewVD->setInvalidDecl();
8278         return;
8279       }
8280     }
8281 
8282     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8283     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8284         NewVD->hasExternalStorage()) {
8285       if (!T->isSamplerT() && !T->isDependentType() &&
8286           !(T.getAddressSpace() == LangAS::opencl_constant ||
8287             (T.getAddressSpace() == LangAS::opencl_global &&
8288              getOpenCLOptions().areProgramScopeVariablesSupported(
8289                  getLangOpts())))) {
8290         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8291         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8292           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8293               << Scope << "global or constant";
8294         else
8295           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8296               << Scope << "constant";
8297         NewVD->setInvalidDecl();
8298         return;
8299       }
8300     } else {
8301       if (T.getAddressSpace() == LangAS::opencl_global) {
8302         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8303             << 1 /*is any function*/ << "global";
8304         NewVD->setInvalidDecl();
8305         return;
8306       }
8307       if (T.getAddressSpace() == LangAS::opencl_constant ||
8308           T.getAddressSpace() == LangAS::opencl_local) {
8309         FunctionDecl *FD = getCurFunctionDecl();
8310         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8311         // in functions.
8312         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8313           if (T.getAddressSpace() == LangAS::opencl_constant)
8314             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8315                 << 0 /*non-kernel only*/ << "constant";
8316           else
8317             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8318                 << 0 /*non-kernel only*/ << "local";
8319           NewVD->setInvalidDecl();
8320           return;
8321         }
8322         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8323         // in the outermost scope of a kernel function.
8324         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8325           if (!getCurScope()->isFunctionScope()) {
8326             if (T.getAddressSpace() == LangAS::opencl_constant)
8327               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8328                   << "constant";
8329             else
8330               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8331                   << "local";
8332             NewVD->setInvalidDecl();
8333             return;
8334           }
8335         }
8336       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8337                  // If we are parsing a template we didn't deduce an addr
8338                  // space yet.
8339                  T.getAddressSpace() != LangAS::Default) {
8340         // Do not allow other address spaces on automatic variable.
8341         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8342         NewVD->setInvalidDecl();
8343         return;
8344       }
8345     }
8346   }
8347 
8348   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8349       && !NewVD->hasAttr<BlocksAttr>()) {
8350     if (getLangOpts().getGC() != LangOptions::NonGC)
8351       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8352     else {
8353       assert(!getLangOpts().ObjCAutoRefCount);
8354       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8355     }
8356   }
8357 
8358   bool isVM = T->isVariablyModifiedType();
8359   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8360       NewVD->hasAttr<BlocksAttr>())
8361     setFunctionHasBranchProtectedScope();
8362 
8363   if ((isVM && NewVD->hasLinkage()) ||
8364       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8365     bool SizeIsNegative;
8366     llvm::APSInt Oversized;
8367     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8368         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8369     QualType FixedT;
8370     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8371       FixedT = FixedTInfo->getType();
8372     else if (FixedTInfo) {
8373       // Type and type-as-written are canonically different. We need to fix up
8374       // both types separately.
8375       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8376                                                    Oversized);
8377     }
8378     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8379       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8380       // FIXME: This won't give the correct result for
8381       // int a[10][n];
8382       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8383 
8384       if (NewVD->isFileVarDecl())
8385         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8386         << SizeRange;
8387       else if (NewVD->isStaticLocal())
8388         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8389         << SizeRange;
8390       else
8391         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8392         << SizeRange;
8393       NewVD->setInvalidDecl();
8394       return;
8395     }
8396 
8397     if (!FixedTInfo) {
8398       if (NewVD->isFileVarDecl())
8399         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8400       else
8401         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8402       NewVD->setInvalidDecl();
8403       return;
8404     }
8405 
8406     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8407     NewVD->setType(FixedT);
8408     NewVD->setTypeSourceInfo(FixedTInfo);
8409   }
8410 
8411   if (T->isVoidType()) {
8412     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8413     //                    of objects and functions.
8414     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8415       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8416         << T;
8417       NewVD->setInvalidDecl();
8418       return;
8419     }
8420   }
8421 
8422   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8423     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8424     NewVD->setInvalidDecl();
8425     return;
8426   }
8427 
8428   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8429     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8430     NewVD->setInvalidDecl();
8431     return;
8432   }
8433 
8434   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8435     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8436     NewVD->setInvalidDecl();
8437     return;
8438   }
8439 
8440   if (NewVD->isConstexpr() && !T->isDependentType() &&
8441       RequireLiteralType(NewVD->getLocation(), T,
8442                          diag::err_constexpr_var_non_literal)) {
8443     NewVD->setInvalidDecl();
8444     return;
8445   }
8446 
8447   // PPC MMA non-pointer types are not allowed as non-local variable types.
8448   if (Context.getTargetInfo().getTriple().isPPC64() &&
8449       !NewVD->isLocalVarDecl() &&
8450       CheckPPCMMAType(T, NewVD->getLocation())) {
8451     NewVD->setInvalidDecl();
8452     return;
8453   }
8454 }
8455 
8456 /// Perform semantic checking on a newly-created variable
8457 /// declaration.
8458 ///
8459 /// This routine performs all of the type-checking required for a
8460 /// variable declaration once it has been built. It is used both to
8461 /// check variables after they have been parsed and their declarators
8462 /// have been translated into a declaration, and to check variables
8463 /// that have been instantiated from a template.
8464 ///
8465 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8466 ///
8467 /// Returns true if the variable declaration is a redeclaration.
8468 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8469   CheckVariableDeclarationType(NewVD);
8470 
8471   // If the decl is already known invalid, don't check it.
8472   if (NewVD->isInvalidDecl())
8473     return false;
8474 
8475   // If we did not find anything by this name, look for a non-visible
8476   // extern "C" declaration with the same name.
8477   if (Previous.empty() &&
8478       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8479     Previous.setShadowed();
8480 
8481   if (!Previous.empty()) {
8482     MergeVarDecl(NewVD, Previous);
8483     return true;
8484   }
8485   return false;
8486 }
8487 
8488 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8489 /// and if so, check that it's a valid override and remember it.
8490 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8491   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8492 
8493   // Look for methods in base classes that this method might override.
8494   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8495                      /*DetectVirtual=*/false);
8496   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8497     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8498     DeclarationName Name = MD->getDeclName();
8499 
8500     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8501       // We really want to find the base class destructor here.
8502       QualType T = Context.getTypeDeclType(BaseRecord);
8503       CanQualType CT = Context.getCanonicalType(T);
8504       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8505     }
8506 
8507     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8508       CXXMethodDecl *BaseMD =
8509           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8510       if (!BaseMD || !BaseMD->isVirtual() ||
8511           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8512                      /*ConsiderCudaAttrs=*/true,
8513                      // C++2a [class.virtual]p2 does not consider requires
8514                      // clauses when overriding.
8515                      /*ConsiderRequiresClauses=*/false))
8516         continue;
8517 
8518       if (Overridden.insert(BaseMD).second) {
8519         MD->addOverriddenMethod(BaseMD);
8520         CheckOverridingFunctionReturnType(MD, BaseMD);
8521         CheckOverridingFunctionAttributes(MD, BaseMD);
8522         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8523         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8524       }
8525 
8526       // A method can only override one function from each base class. We
8527       // don't track indirectly overridden methods from bases of bases.
8528       return true;
8529     }
8530 
8531     return false;
8532   };
8533 
8534   DC->lookupInBases(VisitBase, Paths);
8535   return !Overridden.empty();
8536 }
8537 
8538 namespace {
8539   // Struct for holding all of the extra arguments needed by
8540   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8541   struct ActOnFDArgs {
8542     Scope *S;
8543     Declarator &D;
8544     MultiTemplateParamsArg TemplateParamLists;
8545     bool AddToScope;
8546   };
8547 } // end anonymous namespace
8548 
8549 namespace {
8550 
8551 // Callback to only accept typo corrections that have a non-zero edit distance.
8552 // Also only accept corrections that have the same parent decl.
8553 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8554  public:
8555   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8556                             CXXRecordDecl *Parent)
8557       : Context(Context), OriginalFD(TypoFD),
8558         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8559 
8560   bool ValidateCandidate(const TypoCorrection &candidate) override {
8561     if (candidate.getEditDistance() == 0)
8562       return false;
8563 
8564     SmallVector<unsigned, 1> MismatchedParams;
8565     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8566                                           CDeclEnd = candidate.end();
8567          CDecl != CDeclEnd; ++CDecl) {
8568       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8569 
8570       if (FD && !FD->hasBody() &&
8571           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8572         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8573           CXXRecordDecl *Parent = MD->getParent();
8574           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8575             return true;
8576         } else if (!ExpectedParent) {
8577           return true;
8578         }
8579       }
8580     }
8581 
8582     return false;
8583   }
8584 
8585   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8586     return std::make_unique<DifferentNameValidatorCCC>(*this);
8587   }
8588 
8589  private:
8590   ASTContext &Context;
8591   FunctionDecl *OriginalFD;
8592   CXXRecordDecl *ExpectedParent;
8593 };
8594 
8595 } // end anonymous namespace
8596 
8597 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8598   TypoCorrectedFunctionDefinitions.insert(F);
8599 }
8600 
8601 /// Generate diagnostics for an invalid function redeclaration.
8602 ///
8603 /// This routine handles generating the diagnostic messages for an invalid
8604 /// function redeclaration, including finding possible similar declarations
8605 /// or performing typo correction if there are no previous declarations with
8606 /// the same name.
8607 ///
8608 /// Returns a NamedDecl iff typo correction was performed and substituting in
8609 /// the new declaration name does not cause new errors.
8610 static NamedDecl *DiagnoseInvalidRedeclaration(
8611     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8612     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8613   DeclarationName Name = NewFD->getDeclName();
8614   DeclContext *NewDC = NewFD->getDeclContext();
8615   SmallVector<unsigned, 1> MismatchedParams;
8616   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8617   TypoCorrection Correction;
8618   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8619   unsigned DiagMsg =
8620     IsLocalFriend ? diag::err_no_matching_local_friend :
8621     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8622     diag::err_member_decl_does_not_match;
8623   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8624                     IsLocalFriend ? Sema::LookupLocalFriendName
8625                                   : Sema::LookupOrdinaryName,
8626                     Sema::ForVisibleRedeclaration);
8627 
8628   NewFD->setInvalidDecl();
8629   if (IsLocalFriend)
8630     SemaRef.LookupName(Prev, S);
8631   else
8632     SemaRef.LookupQualifiedName(Prev, NewDC);
8633   assert(!Prev.isAmbiguous() &&
8634          "Cannot have an ambiguity in previous-declaration lookup");
8635   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8636   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8637                                 MD ? MD->getParent() : nullptr);
8638   if (!Prev.empty()) {
8639     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8640          Func != FuncEnd; ++Func) {
8641       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8642       if (FD &&
8643           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8644         // Add 1 to the index so that 0 can mean the mismatch didn't
8645         // involve a parameter
8646         unsigned ParamNum =
8647             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8648         NearMatches.push_back(std::make_pair(FD, ParamNum));
8649       }
8650     }
8651   // If the qualified name lookup yielded nothing, try typo correction
8652   } else if ((Correction = SemaRef.CorrectTypo(
8653                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8654                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8655                   IsLocalFriend ? nullptr : NewDC))) {
8656     // Set up everything for the call to ActOnFunctionDeclarator
8657     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8658                               ExtraArgs.D.getIdentifierLoc());
8659     Previous.clear();
8660     Previous.setLookupName(Correction.getCorrection());
8661     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8662                                     CDeclEnd = Correction.end();
8663          CDecl != CDeclEnd; ++CDecl) {
8664       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8665       if (FD && !FD->hasBody() &&
8666           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8667         Previous.addDecl(FD);
8668       }
8669     }
8670     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8671 
8672     NamedDecl *Result;
8673     // Retry building the function declaration with the new previous
8674     // declarations, and with errors suppressed.
8675     {
8676       // Trap errors.
8677       Sema::SFINAETrap Trap(SemaRef);
8678 
8679       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8680       // pieces need to verify the typo-corrected C++ declaration and hopefully
8681       // eliminate the need for the parameter pack ExtraArgs.
8682       Result = SemaRef.ActOnFunctionDeclarator(
8683           ExtraArgs.S, ExtraArgs.D,
8684           Correction.getCorrectionDecl()->getDeclContext(),
8685           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8686           ExtraArgs.AddToScope);
8687 
8688       if (Trap.hasErrorOccurred())
8689         Result = nullptr;
8690     }
8691 
8692     if (Result) {
8693       // Determine which correction we picked.
8694       Decl *Canonical = Result->getCanonicalDecl();
8695       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8696            I != E; ++I)
8697         if ((*I)->getCanonicalDecl() == Canonical)
8698           Correction.setCorrectionDecl(*I);
8699 
8700       // Let Sema know about the correction.
8701       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8702       SemaRef.diagnoseTypo(
8703           Correction,
8704           SemaRef.PDiag(IsLocalFriend
8705                           ? diag::err_no_matching_local_friend_suggest
8706                           : diag::err_member_decl_does_not_match_suggest)
8707             << Name << NewDC << IsDefinition);
8708       return Result;
8709     }
8710 
8711     // Pretend the typo correction never occurred
8712     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8713                               ExtraArgs.D.getIdentifierLoc());
8714     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8715     Previous.clear();
8716     Previous.setLookupName(Name);
8717   }
8718 
8719   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8720       << Name << NewDC << IsDefinition << NewFD->getLocation();
8721 
8722   bool NewFDisConst = false;
8723   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8724     NewFDisConst = NewMD->isConst();
8725 
8726   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8727        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8728        NearMatch != NearMatchEnd; ++NearMatch) {
8729     FunctionDecl *FD = NearMatch->first;
8730     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8731     bool FDisConst = MD && MD->isConst();
8732     bool IsMember = MD || !IsLocalFriend;
8733 
8734     // FIXME: These notes are poorly worded for the local friend case.
8735     if (unsigned Idx = NearMatch->second) {
8736       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8737       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8738       if (Loc.isInvalid()) Loc = FD->getLocation();
8739       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8740                                  : diag::note_local_decl_close_param_match)
8741         << Idx << FDParam->getType()
8742         << NewFD->getParamDecl(Idx - 1)->getType();
8743     } else if (FDisConst != NewFDisConst) {
8744       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8745           << NewFDisConst << FD->getSourceRange().getEnd()
8746           << (NewFDisConst
8747                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8748                                                  .getConstQualifierLoc())
8749                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8750                                                    .getRParenLoc()
8751                                                    .getLocWithOffset(1),
8752                                                " const"));
8753     } else
8754       SemaRef.Diag(FD->getLocation(),
8755                    IsMember ? diag::note_member_def_close_match
8756                             : diag::note_local_decl_close_match);
8757   }
8758   return nullptr;
8759 }
8760 
8761 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8762   switch (D.getDeclSpec().getStorageClassSpec()) {
8763   default: llvm_unreachable("Unknown storage class!");
8764   case DeclSpec::SCS_auto:
8765   case DeclSpec::SCS_register:
8766   case DeclSpec::SCS_mutable:
8767     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8768                  diag::err_typecheck_sclass_func);
8769     D.getMutableDeclSpec().ClearStorageClassSpecs();
8770     D.setInvalidType();
8771     break;
8772   case DeclSpec::SCS_unspecified: break;
8773   case DeclSpec::SCS_extern:
8774     if (D.getDeclSpec().isExternInLinkageSpec())
8775       return SC_None;
8776     return SC_Extern;
8777   case DeclSpec::SCS_static: {
8778     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8779       // C99 6.7.1p5:
8780       //   The declaration of an identifier for a function that has
8781       //   block scope shall have no explicit storage-class specifier
8782       //   other than extern
8783       // See also (C++ [dcl.stc]p4).
8784       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8785                    diag::err_static_block_func);
8786       break;
8787     } else
8788       return SC_Static;
8789   }
8790   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8791   }
8792 
8793   // No explicit storage class has already been returned
8794   return SC_None;
8795 }
8796 
8797 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8798                                            DeclContext *DC, QualType &R,
8799                                            TypeSourceInfo *TInfo,
8800                                            StorageClass SC,
8801                                            bool &IsVirtualOkay) {
8802   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8803   DeclarationName Name = NameInfo.getName();
8804 
8805   FunctionDecl *NewFD = nullptr;
8806   bool isInline = D.getDeclSpec().isInlineSpecified();
8807 
8808   if (!SemaRef.getLangOpts().CPlusPlus) {
8809     // Determine whether the function was written with a prototype. This is
8810     // true when:
8811     //   - there is a prototype in the declarator, or
8812     //   - the type R of the function is some kind of typedef or other non-
8813     //     attributed reference to a type name (which eventually refers to a
8814     //     function type). Note, we can't always look at the adjusted type to
8815     //     check this case because attributes may cause a non-function
8816     //     declarator to still have a function type. e.g.,
8817     //       typedef void func(int a);
8818     //       __attribute__((noreturn)) func other_func; // This has a prototype
8819     bool HasPrototype =
8820         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8821         (D.getDeclSpec().isTypeRep() &&
8822          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8823         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8824     assert(
8825         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8826         "Strict prototypes are required");
8827 
8828     NewFD = FunctionDecl::Create(
8829         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8830         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8831         ConstexprSpecKind::Unspecified,
8832         /*TrailingRequiresClause=*/nullptr);
8833     if (D.isInvalidType())
8834       NewFD->setInvalidDecl();
8835 
8836     return NewFD;
8837   }
8838 
8839   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8840 
8841   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8842   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8843     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8844                  diag::err_constexpr_wrong_decl_kind)
8845         << static_cast<int>(ConstexprKind);
8846     ConstexprKind = ConstexprSpecKind::Unspecified;
8847     D.getMutableDeclSpec().ClearConstexprSpec();
8848   }
8849   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8850 
8851   // Check that the return type is not an abstract class type.
8852   // For record types, this is done by the AbstractClassUsageDiagnoser once
8853   // the class has been completely parsed.
8854   if (!DC->isRecord() &&
8855       SemaRef.RequireNonAbstractType(
8856           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8857           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8858     D.setInvalidType();
8859 
8860   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8861     // This is a C++ constructor declaration.
8862     assert(DC->isRecord() &&
8863            "Constructors can only be declared in a member context");
8864 
8865     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8866     return CXXConstructorDecl::Create(
8867         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8868         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8869         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8870         InheritedConstructor(), TrailingRequiresClause);
8871 
8872   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8873     // This is a C++ destructor declaration.
8874     if (DC->isRecord()) {
8875       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8876       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8877       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8878           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8879           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8880           /*isImplicitlyDeclared=*/false, ConstexprKind,
8881           TrailingRequiresClause);
8882 
8883       // If the destructor needs an implicit exception specification, set it
8884       // now. FIXME: It'd be nice to be able to create the right type to start
8885       // with, but the type needs to reference the destructor declaration.
8886       if (SemaRef.getLangOpts().CPlusPlus11)
8887         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8888 
8889       IsVirtualOkay = true;
8890       return NewDD;
8891 
8892     } else {
8893       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8894       D.setInvalidType();
8895 
8896       // Create a FunctionDecl to satisfy the function definition parsing
8897       // code path.
8898       return FunctionDecl::Create(
8899           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8900           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8901           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8902     }
8903 
8904   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8905     if (!DC->isRecord()) {
8906       SemaRef.Diag(D.getIdentifierLoc(),
8907            diag::err_conv_function_not_member);
8908       return nullptr;
8909     }
8910 
8911     SemaRef.CheckConversionDeclarator(D, R, SC);
8912     if (D.isInvalidType())
8913       return nullptr;
8914 
8915     IsVirtualOkay = true;
8916     return CXXConversionDecl::Create(
8917         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8918         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8919         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8920         TrailingRequiresClause);
8921 
8922   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8923     if (TrailingRequiresClause)
8924       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8925                    diag::err_trailing_requires_clause_on_deduction_guide)
8926           << TrailingRequiresClause->getSourceRange();
8927     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8928 
8929     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8930                                          ExplicitSpecifier, NameInfo, R, TInfo,
8931                                          D.getEndLoc());
8932   } else if (DC->isRecord()) {
8933     // If the name of the function is the same as the name of the record,
8934     // then this must be an invalid constructor that has a return type.
8935     // (The parser checks for a return type and makes the declarator a
8936     // constructor if it has no return type).
8937     if (Name.getAsIdentifierInfo() &&
8938         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8939       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8940         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8941         << SourceRange(D.getIdentifierLoc());
8942       return nullptr;
8943     }
8944 
8945     // This is a C++ method declaration.
8946     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8947         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8948         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8949         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8950     IsVirtualOkay = !Ret->isStatic();
8951     return Ret;
8952   } else {
8953     bool isFriend =
8954         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8955     if (!isFriend && SemaRef.CurContext->isRecord())
8956       return nullptr;
8957 
8958     // Determine whether the function was written with a
8959     // prototype. This true when:
8960     //   - we're in C++ (where every function has a prototype),
8961     return FunctionDecl::Create(
8962         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8963         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8964         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8965   }
8966 }
8967 
8968 enum OpenCLParamType {
8969   ValidKernelParam,
8970   PtrPtrKernelParam,
8971   PtrKernelParam,
8972   InvalidAddrSpacePtrKernelParam,
8973   InvalidKernelParam,
8974   RecordKernelParam
8975 };
8976 
8977 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8978   // Size dependent types are just typedefs to normal integer types
8979   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8980   // integers other than by their names.
8981   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8982 
8983   // Remove typedefs one by one until we reach a typedef
8984   // for a size dependent type.
8985   QualType DesugaredTy = Ty;
8986   do {
8987     ArrayRef<StringRef> Names(SizeTypeNames);
8988     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8989     if (Names.end() != Match)
8990       return true;
8991 
8992     Ty = DesugaredTy;
8993     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8994   } while (DesugaredTy != Ty);
8995 
8996   return false;
8997 }
8998 
8999 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9000   if (PT->isDependentType())
9001     return InvalidKernelParam;
9002 
9003   if (PT->isPointerType() || PT->isReferenceType()) {
9004     QualType PointeeType = PT->getPointeeType();
9005     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9006         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9007         PointeeType.getAddressSpace() == LangAS::Default)
9008       return InvalidAddrSpacePtrKernelParam;
9009 
9010     if (PointeeType->isPointerType()) {
9011       // This is a pointer to pointer parameter.
9012       // Recursively check inner type.
9013       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9014       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9015           ParamKind == InvalidKernelParam)
9016         return ParamKind;
9017 
9018       return PtrPtrKernelParam;
9019     }
9020 
9021     // C++ for OpenCL v1.0 s2.4:
9022     // Moreover the types used in parameters of the kernel functions must be:
9023     // Standard layout types for pointer parameters. The same applies to
9024     // reference if an implementation supports them in kernel parameters.
9025     if (S.getLangOpts().OpenCLCPlusPlus &&
9026         !S.getOpenCLOptions().isAvailableOption(
9027             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9028         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9029         !PointeeType->isStandardLayoutType())
9030       return InvalidKernelParam;
9031 
9032     return PtrKernelParam;
9033   }
9034 
9035   // OpenCL v1.2 s6.9.k:
9036   // Arguments to kernel functions in a program cannot be declared with the
9037   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9038   // uintptr_t or a struct and/or union that contain fields declared to be one
9039   // of these built-in scalar types.
9040   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9041     return InvalidKernelParam;
9042 
9043   if (PT->isImageType())
9044     return PtrKernelParam;
9045 
9046   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9047     return InvalidKernelParam;
9048 
9049   // OpenCL extension spec v1.2 s9.5:
9050   // This extension adds support for half scalar and vector types as built-in
9051   // types that can be used for arithmetic operations, conversions etc.
9052   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9053       PT->isHalfType())
9054     return InvalidKernelParam;
9055 
9056   // Look into an array argument to check if it has a forbidden type.
9057   if (PT->isArrayType()) {
9058     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9059     // Call ourself to check an underlying type of an array. Since the
9060     // getPointeeOrArrayElementType returns an innermost type which is not an
9061     // array, this recursive call only happens once.
9062     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9063   }
9064 
9065   // C++ for OpenCL v1.0 s2.4:
9066   // Moreover the types used in parameters of the kernel functions must be:
9067   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9068   // types) for parameters passed by value;
9069   if (S.getLangOpts().OpenCLCPlusPlus &&
9070       !S.getOpenCLOptions().isAvailableOption(
9071           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9072       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9073     return InvalidKernelParam;
9074 
9075   if (PT->isRecordType())
9076     return RecordKernelParam;
9077 
9078   return ValidKernelParam;
9079 }
9080 
9081 static void checkIsValidOpenCLKernelParameter(
9082   Sema &S,
9083   Declarator &D,
9084   ParmVarDecl *Param,
9085   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9086   QualType PT = Param->getType();
9087 
9088   // Cache the valid types we encounter to avoid rechecking structs that are
9089   // used again
9090   if (ValidTypes.count(PT.getTypePtr()))
9091     return;
9092 
9093   switch (getOpenCLKernelParameterType(S, PT)) {
9094   case PtrPtrKernelParam:
9095     // OpenCL v3.0 s6.11.a:
9096     // A kernel function argument cannot be declared as a pointer to a pointer
9097     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9098     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9099       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9100       D.setInvalidType();
9101       return;
9102     }
9103 
9104     ValidTypes.insert(PT.getTypePtr());
9105     return;
9106 
9107   case InvalidAddrSpacePtrKernelParam:
9108     // OpenCL v1.0 s6.5:
9109     // __kernel function arguments declared to be a pointer of a type can point
9110     // to one of the following address spaces only : __global, __local or
9111     // __constant.
9112     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9113     D.setInvalidType();
9114     return;
9115 
9116     // OpenCL v1.2 s6.9.k:
9117     // Arguments to kernel functions in a program cannot be declared with the
9118     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9119     // uintptr_t or a struct and/or union that contain fields declared to be
9120     // one of these built-in scalar types.
9121 
9122   case InvalidKernelParam:
9123     // OpenCL v1.2 s6.8 n:
9124     // A kernel function argument cannot be declared
9125     // of event_t type.
9126     // Do not diagnose half type since it is diagnosed as invalid argument
9127     // type for any function elsewhere.
9128     if (!PT->isHalfType()) {
9129       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9130 
9131       // Explain what typedefs are involved.
9132       const TypedefType *Typedef = nullptr;
9133       while ((Typedef = PT->getAs<TypedefType>())) {
9134         SourceLocation Loc = Typedef->getDecl()->getLocation();
9135         // SourceLocation may be invalid for a built-in type.
9136         if (Loc.isValid())
9137           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9138         PT = Typedef->desugar();
9139       }
9140     }
9141 
9142     D.setInvalidType();
9143     return;
9144 
9145   case PtrKernelParam:
9146   case ValidKernelParam:
9147     ValidTypes.insert(PT.getTypePtr());
9148     return;
9149 
9150   case RecordKernelParam:
9151     break;
9152   }
9153 
9154   // Track nested structs we will inspect
9155   SmallVector<const Decl *, 4> VisitStack;
9156 
9157   // Track where we are in the nested structs. Items will migrate from
9158   // VisitStack to HistoryStack as we do the DFS for bad field.
9159   SmallVector<const FieldDecl *, 4> HistoryStack;
9160   HistoryStack.push_back(nullptr);
9161 
9162   // At this point we already handled everything except of a RecordType or
9163   // an ArrayType of a RecordType.
9164   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9165   const RecordType *RecTy =
9166       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9167   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9168 
9169   VisitStack.push_back(RecTy->getDecl());
9170   assert(VisitStack.back() && "First decl null?");
9171 
9172   do {
9173     const Decl *Next = VisitStack.pop_back_val();
9174     if (!Next) {
9175       assert(!HistoryStack.empty());
9176       // Found a marker, we have gone up a level
9177       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9178         ValidTypes.insert(Hist->getType().getTypePtr());
9179 
9180       continue;
9181     }
9182 
9183     // Adds everything except the original parameter declaration (which is not a
9184     // field itself) to the history stack.
9185     const RecordDecl *RD;
9186     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9187       HistoryStack.push_back(Field);
9188 
9189       QualType FieldTy = Field->getType();
9190       // Other field types (known to be valid or invalid) are handled while we
9191       // walk around RecordDecl::fields().
9192       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9193              "Unexpected type.");
9194       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9195 
9196       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9197     } else {
9198       RD = cast<RecordDecl>(Next);
9199     }
9200 
9201     // Add a null marker so we know when we've gone back up a level
9202     VisitStack.push_back(nullptr);
9203 
9204     for (const auto *FD : RD->fields()) {
9205       QualType QT = FD->getType();
9206 
9207       if (ValidTypes.count(QT.getTypePtr()))
9208         continue;
9209 
9210       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9211       if (ParamType == ValidKernelParam)
9212         continue;
9213 
9214       if (ParamType == RecordKernelParam) {
9215         VisitStack.push_back(FD);
9216         continue;
9217       }
9218 
9219       // OpenCL v1.2 s6.9.p:
9220       // Arguments to kernel functions that are declared to be a struct or union
9221       // do not allow OpenCL objects to be passed as elements of the struct or
9222       // union.
9223       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9224           ParamType == InvalidAddrSpacePtrKernelParam) {
9225         S.Diag(Param->getLocation(),
9226                diag::err_record_with_pointers_kernel_param)
9227           << PT->isUnionType()
9228           << PT;
9229       } else {
9230         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9231       }
9232 
9233       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9234           << OrigRecDecl->getDeclName();
9235 
9236       // We have an error, now let's go back up through history and show where
9237       // the offending field came from
9238       for (ArrayRef<const FieldDecl *>::const_iterator
9239                I = HistoryStack.begin() + 1,
9240                E = HistoryStack.end();
9241            I != E; ++I) {
9242         const FieldDecl *OuterField = *I;
9243         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9244           << OuterField->getType();
9245       }
9246 
9247       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9248         << QT->isPointerType()
9249         << QT;
9250       D.setInvalidType();
9251       return;
9252     }
9253   } while (!VisitStack.empty());
9254 }
9255 
9256 /// Find the DeclContext in which a tag is implicitly declared if we see an
9257 /// elaborated type specifier in the specified context, and lookup finds
9258 /// nothing.
9259 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9260   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9261     DC = DC->getParent();
9262   return DC;
9263 }
9264 
9265 /// Find the Scope in which a tag is implicitly declared if we see an
9266 /// elaborated type specifier in the specified context, and lookup finds
9267 /// nothing.
9268 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9269   while (S->isClassScope() ||
9270          (LangOpts.CPlusPlus &&
9271           S->isFunctionPrototypeScope()) ||
9272          ((S->getFlags() & Scope::DeclScope) == 0) ||
9273          (S->getEntity() && S->getEntity()->isTransparentContext()))
9274     S = S->getParent();
9275   return S;
9276 }
9277 
9278 /// Determine whether a declaration matches a known function in namespace std.
9279 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9280                          unsigned BuiltinID) {
9281   switch (BuiltinID) {
9282   case Builtin::BI__GetExceptionInfo:
9283     // No type checking whatsoever.
9284     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9285 
9286   case Builtin::BIaddressof:
9287   case Builtin::BI__addressof:
9288   case Builtin::BIforward:
9289   case Builtin::BImove:
9290   case Builtin::BImove_if_noexcept:
9291   case Builtin::BIas_const: {
9292     // Ensure that we don't treat the algorithm
9293     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9294     // as the builtin std::move.
9295     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9296     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9297   }
9298 
9299   default:
9300     return false;
9301   }
9302 }
9303 
9304 NamedDecl*
9305 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9306                               TypeSourceInfo *TInfo, LookupResult &Previous,
9307                               MultiTemplateParamsArg TemplateParamListsRef,
9308                               bool &AddToScope) {
9309   QualType R = TInfo->getType();
9310 
9311   assert(R->isFunctionType());
9312   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9313     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9314 
9315   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9316   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9317   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9318     if (!TemplateParamLists.empty() &&
9319         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9320       TemplateParamLists.back() = Invented;
9321     else
9322       TemplateParamLists.push_back(Invented);
9323   }
9324 
9325   // TODO: consider using NameInfo for diagnostic.
9326   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9327   DeclarationName Name = NameInfo.getName();
9328   StorageClass SC = getFunctionStorageClass(*this, D);
9329 
9330   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9331     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9332          diag::err_invalid_thread)
9333       << DeclSpec::getSpecifierName(TSCS);
9334 
9335   if (D.isFirstDeclarationOfMember())
9336     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9337                            D.getIdentifierLoc());
9338 
9339   bool isFriend = false;
9340   FunctionTemplateDecl *FunctionTemplate = nullptr;
9341   bool isMemberSpecialization = false;
9342   bool isFunctionTemplateSpecialization = false;
9343 
9344   bool isDependentClassScopeExplicitSpecialization = false;
9345   bool HasExplicitTemplateArgs = false;
9346   TemplateArgumentListInfo TemplateArgs;
9347 
9348   bool isVirtualOkay = false;
9349 
9350   DeclContext *OriginalDC = DC;
9351   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9352 
9353   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9354                                               isVirtualOkay);
9355   if (!NewFD) return nullptr;
9356 
9357   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9358     NewFD->setTopLevelDeclInObjCContainer();
9359 
9360   // Set the lexical context. If this is a function-scope declaration, or has a
9361   // C++ scope specifier, or is the object of a friend declaration, the lexical
9362   // context will be different from the semantic context.
9363   NewFD->setLexicalDeclContext(CurContext);
9364 
9365   if (IsLocalExternDecl)
9366     NewFD->setLocalExternDecl();
9367 
9368   if (getLangOpts().CPlusPlus) {
9369     bool isInline = D.getDeclSpec().isInlineSpecified();
9370     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9371     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9372     isFriend = D.getDeclSpec().isFriendSpecified();
9373     if (isFriend && !isInline && D.isFunctionDefinition()) {
9374       // C++ [class.friend]p5
9375       //   A function can be defined in a friend declaration of a
9376       //   class . . . . Such a function is implicitly inline.
9377       NewFD->setImplicitlyInline();
9378     }
9379 
9380     // If this is a method defined in an __interface, and is not a constructor
9381     // or an overloaded operator, then set the pure flag (isVirtual will already
9382     // return true).
9383     if (const CXXRecordDecl *Parent =
9384           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9385       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9386         NewFD->setPure(true);
9387 
9388       // C++ [class.union]p2
9389       //   A union can have member functions, but not virtual functions.
9390       if (isVirtual && Parent->isUnion()) {
9391         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9392         NewFD->setInvalidDecl();
9393       }
9394       if ((Parent->isClass() || Parent->isStruct()) &&
9395           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9396           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9397           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9398         if (auto *Def = Parent->getDefinition())
9399           Def->setInitMethod(true);
9400       }
9401     }
9402 
9403     SetNestedNameSpecifier(*this, NewFD, D);
9404     isMemberSpecialization = false;
9405     isFunctionTemplateSpecialization = false;
9406     if (D.isInvalidType())
9407       NewFD->setInvalidDecl();
9408 
9409     // Match up the template parameter lists with the scope specifier, then
9410     // determine whether we have a template or a template specialization.
9411     bool Invalid = false;
9412     TemplateParameterList *TemplateParams =
9413         MatchTemplateParametersToScopeSpecifier(
9414             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9415             D.getCXXScopeSpec(),
9416             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9417                 ? D.getName().TemplateId
9418                 : nullptr,
9419             TemplateParamLists, isFriend, isMemberSpecialization,
9420             Invalid);
9421     if (TemplateParams) {
9422       // Check that we can declare a template here.
9423       if (CheckTemplateDeclScope(S, TemplateParams))
9424         NewFD->setInvalidDecl();
9425 
9426       if (TemplateParams->size() > 0) {
9427         // This is a function template
9428 
9429         // A destructor cannot be a template.
9430         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9431           Diag(NewFD->getLocation(), diag::err_destructor_template);
9432           NewFD->setInvalidDecl();
9433         }
9434 
9435         // If we're adding a template to a dependent context, we may need to
9436         // rebuilding some of the types used within the template parameter list,
9437         // now that we know what the current instantiation is.
9438         if (DC->isDependentContext()) {
9439           ContextRAII SavedContext(*this, DC);
9440           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9441             Invalid = true;
9442         }
9443 
9444         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9445                                                         NewFD->getLocation(),
9446                                                         Name, TemplateParams,
9447                                                         NewFD);
9448         FunctionTemplate->setLexicalDeclContext(CurContext);
9449         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9450 
9451         // For source fidelity, store the other template param lists.
9452         if (TemplateParamLists.size() > 1) {
9453           NewFD->setTemplateParameterListsInfo(Context,
9454               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9455                   .drop_back(1));
9456         }
9457       } else {
9458         // This is a function template specialization.
9459         isFunctionTemplateSpecialization = true;
9460         // For source fidelity, store all the template param lists.
9461         if (TemplateParamLists.size() > 0)
9462           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9463 
9464         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9465         if (isFriend) {
9466           // We want to remove the "template<>", found here.
9467           SourceRange RemoveRange = TemplateParams->getSourceRange();
9468 
9469           // If we remove the template<> and the name is not a
9470           // template-id, we're actually silently creating a problem:
9471           // the friend declaration will refer to an untemplated decl,
9472           // and clearly the user wants a template specialization.  So
9473           // we need to insert '<>' after the name.
9474           SourceLocation InsertLoc;
9475           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9476             InsertLoc = D.getName().getSourceRange().getEnd();
9477             InsertLoc = getLocForEndOfToken(InsertLoc);
9478           }
9479 
9480           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9481             << Name << RemoveRange
9482             << FixItHint::CreateRemoval(RemoveRange)
9483             << FixItHint::CreateInsertion(InsertLoc, "<>");
9484           Invalid = true;
9485         }
9486       }
9487     } else {
9488       // Check that we can declare a template here.
9489       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9490           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9491         NewFD->setInvalidDecl();
9492 
9493       // All template param lists were matched against the scope specifier:
9494       // this is NOT (an explicit specialization of) a template.
9495       if (TemplateParamLists.size() > 0)
9496         // For source fidelity, store all the template param lists.
9497         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9498     }
9499 
9500     if (Invalid) {
9501       NewFD->setInvalidDecl();
9502       if (FunctionTemplate)
9503         FunctionTemplate->setInvalidDecl();
9504     }
9505 
9506     // C++ [dcl.fct.spec]p5:
9507     //   The virtual specifier shall only be used in declarations of
9508     //   nonstatic class member functions that appear within a
9509     //   member-specification of a class declaration; see 10.3.
9510     //
9511     if (isVirtual && !NewFD->isInvalidDecl()) {
9512       if (!isVirtualOkay) {
9513         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9514              diag::err_virtual_non_function);
9515       } else if (!CurContext->isRecord()) {
9516         // 'virtual' was specified outside of the class.
9517         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9518              diag::err_virtual_out_of_class)
9519           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9520       } else if (NewFD->getDescribedFunctionTemplate()) {
9521         // C++ [temp.mem]p3:
9522         //  A member function template shall not be virtual.
9523         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9524              diag::err_virtual_member_function_template)
9525           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9526       } else {
9527         // Okay: Add virtual to the method.
9528         NewFD->setVirtualAsWritten(true);
9529       }
9530 
9531       if (getLangOpts().CPlusPlus14 &&
9532           NewFD->getReturnType()->isUndeducedType())
9533         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9534     }
9535 
9536     if (getLangOpts().CPlusPlus14 &&
9537         (NewFD->isDependentContext() ||
9538          (isFriend && CurContext->isDependentContext())) &&
9539         NewFD->getReturnType()->isUndeducedType()) {
9540       // If the function template is referenced directly (for instance, as a
9541       // member of the current instantiation), pretend it has a dependent type.
9542       // This is not really justified by the standard, but is the only sane
9543       // thing to do.
9544       // FIXME: For a friend function, we have not marked the function as being
9545       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9546       const FunctionProtoType *FPT =
9547           NewFD->getType()->castAs<FunctionProtoType>();
9548       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9549       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9550                                              FPT->getExtProtoInfo()));
9551     }
9552 
9553     // C++ [dcl.fct.spec]p3:
9554     //  The inline specifier shall not appear on a block scope function
9555     //  declaration.
9556     if (isInline && !NewFD->isInvalidDecl()) {
9557       if (CurContext->isFunctionOrMethod()) {
9558         // 'inline' is not allowed on block scope function declaration.
9559         Diag(D.getDeclSpec().getInlineSpecLoc(),
9560              diag::err_inline_declaration_block_scope) << Name
9561           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9562       }
9563     }
9564 
9565     // C++ [dcl.fct.spec]p6:
9566     //  The explicit specifier shall be used only in the declaration of a
9567     //  constructor or conversion function within its class definition;
9568     //  see 12.3.1 and 12.3.2.
9569     if (hasExplicit && !NewFD->isInvalidDecl() &&
9570         !isa<CXXDeductionGuideDecl>(NewFD)) {
9571       if (!CurContext->isRecord()) {
9572         // 'explicit' was specified outside of the class.
9573         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9574              diag::err_explicit_out_of_class)
9575             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9576       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9577                  !isa<CXXConversionDecl>(NewFD)) {
9578         // 'explicit' was specified on a function that wasn't a constructor
9579         // or conversion function.
9580         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9581              diag::err_explicit_non_ctor_or_conv_function)
9582             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9583       }
9584     }
9585 
9586     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9587     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9588       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9589       // are implicitly inline.
9590       NewFD->setImplicitlyInline();
9591 
9592       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9593       // be either constructors or to return a literal type. Therefore,
9594       // destructors cannot be declared constexpr.
9595       if (isa<CXXDestructorDecl>(NewFD) &&
9596           (!getLangOpts().CPlusPlus20 ||
9597            ConstexprKind == ConstexprSpecKind::Consteval)) {
9598         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9599             << static_cast<int>(ConstexprKind);
9600         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9601                                     ? ConstexprSpecKind::Unspecified
9602                                     : ConstexprSpecKind::Constexpr);
9603       }
9604       // C++20 [dcl.constexpr]p2: An allocation function, or a
9605       // deallocation function shall not be declared with the consteval
9606       // specifier.
9607       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9608           (NewFD->getOverloadedOperator() == OO_New ||
9609            NewFD->getOverloadedOperator() == OO_Array_New ||
9610            NewFD->getOverloadedOperator() == OO_Delete ||
9611            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9612         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9613              diag::err_invalid_consteval_decl_kind)
9614             << NewFD;
9615         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9616       }
9617     }
9618 
9619     // If __module_private__ was specified, mark the function accordingly.
9620     if (D.getDeclSpec().isModulePrivateSpecified()) {
9621       if (isFunctionTemplateSpecialization) {
9622         SourceLocation ModulePrivateLoc
9623           = D.getDeclSpec().getModulePrivateSpecLoc();
9624         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9625           << 0
9626           << FixItHint::CreateRemoval(ModulePrivateLoc);
9627       } else {
9628         NewFD->setModulePrivate();
9629         if (FunctionTemplate)
9630           FunctionTemplate->setModulePrivate();
9631       }
9632     }
9633 
9634     if (isFriend) {
9635       if (FunctionTemplate) {
9636         FunctionTemplate->setObjectOfFriendDecl();
9637         FunctionTemplate->setAccess(AS_public);
9638       }
9639       NewFD->setObjectOfFriendDecl();
9640       NewFD->setAccess(AS_public);
9641     }
9642 
9643     // If a function is defined as defaulted or deleted, mark it as such now.
9644     // We'll do the relevant checks on defaulted / deleted functions later.
9645     switch (D.getFunctionDefinitionKind()) {
9646     case FunctionDefinitionKind::Declaration:
9647     case FunctionDefinitionKind::Definition:
9648       break;
9649 
9650     case FunctionDefinitionKind::Defaulted:
9651       NewFD->setDefaulted();
9652       break;
9653 
9654     case FunctionDefinitionKind::Deleted:
9655       NewFD->setDeletedAsWritten();
9656       break;
9657     }
9658 
9659     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9660         D.isFunctionDefinition()) {
9661       // C++ [class.mfct]p2:
9662       //   A member function may be defined (8.4) in its class definition, in
9663       //   which case it is an inline member function (7.1.2)
9664       NewFD->setImplicitlyInline();
9665     }
9666 
9667     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9668         !CurContext->isRecord()) {
9669       // C++ [class.static]p1:
9670       //   A data or function member of a class may be declared static
9671       //   in a class definition, in which case it is a static member of
9672       //   the class.
9673 
9674       // Complain about the 'static' specifier if it's on an out-of-line
9675       // member function definition.
9676 
9677       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9678       // member function template declaration and class member template
9679       // declaration (MSVC versions before 2015), warn about this.
9680       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9681            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9682              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9683            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9684            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9685         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9686     }
9687 
9688     // C++11 [except.spec]p15:
9689     //   A deallocation function with no exception-specification is treated
9690     //   as if it were specified with noexcept(true).
9691     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9692     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9693          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9694         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9695       NewFD->setType(Context.getFunctionType(
9696           FPT->getReturnType(), FPT->getParamTypes(),
9697           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9698   }
9699 
9700   // Filter out previous declarations that don't match the scope.
9701   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9702                        D.getCXXScopeSpec().isNotEmpty() ||
9703                        isMemberSpecialization ||
9704                        isFunctionTemplateSpecialization);
9705 
9706   // Handle GNU asm-label extension (encoded as an attribute).
9707   if (Expr *E = (Expr*) D.getAsmLabel()) {
9708     // The parser guarantees this is a string.
9709     StringLiteral *SE = cast<StringLiteral>(E);
9710     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9711                                         /*IsLiteralLabel=*/true,
9712                                         SE->getStrTokenLoc(0)));
9713   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9714     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9715       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9716     if (I != ExtnameUndeclaredIdentifiers.end()) {
9717       if (isDeclExternC(NewFD)) {
9718         NewFD->addAttr(I->second);
9719         ExtnameUndeclaredIdentifiers.erase(I);
9720       } else
9721         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9722             << /*Variable*/0 << NewFD;
9723     }
9724   }
9725 
9726   // Copy the parameter declarations from the declarator D to the function
9727   // declaration NewFD, if they are available.  First scavenge them into Params.
9728   SmallVector<ParmVarDecl*, 16> Params;
9729   unsigned FTIIdx;
9730   if (D.isFunctionDeclarator(FTIIdx)) {
9731     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9732 
9733     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9734     // function that takes no arguments, not a function that takes a
9735     // single void argument.
9736     // We let through "const void" here because Sema::GetTypeForDeclarator
9737     // already checks for that case.
9738     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9739       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9740         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9741         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9742         Param->setDeclContext(NewFD);
9743         Params.push_back(Param);
9744 
9745         if (Param->isInvalidDecl())
9746           NewFD->setInvalidDecl();
9747       }
9748     }
9749 
9750     if (!getLangOpts().CPlusPlus) {
9751       // In C, find all the tag declarations from the prototype and move them
9752       // into the function DeclContext. Remove them from the surrounding tag
9753       // injection context of the function, which is typically but not always
9754       // the TU.
9755       DeclContext *PrototypeTagContext =
9756           getTagInjectionContext(NewFD->getLexicalDeclContext());
9757       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9758         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9759 
9760         // We don't want to reparent enumerators. Look at their parent enum
9761         // instead.
9762         if (!TD) {
9763           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9764             TD = cast<EnumDecl>(ECD->getDeclContext());
9765         }
9766         if (!TD)
9767           continue;
9768         DeclContext *TagDC = TD->getLexicalDeclContext();
9769         if (!TagDC->containsDecl(TD))
9770           continue;
9771         TagDC->removeDecl(TD);
9772         TD->setDeclContext(NewFD);
9773         NewFD->addDecl(TD);
9774 
9775         // Preserve the lexical DeclContext if it is not the surrounding tag
9776         // injection context of the FD. In this example, the semantic context of
9777         // E will be f and the lexical context will be S, while both the
9778         // semantic and lexical contexts of S will be f:
9779         //   void f(struct S { enum E { a } f; } s);
9780         if (TagDC != PrototypeTagContext)
9781           TD->setLexicalDeclContext(TagDC);
9782       }
9783     }
9784   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9785     // When we're declaring a function with a typedef, typeof, etc as in the
9786     // following example, we'll need to synthesize (unnamed)
9787     // parameters for use in the declaration.
9788     //
9789     // @code
9790     // typedef void fn(int);
9791     // fn f;
9792     // @endcode
9793 
9794     // Synthesize a parameter for each argument type.
9795     for (const auto &AI : FT->param_types()) {
9796       ParmVarDecl *Param =
9797           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9798       Param->setScopeInfo(0, Params.size());
9799       Params.push_back(Param);
9800     }
9801   } else {
9802     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9803            "Should not need args for typedef of non-prototype fn");
9804   }
9805 
9806   // Finally, we know we have the right number of parameters, install them.
9807   NewFD->setParams(Params);
9808 
9809   if (D.getDeclSpec().isNoreturnSpecified())
9810     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9811                                            D.getDeclSpec().getNoreturnSpecLoc(),
9812                                            AttributeCommonInfo::AS_Keyword));
9813 
9814   // Functions returning a variably modified type violate C99 6.7.5.2p2
9815   // because all functions have linkage.
9816   if (!NewFD->isInvalidDecl() &&
9817       NewFD->getReturnType()->isVariablyModifiedType()) {
9818     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9819     NewFD->setInvalidDecl();
9820   }
9821 
9822   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9823   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9824       !NewFD->hasAttr<SectionAttr>())
9825     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9826         Context, PragmaClangTextSection.SectionName,
9827         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9828 
9829   // Apply an implicit SectionAttr if #pragma code_seg is active.
9830   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9831       !NewFD->hasAttr<SectionAttr>()) {
9832     NewFD->addAttr(SectionAttr::CreateImplicit(
9833         Context, CodeSegStack.CurrentValue->getString(),
9834         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9835         SectionAttr::Declspec_allocate));
9836     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9837                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9838                          ASTContext::PSF_Read,
9839                      NewFD))
9840       NewFD->dropAttr<SectionAttr>();
9841   }
9842 
9843   // Apply an implicit CodeSegAttr from class declspec or
9844   // apply an implicit SectionAttr from #pragma code_seg if active.
9845   if (!NewFD->hasAttr<CodeSegAttr>()) {
9846     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9847                                                                  D.isFunctionDefinition())) {
9848       NewFD->addAttr(SAttr);
9849     }
9850   }
9851 
9852   // Handle attributes.
9853   ProcessDeclAttributes(S, NewFD, D);
9854 
9855   if (getLangOpts().OpenCL) {
9856     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9857     // type declaration will generate a compilation error.
9858     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9859     if (AddressSpace != LangAS::Default) {
9860       Diag(NewFD->getLocation(),
9861            diag::err_opencl_return_value_with_address_space);
9862       NewFD->setInvalidDecl();
9863     }
9864   }
9865 
9866   if (!getLangOpts().CPlusPlus) {
9867     // Perform semantic checking on the function declaration.
9868     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9869       CheckMain(NewFD, D.getDeclSpec());
9870 
9871     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9872       CheckMSVCRTEntryPoint(NewFD);
9873 
9874     if (!NewFD->isInvalidDecl())
9875       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9876                                                   isMemberSpecialization,
9877                                                   D.isFunctionDefinition()));
9878     else if (!Previous.empty())
9879       // Recover gracefully from an invalid redeclaration.
9880       D.setRedeclaration(true);
9881     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9882             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9883            "previous declaration set still overloaded");
9884 
9885     // Diagnose no-prototype function declarations with calling conventions that
9886     // don't support variadic calls. Only do this in C and do it after merging
9887     // possibly prototyped redeclarations.
9888     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9889     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9890       CallingConv CC = FT->getExtInfo().getCC();
9891       if (!supportsVariadicCall(CC)) {
9892         // Windows system headers sometimes accidentally use stdcall without
9893         // (void) parameters, so we relax this to a warning.
9894         int DiagID =
9895             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9896         Diag(NewFD->getLocation(), DiagID)
9897             << FunctionType::getNameForCallConv(CC);
9898       }
9899     }
9900 
9901    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9902        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9903      checkNonTrivialCUnion(NewFD->getReturnType(),
9904                            NewFD->getReturnTypeSourceRange().getBegin(),
9905                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9906   } else {
9907     // C++11 [replacement.functions]p3:
9908     //  The program's definitions shall not be specified as inline.
9909     //
9910     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9911     //
9912     // Suppress the diagnostic if the function is __attribute__((used)), since
9913     // that forces an external definition to be emitted.
9914     if (D.getDeclSpec().isInlineSpecified() &&
9915         NewFD->isReplaceableGlobalAllocationFunction() &&
9916         !NewFD->hasAttr<UsedAttr>())
9917       Diag(D.getDeclSpec().getInlineSpecLoc(),
9918            diag::ext_operator_new_delete_declared_inline)
9919         << NewFD->getDeclName();
9920 
9921     // If the declarator is a template-id, translate the parser's template
9922     // argument list into our AST format.
9923     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9924       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9925       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9926       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9927       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9928                                          TemplateId->NumArgs);
9929       translateTemplateArguments(TemplateArgsPtr,
9930                                  TemplateArgs);
9931 
9932       HasExplicitTemplateArgs = true;
9933 
9934       if (NewFD->isInvalidDecl()) {
9935         HasExplicitTemplateArgs = false;
9936       } else if (FunctionTemplate) {
9937         // Function template with explicit template arguments.
9938         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9939           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9940 
9941         HasExplicitTemplateArgs = false;
9942       } else {
9943         assert((isFunctionTemplateSpecialization ||
9944                 D.getDeclSpec().isFriendSpecified()) &&
9945                "should have a 'template<>' for this decl");
9946         // "friend void foo<>(int);" is an implicit specialization decl.
9947         isFunctionTemplateSpecialization = true;
9948       }
9949     } else if (isFriend && isFunctionTemplateSpecialization) {
9950       // This combination is only possible in a recovery case;  the user
9951       // wrote something like:
9952       //   template <> friend void foo(int);
9953       // which we're recovering from as if the user had written:
9954       //   friend void foo<>(int);
9955       // Go ahead and fake up a template id.
9956       HasExplicitTemplateArgs = true;
9957       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9958       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9959     }
9960 
9961     // We do not add HD attributes to specializations here because
9962     // they may have different constexpr-ness compared to their
9963     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9964     // may end up with different effective targets. Instead, a
9965     // specialization inherits its target attributes from its template
9966     // in the CheckFunctionTemplateSpecialization() call below.
9967     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9968       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9969 
9970     // If it's a friend (and only if it's a friend), it's possible
9971     // that either the specialized function type or the specialized
9972     // template is dependent, and therefore matching will fail.  In
9973     // this case, don't check the specialization yet.
9974     if (isFunctionTemplateSpecialization && isFriend &&
9975         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9976          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9977              TemplateArgs.arguments()))) {
9978       assert(HasExplicitTemplateArgs &&
9979              "friend function specialization without template args");
9980       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9981                                                        Previous))
9982         NewFD->setInvalidDecl();
9983     } else if (isFunctionTemplateSpecialization) {
9984       if (CurContext->isDependentContext() && CurContext->isRecord()
9985           && !isFriend) {
9986         isDependentClassScopeExplicitSpecialization = true;
9987       } else if (!NewFD->isInvalidDecl() &&
9988                  CheckFunctionTemplateSpecialization(
9989                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9990                      Previous))
9991         NewFD->setInvalidDecl();
9992 
9993       // C++ [dcl.stc]p1:
9994       //   A storage-class-specifier shall not be specified in an explicit
9995       //   specialization (14.7.3)
9996       FunctionTemplateSpecializationInfo *Info =
9997           NewFD->getTemplateSpecializationInfo();
9998       if (Info && SC != SC_None) {
9999         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10000           Diag(NewFD->getLocation(),
10001                diag::err_explicit_specialization_inconsistent_storage_class)
10002             << SC
10003             << FixItHint::CreateRemoval(
10004                                       D.getDeclSpec().getStorageClassSpecLoc());
10005 
10006         else
10007           Diag(NewFD->getLocation(),
10008                diag::ext_explicit_specialization_storage_class)
10009             << FixItHint::CreateRemoval(
10010                                       D.getDeclSpec().getStorageClassSpecLoc());
10011       }
10012     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10013       if (CheckMemberSpecialization(NewFD, Previous))
10014           NewFD->setInvalidDecl();
10015     }
10016 
10017     // Perform semantic checking on the function declaration.
10018     if (!isDependentClassScopeExplicitSpecialization) {
10019       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10020         CheckMain(NewFD, D.getDeclSpec());
10021 
10022       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10023         CheckMSVCRTEntryPoint(NewFD);
10024 
10025       if (!NewFD->isInvalidDecl())
10026         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10027                                                     isMemberSpecialization,
10028                                                     D.isFunctionDefinition()));
10029       else if (!Previous.empty())
10030         // Recover gracefully from an invalid redeclaration.
10031         D.setRedeclaration(true);
10032     }
10033 
10034     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10035             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10036            "previous declaration set still overloaded");
10037 
10038     NamedDecl *PrincipalDecl = (FunctionTemplate
10039                                 ? cast<NamedDecl>(FunctionTemplate)
10040                                 : NewFD);
10041 
10042     if (isFriend && NewFD->getPreviousDecl()) {
10043       AccessSpecifier Access = AS_public;
10044       if (!NewFD->isInvalidDecl())
10045         Access = NewFD->getPreviousDecl()->getAccess();
10046 
10047       NewFD->setAccess(Access);
10048       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10049     }
10050 
10051     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10052         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10053       PrincipalDecl->setNonMemberOperator();
10054 
10055     // If we have a function template, check the template parameter
10056     // list. This will check and merge default template arguments.
10057     if (FunctionTemplate) {
10058       FunctionTemplateDecl *PrevTemplate =
10059                                      FunctionTemplate->getPreviousDecl();
10060       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10061                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10062                                     : nullptr,
10063                             D.getDeclSpec().isFriendSpecified()
10064                               ? (D.isFunctionDefinition()
10065                                    ? TPC_FriendFunctionTemplateDefinition
10066                                    : TPC_FriendFunctionTemplate)
10067                               : (D.getCXXScopeSpec().isSet() &&
10068                                  DC && DC->isRecord() &&
10069                                  DC->isDependentContext())
10070                                   ? TPC_ClassTemplateMember
10071                                   : TPC_FunctionTemplate);
10072     }
10073 
10074     if (NewFD->isInvalidDecl()) {
10075       // Ignore all the rest of this.
10076     } else if (!D.isRedeclaration()) {
10077       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10078                                        AddToScope };
10079       // Fake up an access specifier if it's supposed to be a class member.
10080       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10081         NewFD->setAccess(AS_public);
10082 
10083       // Qualified decls generally require a previous declaration.
10084       if (D.getCXXScopeSpec().isSet()) {
10085         // ...with the major exception of templated-scope or
10086         // dependent-scope friend declarations.
10087 
10088         // TODO: we currently also suppress this check in dependent
10089         // contexts because (1) the parameter depth will be off when
10090         // matching friend templates and (2) we might actually be
10091         // selecting a friend based on a dependent factor.  But there
10092         // are situations where these conditions don't apply and we
10093         // can actually do this check immediately.
10094         //
10095         // Unless the scope is dependent, it's always an error if qualified
10096         // redeclaration lookup found nothing at all. Diagnose that now;
10097         // nothing will diagnose that error later.
10098         if (isFriend &&
10099             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10100              (!Previous.empty() && CurContext->isDependentContext()))) {
10101           // ignore these
10102         } else if (NewFD->isCPUDispatchMultiVersion() ||
10103                    NewFD->isCPUSpecificMultiVersion()) {
10104           // ignore this, we allow the redeclaration behavior here to create new
10105           // versions of the function.
10106         } else {
10107           // The user tried to provide an out-of-line definition for a
10108           // function that is a member of a class or namespace, but there
10109           // was no such member function declared (C++ [class.mfct]p2,
10110           // C++ [namespace.memdef]p2). For example:
10111           //
10112           // class X {
10113           //   void f() const;
10114           // };
10115           //
10116           // void X::f() { } // ill-formed
10117           //
10118           // Complain about this problem, and attempt to suggest close
10119           // matches (e.g., those that differ only in cv-qualifiers and
10120           // whether the parameter types are references).
10121 
10122           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10123                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10124             AddToScope = ExtraArgs.AddToScope;
10125             return Result;
10126           }
10127         }
10128 
10129         // Unqualified local friend declarations are required to resolve
10130         // to something.
10131       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10132         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10133                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10134           AddToScope = ExtraArgs.AddToScope;
10135           return Result;
10136         }
10137       }
10138     } else if (!D.isFunctionDefinition() &&
10139                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10140                !isFriend && !isFunctionTemplateSpecialization &&
10141                !isMemberSpecialization) {
10142       // An out-of-line member function declaration must also be a
10143       // definition (C++ [class.mfct]p2).
10144       // Note that this is not the case for explicit specializations of
10145       // function templates or member functions of class templates, per
10146       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10147       // extension for compatibility with old SWIG code which likes to
10148       // generate them.
10149       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10150         << D.getCXXScopeSpec().getRange();
10151     }
10152   }
10153 
10154   // If this is the first declaration of a library builtin function, add
10155   // attributes as appropriate.
10156   if (!D.isRedeclaration()) {
10157     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10158       if (unsigned BuiltinID = II->getBuiltinID()) {
10159         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10160         if (!InStdNamespace &&
10161             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10162           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10163             // Validate the type matches unless this builtin is specified as
10164             // matching regardless of its declared type.
10165             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10166               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10167             } else {
10168               ASTContext::GetBuiltinTypeError Error;
10169               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10170               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10171 
10172               if (!Error && !BuiltinType.isNull() &&
10173                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10174                       NewFD->getType(), BuiltinType))
10175                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10176             }
10177           }
10178         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10179                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10180           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10181         }
10182       }
10183     }
10184   }
10185 
10186   ProcessPragmaWeak(S, NewFD);
10187   checkAttributesAfterMerging(*this, *NewFD);
10188 
10189   AddKnownFunctionAttributes(NewFD);
10190 
10191   if (NewFD->hasAttr<OverloadableAttr>() &&
10192       !NewFD->getType()->getAs<FunctionProtoType>()) {
10193     Diag(NewFD->getLocation(),
10194          diag::err_attribute_overloadable_no_prototype)
10195       << NewFD;
10196 
10197     // Turn this into a variadic function with no parameters.
10198     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10199     FunctionProtoType::ExtProtoInfo EPI(
10200         Context.getDefaultCallingConvention(true, false));
10201     EPI.Variadic = true;
10202     EPI.ExtInfo = FT->getExtInfo();
10203 
10204     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10205     NewFD->setType(R);
10206   }
10207 
10208   // If there's a #pragma GCC visibility in scope, and this isn't a class
10209   // member, set the visibility of this function.
10210   if (!DC->isRecord() && NewFD->isExternallyVisible())
10211     AddPushedVisibilityAttribute(NewFD);
10212 
10213   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10214   // marking the function.
10215   AddCFAuditedAttribute(NewFD);
10216 
10217   // If this is a function definition, check if we have to apply any
10218   // attributes (i.e. optnone and no_builtin) due to a pragma.
10219   if (D.isFunctionDefinition()) {
10220     AddRangeBasedOptnone(NewFD);
10221     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10222     AddSectionMSAllocText(NewFD);
10223   }
10224 
10225   // If this is the first declaration of an extern C variable, update
10226   // the map of such variables.
10227   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10228       isIncompleteDeclExternC(*this, NewFD))
10229     RegisterLocallyScopedExternCDecl(NewFD, S);
10230 
10231   // Set this FunctionDecl's range up to the right paren.
10232   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10233 
10234   if (D.isRedeclaration() && !Previous.empty()) {
10235     NamedDecl *Prev = Previous.getRepresentativeDecl();
10236     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10237                                    isMemberSpecialization ||
10238                                        isFunctionTemplateSpecialization,
10239                                    D.isFunctionDefinition());
10240   }
10241 
10242   if (getLangOpts().CUDA) {
10243     IdentifierInfo *II = NewFD->getIdentifier();
10244     if (II && II->isStr(getCudaConfigureFuncName()) &&
10245         !NewFD->isInvalidDecl() &&
10246         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10247       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10248         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10249             << getCudaConfigureFuncName();
10250       Context.setcudaConfigureCallDecl(NewFD);
10251     }
10252 
10253     // Variadic functions, other than a *declaration* of printf, are not allowed
10254     // in device-side CUDA code, unless someone passed
10255     // -fcuda-allow-variadic-functions.
10256     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10257         (NewFD->hasAttr<CUDADeviceAttr>() ||
10258          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10259         !(II && II->isStr("printf") && NewFD->isExternC() &&
10260           !D.isFunctionDefinition())) {
10261       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10262     }
10263   }
10264 
10265   MarkUnusedFileScopedDecl(NewFD);
10266 
10267 
10268 
10269   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10270     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10271     if (SC == SC_Static) {
10272       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10273       D.setInvalidType();
10274     }
10275 
10276     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10277     if (!NewFD->getReturnType()->isVoidType()) {
10278       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10279       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10280           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10281                                 : FixItHint());
10282       D.setInvalidType();
10283     }
10284 
10285     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10286     for (auto Param : NewFD->parameters())
10287       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10288 
10289     if (getLangOpts().OpenCLCPlusPlus) {
10290       if (DC->isRecord()) {
10291         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10292         D.setInvalidType();
10293       }
10294       if (FunctionTemplate) {
10295         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10296         D.setInvalidType();
10297       }
10298     }
10299   }
10300 
10301   if (getLangOpts().CPlusPlus) {
10302     if (FunctionTemplate) {
10303       if (NewFD->isInvalidDecl())
10304         FunctionTemplate->setInvalidDecl();
10305       return FunctionTemplate;
10306     }
10307 
10308     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10309       CompleteMemberSpecialization(NewFD, Previous);
10310   }
10311 
10312   for (const ParmVarDecl *Param : NewFD->parameters()) {
10313     QualType PT = Param->getType();
10314 
10315     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10316     // types.
10317     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10318       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10319         QualType ElemTy = PipeTy->getElementType();
10320           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10321             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10322             D.setInvalidType();
10323           }
10324       }
10325     }
10326   }
10327 
10328   // Here we have an function template explicit specialization at class scope.
10329   // The actual specialization will be postponed to template instatiation
10330   // time via the ClassScopeFunctionSpecializationDecl node.
10331   if (isDependentClassScopeExplicitSpecialization) {
10332     ClassScopeFunctionSpecializationDecl *NewSpec =
10333                          ClassScopeFunctionSpecializationDecl::Create(
10334                                 Context, CurContext, NewFD->getLocation(),
10335                                 cast<CXXMethodDecl>(NewFD),
10336                                 HasExplicitTemplateArgs, TemplateArgs);
10337     CurContext->addDecl(NewSpec);
10338     AddToScope = false;
10339   }
10340 
10341   // Diagnose availability attributes. Availability cannot be used on functions
10342   // that are run during load/unload.
10343   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10344     if (NewFD->hasAttr<ConstructorAttr>()) {
10345       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10346           << 1;
10347       NewFD->dropAttr<AvailabilityAttr>();
10348     }
10349     if (NewFD->hasAttr<DestructorAttr>()) {
10350       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10351           << 2;
10352       NewFD->dropAttr<AvailabilityAttr>();
10353     }
10354   }
10355 
10356   // Diagnose no_builtin attribute on function declaration that are not a
10357   // definition.
10358   // FIXME: We should really be doing this in
10359   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10360   // the FunctionDecl and at this point of the code
10361   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10362   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10363   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10364     switch (D.getFunctionDefinitionKind()) {
10365     case FunctionDefinitionKind::Defaulted:
10366     case FunctionDefinitionKind::Deleted:
10367       Diag(NBA->getLocation(),
10368            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10369           << NBA->getSpelling();
10370       break;
10371     case FunctionDefinitionKind::Declaration:
10372       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10373           << NBA->getSpelling();
10374       break;
10375     case FunctionDefinitionKind::Definition:
10376       break;
10377     }
10378 
10379   return NewFD;
10380 }
10381 
10382 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10383 /// when __declspec(code_seg) "is applied to a class, all member functions of
10384 /// the class and nested classes -- this includes compiler-generated special
10385 /// member functions -- are put in the specified segment."
10386 /// The actual behavior is a little more complicated. The Microsoft compiler
10387 /// won't check outer classes if there is an active value from #pragma code_seg.
10388 /// The CodeSeg is always applied from the direct parent but only from outer
10389 /// classes when the #pragma code_seg stack is empty. See:
10390 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10391 /// available since MS has removed the page.
10392 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10393   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10394   if (!Method)
10395     return nullptr;
10396   const CXXRecordDecl *Parent = Method->getParent();
10397   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10398     Attr *NewAttr = SAttr->clone(S.getASTContext());
10399     NewAttr->setImplicit(true);
10400     return NewAttr;
10401   }
10402 
10403   // The Microsoft compiler won't check outer classes for the CodeSeg
10404   // when the #pragma code_seg stack is active.
10405   if (S.CodeSegStack.CurrentValue)
10406    return nullptr;
10407 
10408   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10409     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10410       Attr *NewAttr = SAttr->clone(S.getASTContext());
10411       NewAttr->setImplicit(true);
10412       return NewAttr;
10413     }
10414   }
10415   return nullptr;
10416 }
10417 
10418 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10419 /// containing class. Otherwise it will return implicit SectionAttr if the
10420 /// function is a definition and there is an active value on CodeSegStack
10421 /// (from the current #pragma code-seg value).
10422 ///
10423 /// \param FD Function being declared.
10424 /// \param IsDefinition Whether it is a definition or just a declarartion.
10425 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10426 ///          nullptr if no attribute should be added.
10427 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10428                                                        bool IsDefinition) {
10429   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10430     return A;
10431   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10432       CodeSegStack.CurrentValue)
10433     return SectionAttr::CreateImplicit(
10434         getASTContext(), CodeSegStack.CurrentValue->getString(),
10435         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10436         SectionAttr::Declspec_allocate);
10437   return nullptr;
10438 }
10439 
10440 /// Determines if we can perform a correct type check for \p D as a
10441 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10442 /// best-effort check.
10443 ///
10444 /// \param NewD The new declaration.
10445 /// \param OldD The old declaration.
10446 /// \param NewT The portion of the type of the new declaration to check.
10447 /// \param OldT The portion of the type of the old declaration to check.
10448 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10449                                           QualType NewT, QualType OldT) {
10450   if (!NewD->getLexicalDeclContext()->isDependentContext())
10451     return true;
10452 
10453   // For dependently-typed local extern declarations and friends, we can't
10454   // perform a correct type check in general until instantiation:
10455   //
10456   //   int f();
10457   //   template<typename T> void g() { T f(); }
10458   //
10459   // (valid if g() is only instantiated with T = int).
10460   if (NewT->isDependentType() &&
10461       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10462     return false;
10463 
10464   // Similarly, if the previous declaration was a dependent local extern
10465   // declaration, we don't really know its type yet.
10466   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10467     return false;
10468 
10469   return true;
10470 }
10471 
10472 /// Checks if the new declaration declared in dependent context must be
10473 /// put in the same redeclaration chain as the specified declaration.
10474 ///
10475 /// \param D Declaration that is checked.
10476 /// \param PrevDecl Previous declaration found with proper lookup method for the
10477 ///                 same declaration name.
10478 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10479 ///          belongs to.
10480 ///
10481 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10482   if (!D->getLexicalDeclContext()->isDependentContext())
10483     return true;
10484 
10485   // Don't chain dependent friend function definitions until instantiation, to
10486   // permit cases like
10487   //
10488   //   void func();
10489   //   template<typename T> class C1 { friend void func() {} };
10490   //   template<typename T> class C2 { friend void func() {} };
10491   //
10492   // ... which is valid if only one of C1 and C2 is ever instantiated.
10493   //
10494   // FIXME: This need only apply to function definitions. For now, we proxy
10495   // this by checking for a file-scope function. We do not want this to apply
10496   // to friend declarations nominating member functions, because that gets in
10497   // the way of access checks.
10498   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10499     return false;
10500 
10501   auto *VD = dyn_cast<ValueDecl>(D);
10502   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10503   return !VD || !PrevVD ||
10504          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10505                                         PrevVD->getType());
10506 }
10507 
10508 /// Check the target attribute of the function for MultiVersion
10509 /// validity.
10510 ///
10511 /// Returns true if there was an error, false otherwise.
10512 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10513   const auto *TA = FD->getAttr<TargetAttr>();
10514   assert(TA && "MultiVersion Candidate requires a target attribute");
10515   ParsedTargetAttr ParseInfo = TA->parse();
10516   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10517   enum ErrType { Feature = 0, Architecture = 1 };
10518 
10519   if (!ParseInfo.Architecture.empty() &&
10520       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10521     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10522         << Architecture << ParseInfo.Architecture;
10523     return true;
10524   }
10525 
10526   for (const auto &Feat : ParseInfo.Features) {
10527     auto BareFeat = StringRef{Feat}.substr(1);
10528     if (Feat[0] == '-') {
10529       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10530           << Feature << ("no-" + BareFeat).str();
10531       return true;
10532     }
10533 
10534     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10535         !TargetInfo.isValidFeatureName(BareFeat)) {
10536       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10537           << Feature << BareFeat;
10538       return true;
10539     }
10540   }
10541   return false;
10542 }
10543 
10544 // Provide a white-list of attributes that are allowed to be combined with
10545 // multiversion functions.
10546 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10547                                            MultiVersionKind MVKind) {
10548   // Note: this list/diagnosis must match the list in
10549   // checkMultiversionAttributesAllSame.
10550   switch (Kind) {
10551   default:
10552     return false;
10553   case attr::Used:
10554     return MVKind == MultiVersionKind::Target;
10555   case attr::NonNull:
10556   case attr::NoThrow:
10557     return true;
10558   }
10559 }
10560 
10561 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10562                                                  const FunctionDecl *FD,
10563                                                  const FunctionDecl *CausedFD,
10564                                                  MultiVersionKind MVKind) {
10565   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10566     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10567         << static_cast<unsigned>(MVKind) << A;
10568     if (CausedFD)
10569       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10570     return true;
10571   };
10572 
10573   for (const Attr *A : FD->attrs()) {
10574     switch (A->getKind()) {
10575     case attr::CPUDispatch:
10576     case attr::CPUSpecific:
10577       if (MVKind != MultiVersionKind::CPUDispatch &&
10578           MVKind != MultiVersionKind::CPUSpecific)
10579         return Diagnose(S, A);
10580       break;
10581     case attr::Target:
10582       if (MVKind != MultiVersionKind::Target)
10583         return Diagnose(S, A);
10584       break;
10585     case attr::TargetClones:
10586       if (MVKind != MultiVersionKind::TargetClones)
10587         return Diagnose(S, A);
10588       break;
10589     default:
10590       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10591         return Diagnose(S, A);
10592       break;
10593     }
10594   }
10595   return false;
10596 }
10597 
10598 bool Sema::areMultiversionVariantFunctionsCompatible(
10599     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10600     const PartialDiagnostic &NoProtoDiagID,
10601     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10602     const PartialDiagnosticAt &NoSupportDiagIDAt,
10603     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10604     bool ConstexprSupported, bool CLinkageMayDiffer) {
10605   enum DoesntSupport {
10606     FuncTemplates = 0,
10607     VirtFuncs = 1,
10608     DeducedReturn = 2,
10609     Constructors = 3,
10610     Destructors = 4,
10611     DeletedFuncs = 5,
10612     DefaultedFuncs = 6,
10613     ConstexprFuncs = 7,
10614     ConstevalFuncs = 8,
10615     Lambda = 9,
10616   };
10617   enum Different {
10618     CallingConv = 0,
10619     ReturnType = 1,
10620     ConstexprSpec = 2,
10621     InlineSpec = 3,
10622     Linkage = 4,
10623     LanguageLinkage = 5,
10624   };
10625 
10626   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10627       !OldFD->getType()->getAs<FunctionProtoType>()) {
10628     Diag(OldFD->getLocation(), NoProtoDiagID);
10629     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10630     return true;
10631   }
10632 
10633   if (NoProtoDiagID.getDiagID() != 0 &&
10634       !NewFD->getType()->getAs<FunctionProtoType>())
10635     return Diag(NewFD->getLocation(), NoProtoDiagID);
10636 
10637   if (!TemplatesSupported &&
10638       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10639     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10640            << FuncTemplates;
10641 
10642   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10643     if (NewCXXFD->isVirtual())
10644       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10645              << VirtFuncs;
10646 
10647     if (isa<CXXConstructorDecl>(NewCXXFD))
10648       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10649              << Constructors;
10650 
10651     if (isa<CXXDestructorDecl>(NewCXXFD))
10652       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10653              << Destructors;
10654   }
10655 
10656   if (NewFD->isDeleted())
10657     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10658            << DeletedFuncs;
10659 
10660   if (NewFD->isDefaulted())
10661     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10662            << DefaultedFuncs;
10663 
10664   if (!ConstexprSupported && NewFD->isConstexpr())
10665     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10666            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10667 
10668   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10669   const auto *NewType = cast<FunctionType>(NewQType);
10670   QualType NewReturnType = NewType->getReturnType();
10671 
10672   if (NewReturnType->isUndeducedType())
10673     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10674            << DeducedReturn;
10675 
10676   // Ensure the return type is identical.
10677   if (OldFD) {
10678     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10679     const auto *OldType = cast<FunctionType>(OldQType);
10680     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10681     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10682 
10683     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10684       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10685 
10686     QualType OldReturnType = OldType->getReturnType();
10687 
10688     if (OldReturnType != NewReturnType)
10689       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10690 
10691     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10692       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10693 
10694     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10695       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10696 
10697     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10698       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10699 
10700     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10701       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10702 
10703     if (CheckEquivalentExceptionSpec(
10704             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10705             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10706       return true;
10707   }
10708   return false;
10709 }
10710 
10711 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10712                                              const FunctionDecl *NewFD,
10713                                              bool CausesMV,
10714                                              MultiVersionKind MVKind) {
10715   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10716     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10717     if (OldFD)
10718       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10719     return true;
10720   }
10721 
10722   bool IsCPUSpecificCPUDispatchMVKind =
10723       MVKind == MultiVersionKind::CPUDispatch ||
10724       MVKind == MultiVersionKind::CPUSpecific;
10725 
10726   if (CausesMV && OldFD &&
10727       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10728     return true;
10729 
10730   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10731     return true;
10732 
10733   // Only allow transition to MultiVersion if it hasn't been used.
10734   if (OldFD && CausesMV && OldFD->isUsed(false))
10735     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10736 
10737   return S.areMultiversionVariantFunctionsCompatible(
10738       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10739       PartialDiagnosticAt(NewFD->getLocation(),
10740                           S.PDiag(diag::note_multiversioning_caused_here)),
10741       PartialDiagnosticAt(NewFD->getLocation(),
10742                           S.PDiag(diag::err_multiversion_doesnt_support)
10743                               << static_cast<unsigned>(MVKind)),
10744       PartialDiagnosticAt(NewFD->getLocation(),
10745                           S.PDiag(diag::err_multiversion_diff)),
10746       /*TemplatesSupported=*/false,
10747       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10748       /*CLinkageMayDiffer=*/false);
10749 }
10750 
10751 /// Check the validity of a multiversion function declaration that is the
10752 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10753 ///
10754 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10755 ///
10756 /// Returns true if there was an error, false otherwise.
10757 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10758                                            MultiVersionKind MVKind,
10759                                            const TargetAttr *TA) {
10760   assert(MVKind != MultiVersionKind::None &&
10761          "Function lacks multiversion attribute");
10762 
10763   // Target only causes MV if it is default, otherwise this is a normal
10764   // function.
10765   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10766     return false;
10767 
10768   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10769     FD->setInvalidDecl();
10770     return true;
10771   }
10772 
10773   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10774     FD->setInvalidDecl();
10775     return true;
10776   }
10777 
10778   FD->setIsMultiVersion();
10779   return false;
10780 }
10781 
10782 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10783   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10784     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10785       return true;
10786   }
10787 
10788   return false;
10789 }
10790 
10791 static bool CheckTargetCausesMultiVersioning(
10792     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10793     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10794   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10795   ParsedTargetAttr NewParsed = NewTA->parse();
10796   // Sort order doesn't matter, it just needs to be consistent.
10797   llvm::sort(NewParsed.Features);
10798 
10799   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10800   // to change, this is a simple redeclaration.
10801   if (!NewTA->isDefaultVersion() &&
10802       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10803     return false;
10804 
10805   // Otherwise, this decl causes MultiVersioning.
10806   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10807                                        MultiVersionKind::Target)) {
10808     NewFD->setInvalidDecl();
10809     return true;
10810   }
10811 
10812   if (CheckMultiVersionValue(S, NewFD)) {
10813     NewFD->setInvalidDecl();
10814     return true;
10815   }
10816 
10817   // If this is 'default', permit the forward declaration.
10818   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10819     Redeclaration = true;
10820     OldDecl = OldFD;
10821     OldFD->setIsMultiVersion();
10822     NewFD->setIsMultiVersion();
10823     return false;
10824   }
10825 
10826   if (CheckMultiVersionValue(S, OldFD)) {
10827     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10828     NewFD->setInvalidDecl();
10829     return true;
10830   }
10831 
10832   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10833 
10834   if (OldParsed == NewParsed) {
10835     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10836     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10837     NewFD->setInvalidDecl();
10838     return true;
10839   }
10840 
10841   for (const auto *FD : OldFD->redecls()) {
10842     const auto *CurTA = FD->getAttr<TargetAttr>();
10843     // We allow forward declarations before ANY multiversioning attributes, but
10844     // nothing after the fact.
10845     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10846         (!CurTA || CurTA->isInherited())) {
10847       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10848           << 0;
10849       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10850       NewFD->setInvalidDecl();
10851       return true;
10852     }
10853   }
10854 
10855   OldFD->setIsMultiVersion();
10856   NewFD->setIsMultiVersion();
10857   Redeclaration = false;
10858   OldDecl = nullptr;
10859   Previous.clear();
10860   return false;
10861 }
10862 
10863 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10864                                         MultiVersionKind New) {
10865   if (Old == New || Old == MultiVersionKind::None ||
10866       New == MultiVersionKind::None)
10867     return true;
10868 
10869   return (Old == MultiVersionKind::CPUDispatch &&
10870           New == MultiVersionKind::CPUSpecific) ||
10871          (Old == MultiVersionKind::CPUSpecific &&
10872           New == MultiVersionKind::CPUDispatch);
10873 }
10874 
10875 /// Check the validity of a new function declaration being added to an existing
10876 /// multiversioned declaration collection.
10877 static bool CheckMultiVersionAdditionalDecl(
10878     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10879     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10880     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10881     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10882     LookupResult &Previous) {
10883 
10884   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10885   // Disallow mixing of multiversioning types.
10886   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10887     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10888     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10889     NewFD->setInvalidDecl();
10890     return true;
10891   }
10892 
10893   ParsedTargetAttr NewParsed;
10894   if (NewTA) {
10895     NewParsed = NewTA->parse();
10896     llvm::sort(NewParsed.Features);
10897   }
10898 
10899   bool UseMemberUsingDeclRules =
10900       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10901 
10902   bool MayNeedOverloadableChecks =
10903       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10904 
10905   // Next, check ALL non-overloads to see if this is a redeclaration of a
10906   // previous member of the MultiVersion set.
10907   for (NamedDecl *ND : Previous) {
10908     FunctionDecl *CurFD = ND->getAsFunction();
10909     if (!CurFD)
10910       continue;
10911     if (MayNeedOverloadableChecks &&
10912         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10913       continue;
10914 
10915     switch (NewMVKind) {
10916     case MultiVersionKind::None:
10917       assert(OldMVKind == MultiVersionKind::TargetClones &&
10918              "Only target_clones can be omitted in subsequent declarations");
10919       break;
10920     case MultiVersionKind::Target: {
10921       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10922       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10923         NewFD->setIsMultiVersion();
10924         Redeclaration = true;
10925         OldDecl = ND;
10926         return false;
10927       }
10928 
10929       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10930       if (CurParsed == NewParsed) {
10931         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10932         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10933         NewFD->setInvalidDecl();
10934         return true;
10935       }
10936       break;
10937     }
10938     case MultiVersionKind::TargetClones: {
10939       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10940       Redeclaration = true;
10941       OldDecl = CurFD;
10942       NewFD->setIsMultiVersion();
10943 
10944       if (CurClones && NewClones &&
10945           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10946            !std::equal(CurClones->featuresStrs_begin(),
10947                        CurClones->featuresStrs_end(),
10948                        NewClones->featuresStrs_begin()))) {
10949         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10950         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10951         NewFD->setInvalidDecl();
10952         return true;
10953       }
10954 
10955       return false;
10956     }
10957     case MultiVersionKind::CPUSpecific:
10958     case MultiVersionKind::CPUDispatch: {
10959       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10960       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10961       // Handle CPUDispatch/CPUSpecific versions.
10962       // Only 1 CPUDispatch function is allowed, this will make it go through
10963       // the redeclaration errors.
10964       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10965           CurFD->hasAttr<CPUDispatchAttr>()) {
10966         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10967             std::equal(
10968                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10969                 NewCPUDisp->cpus_begin(),
10970                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10971                   return Cur->getName() == New->getName();
10972                 })) {
10973           NewFD->setIsMultiVersion();
10974           Redeclaration = true;
10975           OldDecl = ND;
10976           return false;
10977         }
10978 
10979         // If the declarations don't match, this is an error condition.
10980         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10981         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10982         NewFD->setInvalidDecl();
10983         return true;
10984       }
10985       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10986         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10987             std::equal(
10988                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10989                 NewCPUSpec->cpus_begin(),
10990                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10991                   return Cur->getName() == New->getName();
10992                 })) {
10993           NewFD->setIsMultiVersion();
10994           Redeclaration = true;
10995           OldDecl = ND;
10996           return false;
10997         }
10998 
10999         // Only 1 version of CPUSpecific is allowed for each CPU.
11000         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11001           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11002             if (CurII == NewII) {
11003               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11004                   << NewII;
11005               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11006               NewFD->setInvalidDecl();
11007               return true;
11008             }
11009           }
11010         }
11011       }
11012       break;
11013     }
11014     }
11015   }
11016 
11017   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11018   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11019   // handled in the attribute adding step.
11020   if (NewMVKind == MultiVersionKind::Target &&
11021       CheckMultiVersionValue(S, NewFD)) {
11022     NewFD->setInvalidDecl();
11023     return true;
11024   }
11025 
11026   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11027                                        !OldFD->isMultiVersion(), NewMVKind)) {
11028     NewFD->setInvalidDecl();
11029     return true;
11030   }
11031 
11032   // Permit forward declarations in the case where these two are compatible.
11033   if (!OldFD->isMultiVersion()) {
11034     OldFD->setIsMultiVersion();
11035     NewFD->setIsMultiVersion();
11036     Redeclaration = true;
11037     OldDecl = OldFD;
11038     return false;
11039   }
11040 
11041   NewFD->setIsMultiVersion();
11042   Redeclaration = false;
11043   OldDecl = nullptr;
11044   Previous.clear();
11045   return false;
11046 }
11047 
11048 /// Check the validity of a mulitversion function declaration.
11049 /// Also sets the multiversion'ness' of the function itself.
11050 ///
11051 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11052 ///
11053 /// Returns true if there was an error, false otherwise.
11054 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11055                                       bool &Redeclaration, NamedDecl *&OldDecl,
11056                                       LookupResult &Previous) {
11057   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11058   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11059   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11060   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11061   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11062 
11063   // Main isn't allowed to become a multiversion function, however it IS
11064   // permitted to have 'main' be marked with the 'target' optimization hint.
11065   if (NewFD->isMain()) {
11066     if (MVKind != MultiVersionKind::None &&
11067         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11068       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11069       NewFD->setInvalidDecl();
11070       return true;
11071     }
11072     return false;
11073   }
11074 
11075   if (!OldDecl || !OldDecl->getAsFunction() ||
11076       OldDecl->getDeclContext()->getRedeclContext() !=
11077           NewFD->getDeclContext()->getRedeclContext()) {
11078     // If there's no previous declaration, AND this isn't attempting to cause
11079     // multiversioning, this isn't an error condition.
11080     if (MVKind == MultiVersionKind::None)
11081       return false;
11082     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11083   }
11084 
11085   FunctionDecl *OldFD = OldDecl->getAsFunction();
11086 
11087   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11088     return false;
11089 
11090   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11091   // for target_clones.
11092   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11093       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11094     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11095         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11096     NewFD->setInvalidDecl();
11097     return true;
11098   }
11099 
11100   if (!OldFD->isMultiVersion()) {
11101     switch (MVKind) {
11102     case MultiVersionKind::Target:
11103       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11104                                               Redeclaration, OldDecl, Previous);
11105     case MultiVersionKind::TargetClones:
11106       if (OldFD->isUsed(false)) {
11107         NewFD->setInvalidDecl();
11108         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11109       }
11110       OldFD->setIsMultiVersion();
11111       break;
11112     case MultiVersionKind::CPUDispatch:
11113     case MultiVersionKind::CPUSpecific:
11114     case MultiVersionKind::None:
11115       break;
11116     }
11117   }
11118 
11119   // At this point, we have a multiversion function decl (in OldFD) AND an
11120   // appropriate attribute in the current function decl.  Resolve that these are
11121   // still compatible with previous declarations.
11122   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11123                                          NewCPUDisp, NewCPUSpec, NewClones,
11124                                          Redeclaration, OldDecl, Previous);
11125 }
11126 
11127 /// Perform semantic checking of a new function declaration.
11128 ///
11129 /// Performs semantic analysis of the new function declaration
11130 /// NewFD. This routine performs all semantic checking that does not
11131 /// require the actual declarator involved in the declaration, and is
11132 /// used both for the declaration of functions as they are parsed
11133 /// (called via ActOnDeclarator) and for the declaration of functions
11134 /// that have been instantiated via C++ template instantiation (called
11135 /// via InstantiateDecl).
11136 ///
11137 /// \param IsMemberSpecialization whether this new function declaration is
11138 /// a member specialization (that replaces any definition provided by the
11139 /// previous declaration).
11140 ///
11141 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11142 ///
11143 /// \returns true if the function declaration is a redeclaration.
11144 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11145                                     LookupResult &Previous,
11146                                     bool IsMemberSpecialization,
11147                                     bool DeclIsDefn) {
11148   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11149          "Variably modified return types are not handled here");
11150 
11151   // Determine whether the type of this function should be merged with
11152   // a previous visible declaration. This never happens for functions in C++,
11153   // and always happens in C if the previous declaration was visible.
11154   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11155                                !Previous.isShadowed();
11156 
11157   bool Redeclaration = false;
11158   NamedDecl *OldDecl = nullptr;
11159   bool MayNeedOverloadableChecks = false;
11160 
11161   // Merge or overload the declaration with an existing declaration of
11162   // the same name, if appropriate.
11163   if (!Previous.empty()) {
11164     // Determine whether NewFD is an overload of PrevDecl or
11165     // a declaration that requires merging. If it's an overload,
11166     // there's no more work to do here; we'll just add the new
11167     // function to the scope.
11168     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11169       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11170       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11171         Redeclaration = true;
11172         OldDecl = Candidate;
11173       }
11174     } else {
11175       MayNeedOverloadableChecks = true;
11176       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11177                             /*NewIsUsingDecl*/ false)) {
11178       case Ovl_Match:
11179         Redeclaration = true;
11180         break;
11181 
11182       case Ovl_NonFunction:
11183         Redeclaration = true;
11184         break;
11185 
11186       case Ovl_Overload:
11187         Redeclaration = false;
11188         break;
11189       }
11190     }
11191   }
11192 
11193   // Check for a previous extern "C" declaration with this name.
11194   if (!Redeclaration &&
11195       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11196     if (!Previous.empty()) {
11197       // This is an extern "C" declaration with the same name as a previous
11198       // declaration, and thus redeclares that entity...
11199       Redeclaration = true;
11200       OldDecl = Previous.getFoundDecl();
11201       MergeTypeWithPrevious = false;
11202 
11203       // ... except in the presence of __attribute__((overloadable)).
11204       if (OldDecl->hasAttr<OverloadableAttr>() ||
11205           NewFD->hasAttr<OverloadableAttr>()) {
11206         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11207           MayNeedOverloadableChecks = true;
11208           Redeclaration = false;
11209           OldDecl = nullptr;
11210         }
11211       }
11212     }
11213   }
11214 
11215   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11216     return Redeclaration;
11217 
11218   // PPC MMA non-pointer types are not allowed as function return types.
11219   if (Context.getTargetInfo().getTriple().isPPC64() &&
11220       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11221     NewFD->setInvalidDecl();
11222   }
11223 
11224   // C++11 [dcl.constexpr]p8:
11225   //   A constexpr specifier for a non-static member function that is not
11226   //   a constructor declares that member function to be const.
11227   //
11228   // This needs to be delayed until we know whether this is an out-of-line
11229   // definition of a static member function.
11230   //
11231   // This rule is not present in C++1y, so we produce a backwards
11232   // compatibility warning whenever it happens in C++11.
11233   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11234   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11235       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11236       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11237     CXXMethodDecl *OldMD = nullptr;
11238     if (OldDecl)
11239       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11240     if (!OldMD || !OldMD->isStatic()) {
11241       const FunctionProtoType *FPT =
11242         MD->getType()->castAs<FunctionProtoType>();
11243       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11244       EPI.TypeQuals.addConst();
11245       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11246                                           FPT->getParamTypes(), EPI));
11247 
11248       // Warn that we did this, if we're not performing template instantiation.
11249       // In that case, we'll have warned already when the template was defined.
11250       if (!inTemplateInstantiation()) {
11251         SourceLocation AddConstLoc;
11252         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11253                 .IgnoreParens().getAs<FunctionTypeLoc>())
11254           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11255 
11256         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11257           << FixItHint::CreateInsertion(AddConstLoc, " const");
11258       }
11259     }
11260   }
11261 
11262   if (Redeclaration) {
11263     // NewFD and OldDecl represent declarations that need to be
11264     // merged.
11265     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11266                           DeclIsDefn)) {
11267       NewFD->setInvalidDecl();
11268       return Redeclaration;
11269     }
11270 
11271     Previous.clear();
11272     Previous.addDecl(OldDecl);
11273 
11274     if (FunctionTemplateDecl *OldTemplateDecl =
11275             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11276       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11277       FunctionTemplateDecl *NewTemplateDecl
11278         = NewFD->getDescribedFunctionTemplate();
11279       assert(NewTemplateDecl && "Template/non-template mismatch");
11280 
11281       // The call to MergeFunctionDecl above may have created some state in
11282       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11283       // can add it as a redeclaration.
11284       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11285 
11286       NewFD->setPreviousDeclaration(OldFD);
11287       if (NewFD->isCXXClassMember()) {
11288         NewFD->setAccess(OldTemplateDecl->getAccess());
11289         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11290       }
11291 
11292       // If this is an explicit specialization of a member that is a function
11293       // template, mark it as a member specialization.
11294       if (IsMemberSpecialization &&
11295           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11296         NewTemplateDecl->setMemberSpecialization();
11297         assert(OldTemplateDecl->isMemberSpecialization());
11298         // Explicit specializations of a member template do not inherit deleted
11299         // status from the parent member template that they are specializing.
11300         if (OldFD->isDeleted()) {
11301           // FIXME: This assert will not hold in the presence of modules.
11302           assert(OldFD->getCanonicalDecl() == OldFD);
11303           // FIXME: We need an update record for this AST mutation.
11304           OldFD->setDeletedAsWritten(false);
11305         }
11306       }
11307 
11308     } else {
11309       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11310         auto *OldFD = cast<FunctionDecl>(OldDecl);
11311         // This needs to happen first so that 'inline' propagates.
11312         NewFD->setPreviousDeclaration(OldFD);
11313         if (NewFD->isCXXClassMember())
11314           NewFD->setAccess(OldFD->getAccess());
11315       }
11316     }
11317   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11318              !NewFD->getAttr<OverloadableAttr>()) {
11319     assert((Previous.empty() ||
11320             llvm::any_of(Previous,
11321                          [](const NamedDecl *ND) {
11322                            return ND->hasAttr<OverloadableAttr>();
11323                          })) &&
11324            "Non-redecls shouldn't happen without overloadable present");
11325 
11326     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11327       const auto *FD = dyn_cast<FunctionDecl>(ND);
11328       return FD && !FD->hasAttr<OverloadableAttr>();
11329     });
11330 
11331     if (OtherUnmarkedIter != Previous.end()) {
11332       Diag(NewFD->getLocation(),
11333            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11334       Diag((*OtherUnmarkedIter)->getLocation(),
11335            diag::note_attribute_overloadable_prev_overload)
11336           << false;
11337 
11338       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11339     }
11340   }
11341 
11342   if (LangOpts.OpenMP)
11343     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11344 
11345   // Semantic checking for this function declaration (in isolation).
11346 
11347   if (getLangOpts().CPlusPlus) {
11348     // C++-specific checks.
11349     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11350       CheckConstructor(Constructor);
11351     } else if (CXXDestructorDecl *Destructor =
11352                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11353       CXXRecordDecl *Record = Destructor->getParent();
11354       QualType ClassType = Context.getTypeDeclType(Record);
11355 
11356       // FIXME: Shouldn't we be able to perform this check even when the class
11357       // type is dependent? Both gcc and edg can handle that.
11358       if (!ClassType->isDependentType()) {
11359         DeclarationName Name
11360           = Context.DeclarationNames.getCXXDestructorName(
11361                                         Context.getCanonicalType(ClassType));
11362         if (NewFD->getDeclName() != Name) {
11363           Diag(NewFD->getLocation(), diag::err_destructor_name);
11364           NewFD->setInvalidDecl();
11365           return Redeclaration;
11366         }
11367       }
11368     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11369       if (auto *TD = Guide->getDescribedFunctionTemplate())
11370         CheckDeductionGuideTemplate(TD);
11371 
11372       // A deduction guide is not on the list of entities that can be
11373       // explicitly specialized.
11374       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11375         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11376             << /*explicit specialization*/ 1;
11377     }
11378 
11379     // Find any virtual functions that this function overrides.
11380     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11381       if (!Method->isFunctionTemplateSpecialization() &&
11382           !Method->getDescribedFunctionTemplate() &&
11383           Method->isCanonicalDecl()) {
11384         AddOverriddenMethods(Method->getParent(), Method);
11385       }
11386       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11387         // C++2a [class.virtual]p6
11388         // A virtual method shall not have a requires-clause.
11389         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11390              diag::err_constrained_virtual_method);
11391 
11392       if (Method->isStatic())
11393         checkThisInStaticMemberFunctionType(Method);
11394     }
11395 
11396     // C++20: dcl.decl.general p4:
11397     // The optional requires-clause ([temp.pre]) in an init-declarator or
11398     // member-declarator shall be present only if the declarator declares a
11399     // templated function ([dcl.fct]).
11400     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11401       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11402         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11403     }
11404 
11405     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11406       ActOnConversionDeclarator(Conversion);
11407 
11408     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11409     if (NewFD->isOverloadedOperator() &&
11410         CheckOverloadedOperatorDeclaration(NewFD)) {
11411       NewFD->setInvalidDecl();
11412       return Redeclaration;
11413     }
11414 
11415     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11416     if (NewFD->getLiteralIdentifier() &&
11417         CheckLiteralOperatorDeclaration(NewFD)) {
11418       NewFD->setInvalidDecl();
11419       return Redeclaration;
11420     }
11421 
11422     // In C++, check default arguments now that we have merged decls. Unless
11423     // the lexical context is the class, because in this case this is done
11424     // during delayed parsing anyway.
11425     if (!CurContext->isRecord())
11426       CheckCXXDefaultArguments(NewFD);
11427 
11428     // If this function is declared as being extern "C", then check to see if
11429     // the function returns a UDT (class, struct, or union type) that is not C
11430     // compatible, and if it does, warn the user.
11431     // But, issue any diagnostic on the first declaration only.
11432     if (Previous.empty() && NewFD->isExternC()) {
11433       QualType R = NewFD->getReturnType();
11434       if (R->isIncompleteType() && !R->isVoidType())
11435         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11436             << NewFD << R;
11437       else if (!R.isPODType(Context) && !R->isVoidType() &&
11438                !R->isObjCObjectPointerType())
11439         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11440     }
11441 
11442     // C++1z [dcl.fct]p6:
11443     //   [...] whether the function has a non-throwing exception-specification
11444     //   [is] part of the function type
11445     //
11446     // This results in an ABI break between C++14 and C++17 for functions whose
11447     // declared type includes an exception-specification in a parameter or
11448     // return type. (Exception specifications on the function itself are OK in
11449     // most cases, and exception specifications are not permitted in most other
11450     // contexts where they could make it into a mangling.)
11451     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11452       auto HasNoexcept = [&](QualType T) -> bool {
11453         // Strip off declarator chunks that could be between us and a function
11454         // type. We don't need to look far, exception specifications are very
11455         // restricted prior to C++17.
11456         if (auto *RT = T->getAs<ReferenceType>())
11457           T = RT->getPointeeType();
11458         else if (T->isAnyPointerType())
11459           T = T->getPointeeType();
11460         else if (auto *MPT = T->getAs<MemberPointerType>())
11461           T = MPT->getPointeeType();
11462         if (auto *FPT = T->getAs<FunctionProtoType>())
11463           if (FPT->isNothrow())
11464             return true;
11465         return false;
11466       };
11467 
11468       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11469       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11470       for (QualType T : FPT->param_types())
11471         AnyNoexcept |= HasNoexcept(T);
11472       if (AnyNoexcept)
11473         Diag(NewFD->getLocation(),
11474              diag::warn_cxx17_compat_exception_spec_in_signature)
11475             << NewFD;
11476     }
11477 
11478     if (!Redeclaration && LangOpts.CUDA)
11479       checkCUDATargetOverload(NewFD, Previous);
11480   }
11481   return Redeclaration;
11482 }
11483 
11484 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11485   // C++11 [basic.start.main]p3:
11486   //   A program that [...] declares main to be inline, static or
11487   //   constexpr is ill-formed.
11488   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11489   //   appear in a declaration of main.
11490   // static main is not an error under C99, but we should warn about it.
11491   // We accept _Noreturn main as an extension.
11492   if (FD->getStorageClass() == SC_Static)
11493     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11494          ? diag::err_static_main : diag::warn_static_main)
11495       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11496   if (FD->isInlineSpecified())
11497     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11498       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11499   if (DS.isNoreturnSpecified()) {
11500     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11501     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11502     Diag(NoreturnLoc, diag::ext_noreturn_main);
11503     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11504       << FixItHint::CreateRemoval(NoreturnRange);
11505   }
11506   if (FD->isConstexpr()) {
11507     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11508         << FD->isConsteval()
11509         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11510     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11511   }
11512 
11513   if (getLangOpts().OpenCL) {
11514     Diag(FD->getLocation(), diag::err_opencl_no_main)
11515         << FD->hasAttr<OpenCLKernelAttr>();
11516     FD->setInvalidDecl();
11517     return;
11518   }
11519 
11520   // Functions named main in hlsl are default entries, but don't have specific
11521   // signatures they are required to conform to.
11522   if (getLangOpts().HLSL)
11523     return;
11524 
11525   QualType T = FD->getType();
11526   assert(T->isFunctionType() && "function decl is not of function type");
11527   const FunctionType* FT = T->castAs<FunctionType>();
11528 
11529   // Set default calling convention for main()
11530   if (FT->getCallConv() != CC_C) {
11531     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11532     FD->setType(QualType(FT, 0));
11533     T = Context.getCanonicalType(FD->getType());
11534   }
11535 
11536   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11537     // In C with GNU extensions we allow main() to have non-integer return
11538     // type, but we should warn about the extension, and we disable the
11539     // implicit-return-zero rule.
11540 
11541     // GCC in C mode accepts qualified 'int'.
11542     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11543       FD->setHasImplicitReturnZero(true);
11544     else {
11545       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11546       SourceRange RTRange = FD->getReturnTypeSourceRange();
11547       if (RTRange.isValid())
11548         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11549             << FixItHint::CreateReplacement(RTRange, "int");
11550     }
11551   } else {
11552     // In C and C++, main magically returns 0 if you fall off the end;
11553     // set the flag which tells us that.
11554     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11555 
11556     // All the standards say that main() should return 'int'.
11557     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11558       FD->setHasImplicitReturnZero(true);
11559     else {
11560       // Otherwise, this is just a flat-out error.
11561       SourceRange RTRange = FD->getReturnTypeSourceRange();
11562       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11563           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11564                                 : FixItHint());
11565       FD->setInvalidDecl(true);
11566     }
11567   }
11568 
11569   // Treat protoless main() as nullary.
11570   if (isa<FunctionNoProtoType>(FT)) return;
11571 
11572   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11573   unsigned nparams = FTP->getNumParams();
11574   assert(FD->getNumParams() == nparams);
11575 
11576   bool HasExtraParameters = (nparams > 3);
11577 
11578   if (FTP->isVariadic()) {
11579     Diag(FD->getLocation(), diag::ext_variadic_main);
11580     // FIXME: if we had information about the location of the ellipsis, we
11581     // could add a FixIt hint to remove it as a parameter.
11582   }
11583 
11584   // Darwin passes an undocumented fourth argument of type char**.  If
11585   // other platforms start sprouting these, the logic below will start
11586   // getting shifty.
11587   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11588     HasExtraParameters = false;
11589 
11590   if (HasExtraParameters) {
11591     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11592     FD->setInvalidDecl(true);
11593     nparams = 3;
11594   }
11595 
11596   // FIXME: a lot of the following diagnostics would be improved
11597   // if we had some location information about types.
11598 
11599   QualType CharPP =
11600     Context.getPointerType(Context.getPointerType(Context.CharTy));
11601   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11602 
11603   for (unsigned i = 0; i < nparams; ++i) {
11604     QualType AT = FTP->getParamType(i);
11605 
11606     bool mismatch = true;
11607 
11608     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11609       mismatch = false;
11610     else if (Expected[i] == CharPP) {
11611       // As an extension, the following forms are okay:
11612       //   char const **
11613       //   char const * const *
11614       //   char * const *
11615 
11616       QualifierCollector qs;
11617       const PointerType* PT;
11618       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11619           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11620           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11621                               Context.CharTy)) {
11622         qs.removeConst();
11623         mismatch = !qs.empty();
11624       }
11625     }
11626 
11627     if (mismatch) {
11628       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11629       // TODO: suggest replacing given type with expected type
11630       FD->setInvalidDecl(true);
11631     }
11632   }
11633 
11634   if (nparams == 1 && !FD->isInvalidDecl()) {
11635     Diag(FD->getLocation(), diag::warn_main_one_arg);
11636   }
11637 
11638   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11639     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11640     FD->setInvalidDecl();
11641   }
11642 }
11643 
11644 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11645 
11646   // Default calling convention for main and wmain is __cdecl
11647   if (FD->getName() == "main" || FD->getName() == "wmain")
11648     return false;
11649 
11650   // Default calling convention for MinGW is __cdecl
11651   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11652   if (T.isWindowsGNUEnvironment())
11653     return false;
11654 
11655   // Default calling convention for WinMain, wWinMain and DllMain
11656   // is __stdcall on 32 bit Windows
11657   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11658     return true;
11659 
11660   return false;
11661 }
11662 
11663 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11664   QualType T = FD->getType();
11665   assert(T->isFunctionType() && "function decl is not of function type");
11666   const FunctionType *FT = T->castAs<FunctionType>();
11667 
11668   // Set an implicit return of 'zero' if the function can return some integral,
11669   // enumeration, pointer or nullptr type.
11670   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11671       FT->getReturnType()->isAnyPointerType() ||
11672       FT->getReturnType()->isNullPtrType())
11673     // DllMain is exempt because a return value of zero means it failed.
11674     if (FD->getName() != "DllMain")
11675       FD->setHasImplicitReturnZero(true);
11676 
11677   // Explicity specified calling conventions are applied to MSVC entry points
11678   if (!hasExplicitCallingConv(T)) {
11679     if (isDefaultStdCall(FD, *this)) {
11680       if (FT->getCallConv() != CC_X86StdCall) {
11681         FT = Context.adjustFunctionType(
11682             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11683         FD->setType(QualType(FT, 0));
11684       }
11685     } else if (FT->getCallConv() != CC_C) {
11686       FT = Context.adjustFunctionType(FT,
11687                                       FT->getExtInfo().withCallingConv(CC_C));
11688       FD->setType(QualType(FT, 0));
11689     }
11690   }
11691 
11692   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11693     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11694     FD->setInvalidDecl();
11695   }
11696 }
11697 
11698 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11699   // FIXME: Need strict checking.  In C89, we need to check for
11700   // any assignment, increment, decrement, function-calls, or
11701   // commas outside of a sizeof.  In C99, it's the same list,
11702   // except that the aforementioned are allowed in unevaluated
11703   // expressions.  Everything else falls under the
11704   // "may accept other forms of constant expressions" exception.
11705   //
11706   // Regular C++ code will not end up here (exceptions: language extensions,
11707   // OpenCL C++ etc), so the constant expression rules there don't matter.
11708   if (Init->isValueDependent()) {
11709     assert(Init->containsErrors() &&
11710            "Dependent code should only occur in error-recovery path.");
11711     return true;
11712   }
11713   const Expr *Culprit;
11714   if (Init->isConstantInitializer(Context, false, &Culprit))
11715     return false;
11716   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11717     << Culprit->getSourceRange();
11718   return true;
11719 }
11720 
11721 namespace {
11722   // Visits an initialization expression to see if OrigDecl is evaluated in
11723   // its own initialization and throws a warning if it does.
11724   class SelfReferenceChecker
11725       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11726     Sema &S;
11727     Decl *OrigDecl;
11728     bool isRecordType;
11729     bool isPODType;
11730     bool isReferenceType;
11731 
11732     bool isInitList;
11733     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11734 
11735   public:
11736     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11737 
11738     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11739                                                     S(S), OrigDecl(OrigDecl) {
11740       isPODType = false;
11741       isRecordType = false;
11742       isReferenceType = false;
11743       isInitList = false;
11744       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11745         isPODType = VD->getType().isPODType(S.Context);
11746         isRecordType = VD->getType()->isRecordType();
11747         isReferenceType = VD->getType()->isReferenceType();
11748       }
11749     }
11750 
11751     // For most expressions, just call the visitor.  For initializer lists,
11752     // track the index of the field being initialized since fields are
11753     // initialized in order allowing use of previously initialized fields.
11754     void CheckExpr(Expr *E) {
11755       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11756       if (!InitList) {
11757         Visit(E);
11758         return;
11759       }
11760 
11761       // Track and increment the index here.
11762       isInitList = true;
11763       InitFieldIndex.push_back(0);
11764       for (auto Child : InitList->children()) {
11765         CheckExpr(cast<Expr>(Child));
11766         ++InitFieldIndex.back();
11767       }
11768       InitFieldIndex.pop_back();
11769     }
11770 
11771     // Returns true if MemberExpr is checked and no further checking is needed.
11772     // Returns false if additional checking is required.
11773     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11774       llvm::SmallVector<FieldDecl*, 4> Fields;
11775       Expr *Base = E;
11776       bool ReferenceField = false;
11777 
11778       // Get the field members used.
11779       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11780         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11781         if (!FD)
11782           return false;
11783         Fields.push_back(FD);
11784         if (FD->getType()->isReferenceType())
11785           ReferenceField = true;
11786         Base = ME->getBase()->IgnoreParenImpCasts();
11787       }
11788 
11789       // Keep checking only if the base Decl is the same.
11790       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11791       if (!DRE || DRE->getDecl() != OrigDecl)
11792         return false;
11793 
11794       // A reference field can be bound to an unininitialized field.
11795       if (CheckReference && !ReferenceField)
11796         return true;
11797 
11798       // Convert FieldDecls to their index number.
11799       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11800       for (const FieldDecl *I : llvm::reverse(Fields))
11801         UsedFieldIndex.push_back(I->getFieldIndex());
11802 
11803       // See if a warning is needed by checking the first difference in index
11804       // numbers.  If field being used has index less than the field being
11805       // initialized, then the use is safe.
11806       for (auto UsedIter = UsedFieldIndex.begin(),
11807                 UsedEnd = UsedFieldIndex.end(),
11808                 OrigIter = InitFieldIndex.begin(),
11809                 OrigEnd = InitFieldIndex.end();
11810            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11811         if (*UsedIter < *OrigIter)
11812           return true;
11813         if (*UsedIter > *OrigIter)
11814           break;
11815       }
11816 
11817       // TODO: Add a different warning which will print the field names.
11818       HandleDeclRefExpr(DRE);
11819       return true;
11820     }
11821 
11822     // For most expressions, the cast is directly above the DeclRefExpr.
11823     // For conditional operators, the cast can be outside the conditional
11824     // operator if both expressions are DeclRefExpr's.
11825     void HandleValue(Expr *E) {
11826       E = E->IgnoreParens();
11827       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11828         HandleDeclRefExpr(DRE);
11829         return;
11830       }
11831 
11832       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11833         Visit(CO->getCond());
11834         HandleValue(CO->getTrueExpr());
11835         HandleValue(CO->getFalseExpr());
11836         return;
11837       }
11838 
11839       if (BinaryConditionalOperator *BCO =
11840               dyn_cast<BinaryConditionalOperator>(E)) {
11841         Visit(BCO->getCond());
11842         HandleValue(BCO->getFalseExpr());
11843         return;
11844       }
11845 
11846       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11847         HandleValue(OVE->getSourceExpr());
11848         return;
11849       }
11850 
11851       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11852         if (BO->getOpcode() == BO_Comma) {
11853           Visit(BO->getLHS());
11854           HandleValue(BO->getRHS());
11855           return;
11856         }
11857       }
11858 
11859       if (isa<MemberExpr>(E)) {
11860         if (isInitList) {
11861           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11862                                       false /*CheckReference*/))
11863             return;
11864         }
11865 
11866         Expr *Base = E->IgnoreParenImpCasts();
11867         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11868           // Check for static member variables and don't warn on them.
11869           if (!isa<FieldDecl>(ME->getMemberDecl()))
11870             return;
11871           Base = ME->getBase()->IgnoreParenImpCasts();
11872         }
11873         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11874           HandleDeclRefExpr(DRE);
11875         return;
11876       }
11877 
11878       Visit(E);
11879     }
11880 
11881     // Reference types not handled in HandleValue are handled here since all
11882     // uses of references are bad, not just r-value uses.
11883     void VisitDeclRefExpr(DeclRefExpr *E) {
11884       if (isReferenceType)
11885         HandleDeclRefExpr(E);
11886     }
11887 
11888     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11889       if (E->getCastKind() == CK_LValueToRValue) {
11890         HandleValue(E->getSubExpr());
11891         return;
11892       }
11893 
11894       Inherited::VisitImplicitCastExpr(E);
11895     }
11896 
11897     void VisitMemberExpr(MemberExpr *E) {
11898       if (isInitList) {
11899         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11900           return;
11901       }
11902 
11903       // Don't warn on arrays since they can be treated as pointers.
11904       if (E->getType()->canDecayToPointerType()) return;
11905 
11906       // Warn when a non-static method call is followed by non-static member
11907       // field accesses, which is followed by a DeclRefExpr.
11908       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11909       bool Warn = (MD && !MD->isStatic());
11910       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11911       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11912         if (!isa<FieldDecl>(ME->getMemberDecl()))
11913           Warn = false;
11914         Base = ME->getBase()->IgnoreParenImpCasts();
11915       }
11916 
11917       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11918         if (Warn)
11919           HandleDeclRefExpr(DRE);
11920         return;
11921       }
11922 
11923       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11924       // Visit that expression.
11925       Visit(Base);
11926     }
11927 
11928     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11929       Expr *Callee = E->getCallee();
11930 
11931       if (isa<UnresolvedLookupExpr>(Callee))
11932         return Inherited::VisitCXXOperatorCallExpr(E);
11933 
11934       Visit(Callee);
11935       for (auto Arg: E->arguments())
11936         HandleValue(Arg->IgnoreParenImpCasts());
11937     }
11938 
11939     void VisitUnaryOperator(UnaryOperator *E) {
11940       // For POD record types, addresses of its own members are well-defined.
11941       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11942           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11943         if (!isPODType)
11944           HandleValue(E->getSubExpr());
11945         return;
11946       }
11947 
11948       if (E->isIncrementDecrementOp()) {
11949         HandleValue(E->getSubExpr());
11950         return;
11951       }
11952 
11953       Inherited::VisitUnaryOperator(E);
11954     }
11955 
11956     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11957 
11958     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11959       if (E->getConstructor()->isCopyConstructor()) {
11960         Expr *ArgExpr = E->getArg(0);
11961         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11962           if (ILE->getNumInits() == 1)
11963             ArgExpr = ILE->getInit(0);
11964         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11965           if (ICE->getCastKind() == CK_NoOp)
11966             ArgExpr = ICE->getSubExpr();
11967         HandleValue(ArgExpr);
11968         return;
11969       }
11970       Inherited::VisitCXXConstructExpr(E);
11971     }
11972 
11973     void VisitCallExpr(CallExpr *E) {
11974       // Treat std::move as a use.
11975       if (E->isCallToStdMove()) {
11976         HandleValue(E->getArg(0));
11977         return;
11978       }
11979 
11980       Inherited::VisitCallExpr(E);
11981     }
11982 
11983     void VisitBinaryOperator(BinaryOperator *E) {
11984       if (E->isCompoundAssignmentOp()) {
11985         HandleValue(E->getLHS());
11986         Visit(E->getRHS());
11987         return;
11988       }
11989 
11990       Inherited::VisitBinaryOperator(E);
11991     }
11992 
11993     // A custom visitor for BinaryConditionalOperator is needed because the
11994     // regular visitor would check the condition and true expression separately
11995     // but both point to the same place giving duplicate diagnostics.
11996     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11997       Visit(E->getCond());
11998       Visit(E->getFalseExpr());
11999     }
12000 
12001     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12002       Decl* ReferenceDecl = DRE->getDecl();
12003       if (OrigDecl != ReferenceDecl) return;
12004       unsigned diag;
12005       if (isReferenceType) {
12006         diag = diag::warn_uninit_self_reference_in_reference_init;
12007       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12008         diag = diag::warn_static_self_reference_in_init;
12009       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12010                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12011                  DRE->getDecl()->getType()->isRecordType()) {
12012         diag = diag::warn_uninit_self_reference_in_init;
12013       } else {
12014         // Local variables will be handled by the CFG analysis.
12015         return;
12016       }
12017 
12018       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12019                             S.PDiag(diag)
12020                                 << DRE->getDecl() << OrigDecl->getLocation()
12021                                 << DRE->getSourceRange());
12022     }
12023   };
12024 
12025   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12026   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12027                                  bool DirectInit) {
12028     // Parameters arguments are occassionially constructed with itself,
12029     // for instance, in recursive functions.  Skip them.
12030     if (isa<ParmVarDecl>(OrigDecl))
12031       return;
12032 
12033     E = E->IgnoreParens();
12034 
12035     // Skip checking T a = a where T is not a record or reference type.
12036     // Doing so is a way to silence uninitialized warnings.
12037     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12038       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12039         if (ICE->getCastKind() == CK_LValueToRValue)
12040           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12041             if (DRE->getDecl() == OrigDecl)
12042               return;
12043 
12044     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12045   }
12046 } // end anonymous namespace
12047 
12048 namespace {
12049   // Simple wrapper to add the name of a variable or (if no variable is
12050   // available) a DeclarationName into a diagnostic.
12051   struct VarDeclOrName {
12052     VarDecl *VDecl;
12053     DeclarationName Name;
12054 
12055     friend const Sema::SemaDiagnosticBuilder &
12056     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12057       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12058     }
12059   };
12060 } // end anonymous namespace
12061 
12062 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12063                                             DeclarationName Name, QualType Type,
12064                                             TypeSourceInfo *TSI,
12065                                             SourceRange Range, bool DirectInit,
12066                                             Expr *Init) {
12067   bool IsInitCapture = !VDecl;
12068   assert((!VDecl || !VDecl->isInitCapture()) &&
12069          "init captures are expected to be deduced prior to initialization");
12070 
12071   VarDeclOrName VN{VDecl, Name};
12072 
12073   DeducedType *Deduced = Type->getContainedDeducedType();
12074   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12075 
12076   // C++11 [dcl.spec.auto]p3
12077   if (!Init) {
12078     assert(VDecl && "no init for init capture deduction?");
12079 
12080     // Except for class argument deduction, and then for an initializing
12081     // declaration only, i.e. no static at class scope or extern.
12082     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12083         VDecl->hasExternalStorage() ||
12084         VDecl->isStaticDataMember()) {
12085       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12086         << VDecl->getDeclName() << Type;
12087       return QualType();
12088     }
12089   }
12090 
12091   ArrayRef<Expr*> DeduceInits;
12092   if (Init)
12093     DeduceInits = Init;
12094 
12095   if (DirectInit) {
12096     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12097       DeduceInits = PL->exprs();
12098   }
12099 
12100   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12101     assert(VDecl && "non-auto type for init capture deduction?");
12102     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12103     InitializationKind Kind = InitializationKind::CreateForInit(
12104         VDecl->getLocation(), DirectInit, Init);
12105     // FIXME: Initialization should not be taking a mutable list of inits.
12106     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12107     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12108                                                        InitsCopy);
12109   }
12110 
12111   if (DirectInit) {
12112     if (auto *IL = dyn_cast<InitListExpr>(Init))
12113       DeduceInits = IL->inits();
12114   }
12115 
12116   // Deduction only works if we have exactly one source expression.
12117   if (DeduceInits.empty()) {
12118     // It isn't possible to write this directly, but it is possible to
12119     // end up in this situation with "auto x(some_pack...);"
12120     Diag(Init->getBeginLoc(), IsInitCapture
12121                                   ? diag::err_init_capture_no_expression
12122                                   : diag::err_auto_var_init_no_expression)
12123         << VN << Type << Range;
12124     return QualType();
12125   }
12126 
12127   if (DeduceInits.size() > 1) {
12128     Diag(DeduceInits[1]->getBeginLoc(),
12129          IsInitCapture ? diag::err_init_capture_multiple_expressions
12130                        : diag::err_auto_var_init_multiple_expressions)
12131         << VN << Type << Range;
12132     return QualType();
12133   }
12134 
12135   Expr *DeduceInit = DeduceInits[0];
12136   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12137     Diag(Init->getBeginLoc(), IsInitCapture
12138                                   ? diag::err_init_capture_paren_braces
12139                                   : diag::err_auto_var_init_paren_braces)
12140         << isa<InitListExpr>(Init) << VN << Type << Range;
12141     return QualType();
12142   }
12143 
12144   // Expressions default to 'id' when we're in a debugger.
12145   bool DefaultedAnyToId = false;
12146   if (getLangOpts().DebuggerCastResultToId &&
12147       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12148     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12149     if (Result.isInvalid()) {
12150       return QualType();
12151     }
12152     Init = Result.get();
12153     DefaultedAnyToId = true;
12154   }
12155 
12156   // C++ [dcl.decomp]p1:
12157   //   If the assignment-expression [...] has array type A and no ref-qualifier
12158   //   is present, e has type cv A
12159   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12160       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12161       DeduceInit->getType()->isConstantArrayType())
12162     return Context.getQualifiedType(DeduceInit->getType(),
12163                                     Type.getQualifiers());
12164 
12165   QualType DeducedType;
12166   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12167     if (!IsInitCapture)
12168       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12169     else if (isa<InitListExpr>(Init))
12170       Diag(Range.getBegin(),
12171            diag::err_init_capture_deduction_failure_from_init_list)
12172           << VN
12173           << (DeduceInit->getType().isNull() ? TSI->getType()
12174                                              : DeduceInit->getType())
12175           << DeduceInit->getSourceRange();
12176     else
12177       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12178           << VN << TSI->getType()
12179           << (DeduceInit->getType().isNull() ? TSI->getType()
12180                                              : DeduceInit->getType())
12181           << DeduceInit->getSourceRange();
12182   }
12183 
12184   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12185   // 'id' instead of a specific object type prevents most of our usual
12186   // checks.
12187   // We only want to warn outside of template instantiations, though:
12188   // inside a template, the 'id' could have come from a parameter.
12189   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12190       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12191     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12192     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12193   }
12194 
12195   return DeducedType;
12196 }
12197 
12198 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12199                                          Expr *Init) {
12200   assert(!Init || !Init->containsErrors());
12201   QualType DeducedType = deduceVarTypeFromInitializer(
12202       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12203       VDecl->getSourceRange(), DirectInit, Init);
12204   if (DeducedType.isNull()) {
12205     VDecl->setInvalidDecl();
12206     return true;
12207   }
12208 
12209   VDecl->setType(DeducedType);
12210   assert(VDecl->isLinkageValid());
12211 
12212   // In ARC, infer lifetime.
12213   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12214     VDecl->setInvalidDecl();
12215 
12216   if (getLangOpts().OpenCL)
12217     deduceOpenCLAddressSpace(VDecl);
12218 
12219   // If this is a redeclaration, check that the type we just deduced matches
12220   // the previously declared type.
12221   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12222     // We never need to merge the type, because we cannot form an incomplete
12223     // array of auto, nor deduce such a type.
12224     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12225   }
12226 
12227   // Check the deduced type is valid for a variable declaration.
12228   CheckVariableDeclarationType(VDecl);
12229   return VDecl->isInvalidDecl();
12230 }
12231 
12232 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12233                                               SourceLocation Loc) {
12234   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12235     Init = EWC->getSubExpr();
12236 
12237   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12238     Init = CE->getSubExpr();
12239 
12240   QualType InitType = Init->getType();
12241   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12242           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12243          "shouldn't be called if type doesn't have a non-trivial C struct");
12244   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12245     for (auto I : ILE->inits()) {
12246       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12247           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12248         continue;
12249       SourceLocation SL = I->getExprLoc();
12250       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12251     }
12252     return;
12253   }
12254 
12255   if (isa<ImplicitValueInitExpr>(Init)) {
12256     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12257       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12258                             NTCUK_Init);
12259   } else {
12260     // Assume all other explicit initializers involving copying some existing
12261     // object.
12262     // TODO: ignore any explicit initializers where we can guarantee
12263     // copy-elision.
12264     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12265       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12266   }
12267 }
12268 
12269 namespace {
12270 
12271 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12272   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12273   // in the source code or implicitly by the compiler if it is in a union
12274   // defined in a system header and has non-trivial ObjC ownership
12275   // qualifications. We don't want those fields to participate in determining
12276   // whether the containing union is non-trivial.
12277   return FD->hasAttr<UnavailableAttr>();
12278 }
12279 
12280 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12281     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12282                                     void> {
12283   using Super =
12284       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12285                                     void>;
12286 
12287   DiagNonTrivalCUnionDefaultInitializeVisitor(
12288       QualType OrigTy, SourceLocation OrigLoc,
12289       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12290       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12291 
12292   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12293                      const FieldDecl *FD, bool InNonTrivialUnion) {
12294     if (const auto *AT = S.Context.getAsArrayType(QT))
12295       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12296                                      InNonTrivialUnion);
12297     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12298   }
12299 
12300   void visitARCStrong(QualType QT, const FieldDecl *FD,
12301                       bool InNonTrivialUnion) {
12302     if (InNonTrivialUnion)
12303       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12304           << 1 << 0 << QT << FD->getName();
12305   }
12306 
12307   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12308     if (InNonTrivialUnion)
12309       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12310           << 1 << 0 << QT << FD->getName();
12311   }
12312 
12313   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12314     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12315     if (RD->isUnion()) {
12316       if (OrigLoc.isValid()) {
12317         bool IsUnion = false;
12318         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12319           IsUnion = OrigRD->isUnion();
12320         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12321             << 0 << OrigTy << IsUnion << UseContext;
12322         // Reset OrigLoc so that this diagnostic is emitted only once.
12323         OrigLoc = SourceLocation();
12324       }
12325       InNonTrivialUnion = true;
12326     }
12327 
12328     if (InNonTrivialUnion)
12329       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12330           << 0 << 0 << QT.getUnqualifiedType() << "";
12331 
12332     for (const FieldDecl *FD : RD->fields())
12333       if (!shouldIgnoreForRecordTriviality(FD))
12334         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12335   }
12336 
12337   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12338 
12339   // The non-trivial C union type or the struct/union type that contains a
12340   // non-trivial C union.
12341   QualType OrigTy;
12342   SourceLocation OrigLoc;
12343   Sema::NonTrivialCUnionContext UseContext;
12344   Sema &S;
12345 };
12346 
12347 struct DiagNonTrivalCUnionDestructedTypeVisitor
12348     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12349   using Super =
12350       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12351 
12352   DiagNonTrivalCUnionDestructedTypeVisitor(
12353       QualType OrigTy, SourceLocation OrigLoc,
12354       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12355       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12356 
12357   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12358                      const FieldDecl *FD, bool InNonTrivialUnion) {
12359     if (const auto *AT = S.Context.getAsArrayType(QT))
12360       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12361                                      InNonTrivialUnion);
12362     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12363   }
12364 
12365   void visitARCStrong(QualType QT, const FieldDecl *FD,
12366                       bool InNonTrivialUnion) {
12367     if (InNonTrivialUnion)
12368       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12369           << 1 << 1 << QT << FD->getName();
12370   }
12371 
12372   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12373     if (InNonTrivialUnion)
12374       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12375           << 1 << 1 << QT << FD->getName();
12376   }
12377 
12378   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12379     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12380     if (RD->isUnion()) {
12381       if (OrigLoc.isValid()) {
12382         bool IsUnion = false;
12383         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12384           IsUnion = OrigRD->isUnion();
12385         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12386             << 1 << OrigTy << IsUnion << UseContext;
12387         // Reset OrigLoc so that this diagnostic is emitted only once.
12388         OrigLoc = SourceLocation();
12389       }
12390       InNonTrivialUnion = true;
12391     }
12392 
12393     if (InNonTrivialUnion)
12394       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12395           << 0 << 1 << QT.getUnqualifiedType() << "";
12396 
12397     for (const FieldDecl *FD : RD->fields())
12398       if (!shouldIgnoreForRecordTriviality(FD))
12399         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12400   }
12401 
12402   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12403   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12404                           bool InNonTrivialUnion) {}
12405 
12406   // The non-trivial C union type or the struct/union type that contains a
12407   // non-trivial C union.
12408   QualType OrigTy;
12409   SourceLocation OrigLoc;
12410   Sema::NonTrivialCUnionContext UseContext;
12411   Sema &S;
12412 };
12413 
12414 struct DiagNonTrivalCUnionCopyVisitor
12415     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12416   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12417 
12418   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12419                                  Sema::NonTrivialCUnionContext UseContext,
12420                                  Sema &S)
12421       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12422 
12423   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12424                      const FieldDecl *FD, bool InNonTrivialUnion) {
12425     if (const auto *AT = S.Context.getAsArrayType(QT))
12426       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12427                                      InNonTrivialUnion);
12428     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12429   }
12430 
12431   void visitARCStrong(QualType QT, const FieldDecl *FD,
12432                       bool InNonTrivialUnion) {
12433     if (InNonTrivialUnion)
12434       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12435           << 1 << 2 << QT << FD->getName();
12436   }
12437 
12438   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12439     if (InNonTrivialUnion)
12440       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12441           << 1 << 2 << QT << FD->getName();
12442   }
12443 
12444   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12445     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12446     if (RD->isUnion()) {
12447       if (OrigLoc.isValid()) {
12448         bool IsUnion = false;
12449         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12450           IsUnion = OrigRD->isUnion();
12451         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12452             << 2 << OrigTy << IsUnion << UseContext;
12453         // Reset OrigLoc so that this diagnostic is emitted only once.
12454         OrigLoc = SourceLocation();
12455       }
12456       InNonTrivialUnion = true;
12457     }
12458 
12459     if (InNonTrivialUnion)
12460       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12461           << 0 << 2 << QT.getUnqualifiedType() << "";
12462 
12463     for (const FieldDecl *FD : RD->fields())
12464       if (!shouldIgnoreForRecordTriviality(FD))
12465         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12466   }
12467 
12468   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12469                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12470   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12471   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12472                             bool InNonTrivialUnion) {}
12473 
12474   // The non-trivial C union type or the struct/union type that contains a
12475   // non-trivial C union.
12476   QualType OrigTy;
12477   SourceLocation OrigLoc;
12478   Sema::NonTrivialCUnionContext UseContext;
12479   Sema &S;
12480 };
12481 
12482 } // namespace
12483 
12484 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12485                                  NonTrivialCUnionContext UseContext,
12486                                  unsigned NonTrivialKind) {
12487   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12488           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12489           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12490          "shouldn't be called if type doesn't have a non-trivial C union");
12491 
12492   if ((NonTrivialKind & NTCUK_Init) &&
12493       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12494     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12495         .visit(QT, nullptr, false);
12496   if ((NonTrivialKind & NTCUK_Destruct) &&
12497       QT.hasNonTrivialToPrimitiveDestructCUnion())
12498     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12499         .visit(QT, nullptr, false);
12500   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12501     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12502         .visit(QT, nullptr, false);
12503 }
12504 
12505 /// AddInitializerToDecl - Adds the initializer Init to the
12506 /// declaration dcl. If DirectInit is true, this is C++ direct
12507 /// initialization rather than copy initialization.
12508 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12509   // If there is no declaration, there was an error parsing it.  Just ignore
12510   // the initializer.
12511   if (!RealDecl || RealDecl->isInvalidDecl()) {
12512     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12513     return;
12514   }
12515 
12516   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12517     // Pure-specifiers are handled in ActOnPureSpecifier.
12518     Diag(Method->getLocation(), diag::err_member_function_initialization)
12519       << Method->getDeclName() << Init->getSourceRange();
12520     Method->setInvalidDecl();
12521     return;
12522   }
12523 
12524   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12525   if (!VDecl) {
12526     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12527     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12528     RealDecl->setInvalidDecl();
12529     return;
12530   }
12531 
12532   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12533   if (VDecl->getType()->isUndeducedType()) {
12534     // Attempt typo correction early so that the type of the init expression can
12535     // be deduced based on the chosen correction if the original init contains a
12536     // TypoExpr.
12537     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12538     if (!Res.isUsable()) {
12539       // There are unresolved typos in Init, just drop them.
12540       // FIXME: improve the recovery strategy to preserve the Init.
12541       RealDecl->setInvalidDecl();
12542       return;
12543     }
12544     if (Res.get()->containsErrors()) {
12545       // Invalidate the decl as we don't know the type for recovery-expr yet.
12546       RealDecl->setInvalidDecl();
12547       VDecl->setInit(Res.get());
12548       return;
12549     }
12550     Init = Res.get();
12551 
12552     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12553       return;
12554   }
12555 
12556   // dllimport cannot be used on variable definitions.
12557   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12558     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12559     VDecl->setInvalidDecl();
12560     return;
12561   }
12562 
12563   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12564     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12565     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12566     VDecl->setInvalidDecl();
12567     return;
12568   }
12569 
12570   if (!VDecl->getType()->isDependentType()) {
12571     // A definition must end up with a complete type, which means it must be
12572     // complete with the restriction that an array type might be completed by
12573     // the initializer; note that later code assumes this restriction.
12574     QualType BaseDeclType = VDecl->getType();
12575     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12576       BaseDeclType = Array->getElementType();
12577     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12578                             diag::err_typecheck_decl_incomplete_type)) {
12579       RealDecl->setInvalidDecl();
12580       return;
12581     }
12582 
12583     // The variable can not have an abstract class type.
12584     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12585                                diag::err_abstract_type_in_decl,
12586                                AbstractVariableType))
12587       VDecl->setInvalidDecl();
12588   }
12589 
12590   // If adding the initializer will turn this declaration into a definition,
12591   // and we already have a definition for this variable, diagnose or otherwise
12592   // handle the situation.
12593   if (VarDecl *Def = VDecl->getDefinition())
12594     if (Def != VDecl &&
12595         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12596         !VDecl->isThisDeclarationADemotedDefinition() &&
12597         checkVarDeclRedefinition(Def, VDecl))
12598       return;
12599 
12600   if (getLangOpts().CPlusPlus) {
12601     // C++ [class.static.data]p4
12602     //   If a static data member is of const integral or const
12603     //   enumeration type, its declaration in the class definition can
12604     //   specify a constant-initializer which shall be an integral
12605     //   constant expression (5.19). In that case, the member can appear
12606     //   in integral constant expressions. The member shall still be
12607     //   defined in a namespace scope if it is used in the program and the
12608     //   namespace scope definition shall not contain an initializer.
12609     //
12610     // We already performed a redefinition check above, but for static
12611     // data members we also need to check whether there was an in-class
12612     // declaration with an initializer.
12613     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12614       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12615           << VDecl->getDeclName();
12616       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12617            diag::note_previous_initializer)
12618           << 0;
12619       return;
12620     }
12621 
12622     if (VDecl->hasLocalStorage())
12623       setFunctionHasBranchProtectedScope();
12624 
12625     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12626       VDecl->setInvalidDecl();
12627       return;
12628     }
12629   }
12630 
12631   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12632   // a kernel function cannot be initialized."
12633   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12634     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12635     VDecl->setInvalidDecl();
12636     return;
12637   }
12638 
12639   // The LoaderUninitialized attribute acts as a definition (of undef).
12640   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12641     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12642     VDecl->setInvalidDecl();
12643     return;
12644   }
12645 
12646   // Get the decls type and save a reference for later, since
12647   // CheckInitializerTypes may change it.
12648   QualType DclT = VDecl->getType(), SavT = DclT;
12649 
12650   // Expressions default to 'id' when we're in a debugger
12651   // and we are assigning it to a variable of Objective-C pointer type.
12652   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12653       Init->getType() == Context.UnknownAnyTy) {
12654     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12655     if (Result.isInvalid()) {
12656       VDecl->setInvalidDecl();
12657       return;
12658     }
12659     Init = Result.get();
12660   }
12661 
12662   // Perform the initialization.
12663   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12664   if (!VDecl->isInvalidDecl()) {
12665     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12666     InitializationKind Kind = InitializationKind::CreateForInit(
12667         VDecl->getLocation(), DirectInit, Init);
12668 
12669     MultiExprArg Args = Init;
12670     if (CXXDirectInit)
12671       Args = MultiExprArg(CXXDirectInit->getExprs(),
12672                           CXXDirectInit->getNumExprs());
12673 
12674     // Try to correct any TypoExprs in the initialization arguments.
12675     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12676       ExprResult Res = CorrectDelayedTyposInExpr(
12677           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12678           [this, Entity, Kind](Expr *E) {
12679             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12680             return Init.Failed() ? ExprError() : E;
12681           });
12682       if (Res.isInvalid()) {
12683         VDecl->setInvalidDecl();
12684       } else if (Res.get() != Args[Idx]) {
12685         Args[Idx] = Res.get();
12686       }
12687     }
12688     if (VDecl->isInvalidDecl())
12689       return;
12690 
12691     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12692                                    /*TopLevelOfInitList=*/false,
12693                                    /*TreatUnavailableAsInvalid=*/false);
12694     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12695     if (Result.isInvalid()) {
12696       // If the provided initializer fails to initialize the var decl,
12697       // we attach a recovery expr for better recovery.
12698       auto RecoveryExpr =
12699           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12700       if (RecoveryExpr.get())
12701         VDecl->setInit(RecoveryExpr.get());
12702       return;
12703     }
12704 
12705     Init = Result.getAs<Expr>();
12706   }
12707 
12708   // Check for self-references within variable initializers.
12709   // Variables declared within a function/method body (except for references)
12710   // are handled by a dataflow analysis.
12711   // This is undefined behavior in C++, but valid in C.
12712   if (getLangOpts().CPlusPlus)
12713     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12714         VDecl->getType()->isReferenceType())
12715       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12716 
12717   // If the type changed, it means we had an incomplete type that was
12718   // completed by the initializer. For example:
12719   //   int ary[] = { 1, 3, 5 };
12720   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12721   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12722     VDecl->setType(DclT);
12723 
12724   if (!VDecl->isInvalidDecl()) {
12725     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12726 
12727     if (VDecl->hasAttr<BlocksAttr>())
12728       checkRetainCycles(VDecl, Init);
12729 
12730     // It is safe to assign a weak reference into a strong variable.
12731     // Although this code can still have problems:
12732     //   id x = self.weakProp;
12733     //   id y = self.weakProp;
12734     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12735     // paths through the function. This should be revisited if
12736     // -Wrepeated-use-of-weak is made flow-sensitive.
12737     if (FunctionScopeInfo *FSI = getCurFunction())
12738       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12739            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12740           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12741                            Init->getBeginLoc()))
12742         FSI->markSafeWeakUse(Init);
12743   }
12744 
12745   // The initialization is usually a full-expression.
12746   //
12747   // FIXME: If this is a braced initialization of an aggregate, it is not
12748   // an expression, and each individual field initializer is a separate
12749   // full-expression. For instance, in:
12750   //
12751   //   struct Temp { ~Temp(); };
12752   //   struct S { S(Temp); };
12753   //   struct T { S a, b; } t = { Temp(), Temp() }
12754   //
12755   // we should destroy the first Temp before constructing the second.
12756   ExprResult Result =
12757       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12758                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12759   if (Result.isInvalid()) {
12760     VDecl->setInvalidDecl();
12761     return;
12762   }
12763   Init = Result.get();
12764 
12765   // Attach the initializer to the decl.
12766   VDecl->setInit(Init);
12767 
12768   if (VDecl->isLocalVarDecl()) {
12769     // Don't check the initializer if the declaration is malformed.
12770     if (VDecl->isInvalidDecl()) {
12771       // do nothing
12772 
12773     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12774     // This is true even in C++ for OpenCL.
12775     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12776       CheckForConstantInitializer(Init, DclT);
12777 
12778     // Otherwise, C++ does not restrict the initializer.
12779     } else if (getLangOpts().CPlusPlus) {
12780       // do nothing
12781 
12782     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12783     // static storage duration shall be constant expressions or string literals.
12784     } else if (VDecl->getStorageClass() == SC_Static) {
12785       CheckForConstantInitializer(Init, DclT);
12786 
12787     // C89 is stricter than C99 for aggregate initializers.
12788     // C89 6.5.7p3: All the expressions [...] in an initializer list
12789     // for an object that has aggregate or union type shall be
12790     // constant expressions.
12791     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12792                isa<InitListExpr>(Init)) {
12793       const Expr *Culprit;
12794       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12795         Diag(Culprit->getExprLoc(),
12796              diag::ext_aggregate_init_not_constant)
12797           << Culprit->getSourceRange();
12798       }
12799     }
12800 
12801     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12802       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12803         if (VDecl->hasLocalStorage())
12804           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12805   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12806              VDecl->getLexicalDeclContext()->isRecord()) {
12807     // This is an in-class initialization for a static data member, e.g.,
12808     //
12809     // struct S {
12810     //   static const int value = 17;
12811     // };
12812 
12813     // C++ [class.mem]p4:
12814     //   A member-declarator can contain a constant-initializer only
12815     //   if it declares a static member (9.4) of const integral or
12816     //   const enumeration type, see 9.4.2.
12817     //
12818     // C++11 [class.static.data]p3:
12819     //   If a non-volatile non-inline const static data member is of integral
12820     //   or enumeration type, its declaration in the class definition can
12821     //   specify a brace-or-equal-initializer in which every initializer-clause
12822     //   that is an assignment-expression is a constant expression. A static
12823     //   data member of literal type can be declared in the class definition
12824     //   with the constexpr specifier; if so, its declaration shall specify a
12825     //   brace-or-equal-initializer in which every initializer-clause that is
12826     //   an assignment-expression is a constant expression.
12827 
12828     // Do nothing on dependent types.
12829     if (DclT->isDependentType()) {
12830 
12831     // Allow any 'static constexpr' members, whether or not they are of literal
12832     // type. We separately check that every constexpr variable is of literal
12833     // type.
12834     } else if (VDecl->isConstexpr()) {
12835 
12836     // Require constness.
12837     } else if (!DclT.isConstQualified()) {
12838       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12839         << Init->getSourceRange();
12840       VDecl->setInvalidDecl();
12841 
12842     // We allow integer constant expressions in all cases.
12843     } else if (DclT->isIntegralOrEnumerationType()) {
12844       // Check whether the expression is a constant expression.
12845       SourceLocation Loc;
12846       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12847         // In C++11, a non-constexpr const static data member with an
12848         // in-class initializer cannot be volatile.
12849         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12850       else if (Init->isValueDependent())
12851         ; // Nothing to check.
12852       else if (Init->isIntegerConstantExpr(Context, &Loc))
12853         ; // Ok, it's an ICE!
12854       else if (Init->getType()->isScopedEnumeralType() &&
12855                Init->isCXX11ConstantExpr(Context))
12856         ; // Ok, it is a scoped-enum constant expression.
12857       else if (Init->isEvaluatable(Context)) {
12858         // If we can constant fold the initializer through heroics, accept it,
12859         // but report this as a use of an extension for -pedantic.
12860         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12861           << Init->getSourceRange();
12862       } else {
12863         // Otherwise, this is some crazy unknown case.  Report the issue at the
12864         // location provided by the isIntegerConstantExpr failed check.
12865         Diag(Loc, diag::err_in_class_initializer_non_constant)
12866           << Init->getSourceRange();
12867         VDecl->setInvalidDecl();
12868       }
12869 
12870     // We allow foldable floating-point constants as an extension.
12871     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12872       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12873       // it anyway and provide a fixit to add the 'constexpr'.
12874       if (getLangOpts().CPlusPlus11) {
12875         Diag(VDecl->getLocation(),
12876              diag::ext_in_class_initializer_float_type_cxx11)
12877             << DclT << Init->getSourceRange();
12878         Diag(VDecl->getBeginLoc(),
12879              diag::note_in_class_initializer_float_type_cxx11)
12880             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12881       } else {
12882         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12883           << DclT << Init->getSourceRange();
12884 
12885         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12886           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12887             << Init->getSourceRange();
12888           VDecl->setInvalidDecl();
12889         }
12890       }
12891 
12892     // Suggest adding 'constexpr' in C++11 for literal types.
12893     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12894       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12895           << DclT << Init->getSourceRange()
12896           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12897       VDecl->setConstexpr(true);
12898 
12899     } else {
12900       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12901         << DclT << Init->getSourceRange();
12902       VDecl->setInvalidDecl();
12903     }
12904   } else if (VDecl->isFileVarDecl()) {
12905     // In C, extern is typically used to avoid tentative definitions when
12906     // declaring variables in headers, but adding an intializer makes it a
12907     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12908     // In C++, extern is often used to give implictly static const variables
12909     // external linkage, so don't warn in that case. If selectany is present,
12910     // this might be header code intended for C and C++ inclusion, so apply the
12911     // C++ rules.
12912     if (VDecl->getStorageClass() == SC_Extern &&
12913         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12914          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12915         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12916         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12917       Diag(VDecl->getLocation(), diag::warn_extern_init);
12918 
12919     // In Microsoft C++ mode, a const variable defined in namespace scope has
12920     // external linkage by default if the variable is declared with
12921     // __declspec(dllexport).
12922     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12923         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12924         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12925       VDecl->setStorageClass(SC_Extern);
12926 
12927     // C99 6.7.8p4. All file scoped initializers need to be constant.
12928     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12929       CheckForConstantInitializer(Init, DclT);
12930   }
12931 
12932   QualType InitType = Init->getType();
12933   if (!InitType.isNull() &&
12934       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12935        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12936     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12937 
12938   // We will represent direct-initialization similarly to copy-initialization:
12939   //    int x(1);  -as-> int x = 1;
12940   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12941   //
12942   // Clients that want to distinguish between the two forms, can check for
12943   // direct initializer using VarDecl::getInitStyle().
12944   // A major benefit is that clients that don't particularly care about which
12945   // exactly form was it (like the CodeGen) can handle both cases without
12946   // special case code.
12947 
12948   // C++ 8.5p11:
12949   // The form of initialization (using parentheses or '=') is generally
12950   // insignificant, but does matter when the entity being initialized has a
12951   // class type.
12952   if (CXXDirectInit) {
12953     assert(DirectInit && "Call-style initializer must be direct init.");
12954     VDecl->setInitStyle(VarDecl::CallInit);
12955   } else if (DirectInit) {
12956     // This must be list-initialization. No other way is direct-initialization.
12957     VDecl->setInitStyle(VarDecl::ListInit);
12958   }
12959 
12960   if (LangOpts.OpenMP &&
12961       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12962       VDecl->isFileVarDecl())
12963     DeclsToCheckForDeferredDiags.insert(VDecl);
12964   CheckCompleteVariableDeclaration(VDecl);
12965 }
12966 
12967 /// ActOnInitializerError - Given that there was an error parsing an
12968 /// initializer for the given declaration, try to at least re-establish
12969 /// invariants such as whether a variable's type is either dependent or
12970 /// complete.
12971 void Sema::ActOnInitializerError(Decl *D) {
12972   // Our main concern here is re-establishing invariants like "a
12973   // variable's type is either dependent or complete".
12974   if (!D || D->isInvalidDecl()) return;
12975 
12976   VarDecl *VD = dyn_cast<VarDecl>(D);
12977   if (!VD) return;
12978 
12979   // Bindings are not usable if we can't make sense of the initializer.
12980   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12981     for (auto *BD : DD->bindings())
12982       BD->setInvalidDecl();
12983 
12984   // Auto types are meaningless if we can't make sense of the initializer.
12985   if (VD->getType()->isUndeducedType()) {
12986     D->setInvalidDecl();
12987     return;
12988   }
12989 
12990   QualType Ty = VD->getType();
12991   if (Ty->isDependentType()) return;
12992 
12993   // Require a complete type.
12994   if (RequireCompleteType(VD->getLocation(),
12995                           Context.getBaseElementType(Ty),
12996                           diag::err_typecheck_decl_incomplete_type)) {
12997     VD->setInvalidDecl();
12998     return;
12999   }
13000 
13001   // Require a non-abstract type.
13002   if (RequireNonAbstractType(VD->getLocation(), Ty,
13003                              diag::err_abstract_type_in_decl,
13004                              AbstractVariableType)) {
13005     VD->setInvalidDecl();
13006     return;
13007   }
13008 
13009   // Don't bother complaining about constructors or destructors,
13010   // though.
13011 }
13012 
13013 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13014   // If there is no declaration, there was an error parsing it. Just ignore it.
13015   if (!RealDecl)
13016     return;
13017 
13018   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13019     QualType Type = Var->getType();
13020 
13021     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13022     if (isa<DecompositionDecl>(RealDecl)) {
13023       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13024       Var->setInvalidDecl();
13025       return;
13026     }
13027 
13028     if (Type->isUndeducedType() &&
13029         DeduceVariableDeclarationType(Var, false, nullptr))
13030       return;
13031 
13032     // C++11 [class.static.data]p3: A static data member can be declared with
13033     // the constexpr specifier; if so, its declaration shall specify
13034     // a brace-or-equal-initializer.
13035     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13036     // the definition of a variable [...] or the declaration of a static data
13037     // member.
13038     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13039         !Var->isThisDeclarationADemotedDefinition()) {
13040       if (Var->isStaticDataMember()) {
13041         // C++1z removes the relevant rule; the in-class declaration is always
13042         // a definition there.
13043         if (!getLangOpts().CPlusPlus17 &&
13044             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13045           Diag(Var->getLocation(),
13046                diag::err_constexpr_static_mem_var_requires_init)
13047               << Var;
13048           Var->setInvalidDecl();
13049           return;
13050         }
13051       } else {
13052         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13053         Var->setInvalidDecl();
13054         return;
13055       }
13056     }
13057 
13058     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13059     // be initialized.
13060     if (!Var->isInvalidDecl() &&
13061         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13062         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13063       bool HasConstExprDefaultConstructor = false;
13064       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13065         for (auto *Ctor : RD->ctors()) {
13066           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13067               Ctor->getMethodQualifiers().getAddressSpace() ==
13068                   LangAS::opencl_constant) {
13069             HasConstExprDefaultConstructor = true;
13070           }
13071         }
13072       }
13073       if (!HasConstExprDefaultConstructor) {
13074         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13075         Var->setInvalidDecl();
13076         return;
13077       }
13078     }
13079 
13080     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13081       if (Var->getStorageClass() == SC_Extern) {
13082         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13083             << Var;
13084         Var->setInvalidDecl();
13085         return;
13086       }
13087       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13088                               diag::err_typecheck_decl_incomplete_type)) {
13089         Var->setInvalidDecl();
13090         return;
13091       }
13092       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13093         if (!RD->hasTrivialDefaultConstructor()) {
13094           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13095           Var->setInvalidDecl();
13096           return;
13097         }
13098       }
13099       // The declaration is unitialized, no need for further checks.
13100       return;
13101     }
13102 
13103     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13104     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13105         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13106       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13107                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13108 
13109 
13110     switch (DefKind) {
13111     case VarDecl::Definition:
13112       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13113         break;
13114 
13115       // We have an out-of-line definition of a static data member
13116       // that has an in-class initializer, so we type-check this like
13117       // a declaration.
13118       //
13119       LLVM_FALLTHROUGH;
13120 
13121     case VarDecl::DeclarationOnly:
13122       // It's only a declaration.
13123 
13124       // Block scope. C99 6.7p7: If an identifier for an object is
13125       // declared with no linkage (C99 6.2.2p6), the type for the
13126       // object shall be complete.
13127       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13128           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13129           RequireCompleteType(Var->getLocation(), Type,
13130                               diag::err_typecheck_decl_incomplete_type))
13131         Var->setInvalidDecl();
13132 
13133       // Make sure that the type is not abstract.
13134       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13135           RequireNonAbstractType(Var->getLocation(), Type,
13136                                  diag::err_abstract_type_in_decl,
13137                                  AbstractVariableType))
13138         Var->setInvalidDecl();
13139       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13140           Var->getStorageClass() == SC_PrivateExtern) {
13141         Diag(Var->getLocation(), diag::warn_private_extern);
13142         Diag(Var->getLocation(), diag::note_private_extern);
13143       }
13144 
13145       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13146           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13147         ExternalDeclarations.push_back(Var);
13148 
13149       return;
13150 
13151     case VarDecl::TentativeDefinition:
13152       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13153       // object that has file scope without an initializer, and without a
13154       // storage-class specifier or with the storage-class specifier "static",
13155       // constitutes a tentative definition. Note: A tentative definition with
13156       // external linkage is valid (C99 6.2.2p5).
13157       if (!Var->isInvalidDecl()) {
13158         if (const IncompleteArrayType *ArrayT
13159                                     = Context.getAsIncompleteArrayType(Type)) {
13160           if (RequireCompleteSizedType(
13161                   Var->getLocation(), ArrayT->getElementType(),
13162                   diag::err_array_incomplete_or_sizeless_type))
13163             Var->setInvalidDecl();
13164         } else if (Var->getStorageClass() == SC_Static) {
13165           // C99 6.9.2p3: If the declaration of an identifier for an object is
13166           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13167           // declared type shall not be an incomplete type.
13168           // NOTE: code such as the following
13169           //     static struct s;
13170           //     struct s { int a; };
13171           // is accepted by gcc. Hence here we issue a warning instead of
13172           // an error and we do not invalidate the static declaration.
13173           // NOTE: to avoid multiple warnings, only check the first declaration.
13174           if (Var->isFirstDecl())
13175             RequireCompleteType(Var->getLocation(), Type,
13176                                 diag::ext_typecheck_decl_incomplete_type);
13177         }
13178       }
13179 
13180       // Record the tentative definition; we're done.
13181       if (!Var->isInvalidDecl())
13182         TentativeDefinitions.push_back(Var);
13183       return;
13184     }
13185 
13186     // Provide a specific diagnostic for uninitialized variable
13187     // definitions with incomplete array type.
13188     if (Type->isIncompleteArrayType()) {
13189       Diag(Var->getLocation(),
13190            diag::err_typecheck_incomplete_array_needs_initializer);
13191       Var->setInvalidDecl();
13192       return;
13193     }
13194 
13195     // Provide a specific diagnostic for uninitialized variable
13196     // definitions with reference type.
13197     if (Type->isReferenceType()) {
13198       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13199           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13200       Var->setInvalidDecl();
13201       return;
13202     }
13203 
13204     // Do not attempt to type-check the default initializer for a
13205     // variable with dependent type.
13206     if (Type->isDependentType())
13207       return;
13208 
13209     if (Var->isInvalidDecl())
13210       return;
13211 
13212     if (!Var->hasAttr<AliasAttr>()) {
13213       if (RequireCompleteType(Var->getLocation(),
13214                               Context.getBaseElementType(Type),
13215                               diag::err_typecheck_decl_incomplete_type)) {
13216         Var->setInvalidDecl();
13217         return;
13218       }
13219     } else {
13220       return;
13221     }
13222 
13223     // The variable can not have an abstract class type.
13224     if (RequireNonAbstractType(Var->getLocation(), Type,
13225                                diag::err_abstract_type_in_decl,
13226                                AbstractVariableType)) {
13227       Var->setInvalidDecl();
13228       return;
13229     }
13230 
13231     // Check for jumps past the implicit initializer.  C++0x
13232     // clarifies that this applies to a "variable with automatic
13233     // storage duration", not a "local variable".
13234     // C++11 [stmt.dcl]p3
13235     //   A program that jumps from a point where a variable with automatic
13236     //   storage duration is not in scope to a point where it is in scope is
13237     //   ill-formed unless the variable has scalar type, class type with a
13238     //   trivial default constructor and a trivial destructor, a cv-qualified
13239     //   version of one of these types, or an array of one of the preceding
13240     //   types and is declared without an initializer.
13241     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13242       if (const RecordType *Record
13243             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13244         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13245         // Mark the function (if we're in one) for further checking even if the
13246         // looser rules of C++11 do not require such checks, so that we can
13247         // diagnose incompatibilities with C++98.
13248         if (!CXXRecord->isPOD())
13249           setFunctionHasBranchProtectedScope();
13250       }
13251     }
13252     // In OpenCL, we can't initialize objects in the __local address space,
13253     // even implicitly, so don't synthesize an implicit initializer.
13254     if (getLangOpts().OpenCL &&
13255         Var->getType().getAddressSpace() == LangAS::opencl_local)
13256       return;
13257     // C++03 [dcl.init]p9:
13258     //   If no initializer is specified for an object, and the
13259     //   object is of (possibly cv-qualified) non-POD class type (or
13260     //   array thereof), the object shall be default-initialized; if
13261     //   the object is of const-qualified type, the underlying class
13262     //   type shall have a user-declared default
13263     //   constructor. Otherwise, if no initializer is specified for
13264     //   a non- static object, the object and its subobjects, if
13265     //   any, have an indeterminate initial value); if the object
13266     //   or any of its subobjects are of const-qualified type, the
13267     //   program is ill-formed.
13268     // C++0x [dcl.init]p11:
13269     //   If no initializer is specified for an object, the object is
13270     //   default-initialized; [...].
13271     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13272     InitializationKind Kind
13273       = InitializationKind::CreateDefault(Var->getLocation());
13274 
13275     InitializationSequence InitSeq(*this, Entity, Kind, None);
13276     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13277 
13278     if (Init.get()) {
13279       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13280       // This is important for template substitution.
13281       Var->setInitStyle(VarDecl::CallInit);
13282     } else if (Init.isInvalid()) {
13283       // If default-init fails, attach a recovery-expr initializer to track
13284       // that initialization was attempted and failed.
13285       auto RecoveryExpr =
13286           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13287       if (RecoveryExpr.get())
13288         Var->setInit(RecoveryExpr.get());
13289     }
13290 
13291     CheckCompleteVariableDeclaration(Var);
13292   }
13293 }
13294 
13295 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13296   // If there is no declaration, there was an error parsing it. Ignore it.
13297   if (!D)
13298     return;
13299 
13300   VarDecl *VD = dyn_cast<VarDecl>(D);
13301   if (!VD) {
13302     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13303     D->setInvalidDecl();
13304     return;
13305   }
13306 
13307   VD->setCXXForRangeDecl(true);
13308 
13309   // for-range-declaration cannot be given a storage class specifier.
13310   int Error = -1;
13311   switch (VD->getStorageClass()) {
13312   case SC_None:
13313     break;
13314   case SC_Extern:
13315     Error = 0;
13316     break;
13317   case SC_Static:
13318     Error = 1;
13319     break;
13320   case SC_PrivateExtern:
13321     Error = 2;
13322     break;
13323   case SC_Auto:
13324     Error = 3;
13325     break;
13326   case SC_Register:
13327     Error = 4;
13328     break;
13329   }
13330 
13331   // for-range-declaration cannot be given a storage class specifier con't.
13332   switch (VD->getTSCSpec()) {
13333   case TSCS_thread_local:
13334     Error = 6;
13335     break;
13336   case TSCS___thread:
13337   case TSCS__Thread_local:
13338   case TSCS_unspecified:
13339     break;
13340   }
13341 
13342   if (Error != -1) {
13343     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13344         << VD << Error;
13345     D->setInvalidDecl();
13346   }
13347 }
13348 
13349 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13350                                             IdentifierInfo *Ident,
13351                                             ParsedAttributes &Attrs) {
13352   // C++1y [stmt.iter]p1:
13353   //   A range-based for statement of the form
13354   //      for ( for-range-identifier : for-range-initializer ) statement
13355   //   is equivalent to
13356   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13357   DeclSpec DS(Attrs.getPool().getFactory());
13358 
13359   const char *PrevSpec;
13360   unsigned DiagID;
13361   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13362                      getPrintingPolicy());
13363 
13364   Declarator D(DS, DeclaratorContext::ForInit);
13365   D.SetIdentifier(Ident, IdentLoc);
13366   D.takeAttributes(Attrs);
13367 
13368   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13369                 IdentLoc);
13370   Decl *Var = ActOnDeclarator(S, D);
13371   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13372   FinalizeDeclaration(Var);
13373   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13374                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13375                                                       : IdentLoc);
13376 }
13377 
13378 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13379   if (var->isInvalidDecl()) return;
13380 
13381   MaybeAddCUDAConstantAttr(var);
13382 
13383   if (getLangOpts().OpenCL) {
13384     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13385     // initialiser
13386     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13387         !var->hasInit()) {
13388       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13389           << 1 /*Init*/;
13390       var->setInvalidDecl();
13391       return;
13392     }
13393   }
13394 
13395   // In Objective-C, don't allow jumps past the implicit initialization of a
13396   // local retaining variable.
13397   if (getLangOpts().ObjC &&
13398       var->hasLocalStorage()) {
13399     switch (var->getType().getObjCLifetime()) {
13400     case Qualifiers::OCL_None:
13401     case Qualifiers::OCL_ExplicitNone:
13402     case Qualifiers::OCL_Autoreleasing:
13403       break;
13404 
13405     case Qualifiers::OCL_Weak:
13406     case Qualifiers::OCL_Strong:
13407       setFunctionHasBranchProtectedScope();
13408       break;
13409     }
13410   }
13411 
13412   if (var->hasLocalStorage() &&
13413       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13414     setFunctionHasBranchProtectedScope();
13415 
13416   // Warn about externally-visible variables being defined without a
13417   // prior declaration.  We only want to do this for global
13418   // declarations, but we also specifically need to avoid doing it for
13419   // class members because the linkage of an anonymous class can
13420   // change if it's later given a typedef name.
13421   if (var->isThisDeclarationADefinition() &&
13422       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13423       var->isExternallyVisible() && var->hasLinkage() &&
13424       !var->isInline() && !var->getDescribedVarTemplate() &&
13425       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13426       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13427       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13428                                   var->getLocation())) {
13429     // Find a previous declaration that's not a definition.
13430     VarDecl *prev = var->getPreviousDecl();
13431     while (prev && prev->isThisDeclarationADefinition())
13432       prev = prev->getPreviousDecl();
13433 
13434     if (!prev) {
13435       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13436       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13437           << /* variable */ 0;
13438     }
13439   }
13440 
13441   // Cache the result of checking for constant initialization.
13442   Optional<bool> CacheHasConstInit;
13443   const Expr *CacheCulprit = nullptr;
13444   auto checkConstInit = [&]() mutable {
13445     if (!CacheHasConstInit)
13446       CacheHasConstInit = var->getInit()->isConstantInitializer(
13447             Context, var->getType()->isReferenceType(), &CacheCulprit);
13448     return *CacheHasConstInit;
13449   };
13450 
13451   if (var->getTLSKind() == VarDecl::TLS_Static) {
13452     if (var->getType().isDestructedType()) {
13453       // GNU C++98 edits for __thread, [basic.start.term]p3:
13454       //   The type of an object with thread storage duration shall not
13455       //   have a non-trivial destructor.
13456       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13457       if (getLangOpts().CPlusPlus11)
13458         Diag(var->getLocation(), diag::note_use_thread_local);
13459     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13460       if (!checkConstInit()) {
13461         // GNU C++98 edits for __thread, [basic.start.init]p4:
13462         //   An object of thread storage duration shall not require dynamic
13463         //   initialization.
13464         // FIXME: Need strict checking here.
13465         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13466           << CacheCulprit->getSourceRange();
13467         if (getLangOpts().CPlusPlus11)
13468           Diag(var->getLocation(), diag::note_use_thread_local);
13469       }
13470     }
13471   }
13472 
13473 
13474   if (!var->getType()->isStructureType() && var->hasInit() &&
13475       isa<InitListExpr>(var->getInit())) {
13476     const auto *ILE = cast<InitListExpr>(var->getInit());
13477     unsigned NumInits = ILE->getNumInits();
13478     if (NumInits > 2)
13479       for (unsigned I = 0; I < NumInits; ++I) {
13480         const auto *Init = ILE->getInit(I);
13481         if (!Init)
13482           break;
13483         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13484         if (!SL)
13485           break;
13486 
13487         unsigned NumConcat = SL->getNumConcatenated();
13488         // Diagnose missing comma in string array initialization.
13489         // Do not warn when all the elements in the initializer are concatenated
13490         // together. Do not warn for macros too.
13491         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13492           bool OnlyOneMissingComma = true;
13493           for (unsigned J = I + 1; J < NumInits; ++J) {
13494             const auto *Init = ILE->getInit(J);
13495             if (!Init)
13496               break;
13497             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13498             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13499               OnlyOneMissingComma = false;
13500               break;
13501             }
13502           }
13503 
13504           if (OnlyOneMissingComma) {
13505             SmallVector<FixItHint, 1> Hints;
13506             for (unsigned i = 0; i < NumConcat - 1; ++i)
13507               Hints.push_back(FixItHint::CreateInsertion(
13508                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13509 
13510             Diag(SL->getStrTokenLoc(1),
13511                  diag::warn_concatenated_literal_array_init)
13512                 << Hints;
13513             Diag(SL->getBeginLoc(),
13514                  diag::note_concatenated_string_literal_silence);
13515           }
13516           // In any case, stop now.
13517           break;
13518         }
13519       }
13520   }
13521 
13522 
13523   QualType type = var->getType();
13524 
13525   if (var->hasAttr<BlocksAttr>())
13526     getCurFunction()->addByrefBlockVar(var);
13527 
13528   Expr *Init = var->getInit();
13529   bool GlobalStorage = var->hasGlobalStorage();
13530   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13531   QualType baseType = Context.getBaseElementType(type);
13532   bool HasConstInit = true;
13533 
13534   // Check whether the initializer is sufficiently constant.
13535   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13536       !Init->isValueDependent() &&
13537       (GlobalStorage || var->isConstexpr() ||
13538        var->mightBeUsableInConstantExpressions(Context))) {
13539     // If this variable might have a constant initializer or might be usable in
13540     // constant expressions, check whether or not it actually is now.  We can't
13541     // do this lazily, because the result might depend on things that change
13542     // later, such as which constexpr functions happen to be defined.
13543     SmallVector<PartialDiagnosticAt, 8> Notes;
13544     if (!getLangOpts().CPlusPlus11) {
13545       // Prior to C++11, in contexts where a constant initializer is required,
13546       // the set of valid constant initializers is described by syntactic rules
13547       // in [expr.const]p2-6.
13548       // FIXME: Stricter checking for these rules would be useful for constinit /
13549       // -Wglobal-constructors.
13550       HasConstInit = checkConstInit();
13551 
13552       // Compute and cache the constant value, and remember that we have a
13553       // constant initializer.
13554       if (HasConstInit) {
13555         (void)var->checkForConstantInitialization(Notes);
13556         Notes.clear();
13557       } else if (CacheCulprit) {
13558         Notes.emplace_back(CacheCulprit->getExprLoc(),
13559                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13560         Notes.back().second << CacheCulprit->getSourceRange();
13561       }
13562     } else {
13563       // Evaluate the initializer to see if it's a constant initializer.
13564       HasConstInit = var->checkForConstantInitialization(Notes);
13565     }
13566 
13567     if (HasConstInit) {
13568       // FIXME: Consider replacing the initializer with a ConstantExpr.
13569     } else if (var->isConstexpr()) {
13570       SourceLocation DiagLoc = var->getLocation();
13571       // If the note doesn't add any useful information other than a source
13572       // location, fold it into the primary diagnostic.
13573       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13574                                    diag::note_invalid_subexpr_in_const_expr) {
13575         DiagLoc = Notes[0].first;
13576         Notes.clear();
13577       }
13578       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13579           << var << Init->getSourceRange();
13580       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13581         Diag(Notes[I].first, Notes[I].second);
13582     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13583       auto *Attr = var->getAttr<ConstInitAttr>();
13584       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13585           << Init->getSourceRange();
13586       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13587           << Attr->getRange() << Attr->isConstinit();
13588       for (auto &it : Notes)
13589         Diag(it.first, it.second);
13590     } else if (IsGlobal &&
13591                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13592                                            var->getLocation())) {
13593       // Warn about globals which don't have a constant initializer.  Don't
13594       // warn about globals with a non-trivial destructor because we already
13595       // warned about them.
13596       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13597       if (!(RD && !RD->hasTrivialDestructor())) {
13598         // checkConstInit() here permits trivial default initialization even in
13599         // C++11 onwards, where such an initializer is not a constant initializer
13600         // but nonetheless doesn't require a global constructor.
13601         if (!checkConstInit())
13602           Diag(var->getLocation(), diag::warn_global_constructor)
13603               << Init->getSourceRange();
13604       }
13605     }
13606   }
13607 
13608   // Apply section attributes and pragmas to global variables.
13609   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13610       !inTemplateInstantiation()) {
13611     PragmaStack<StringLiteral *> *Stack = nullptr;
13612     int SectionFlags = ASTContext::PSF_Read;
13613     if (var->getType().isConstQualified()) {
13614       if (HasConstInit)
13615         Stack = &ConstSegStack;
13616       else {
13617         Stack = &BSSSegStack;
13618         SectionFlags |= ASTContext::PSF_Write;
13619       }
13620     } else if (var->hasInit() && HasConstInit) {
13621       Stack = &DataSegStack;
13622       SectionFlags |= ASTContext::PSF_Write;
13623     } else {
13624       Stack = &BSSSegStack;
13625       SectionFlags |= ASTContext::PSF_Write;
13626     }
13627     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13628       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13629         SectionFlags |= ASTContext::PSF_Implicit;
13630       UnifySection(SA->getName(), SectionFlags, var);
13631     } else if (Stack->CurrentValue) {
13632       SectionFlags |= ASTContext::PSF_Implicit;
13633       auto SectionName = Stack->CurrentValue->getString();
13634       var->addAttr(SectionAttr::CreateImplicit(
13635           Context, SectionName, Stack->CurrentPragmaLocation,
13636           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13637       if (UnifySection(SectionName, SectionFlags, var))
13638         var->dropAttr<SectionAttr>();
13639     }
13640 
13641     // Apply the init_seg attribute if this has an initializer.  If the
13642     // initializer turns out to not be dynamic, we'll end up ignoring this
13643     // attribute.
13644     if (CurInitSeg && var->getInit())
13645       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13646                                                CurInitSegLoc,
13647                                                AttributeCommonInfo::AS_Pragma));
13648   }
13649 
13650   // All the following checks are C++ only.
13651   if (!getLangOpts().CPlusPlus) {
13652     // If this variable must be emitted, add it as an initializer for the
13653     // current module.
13654     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13655       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13656     return;
13657   }
13658 
13659   // Require the destructor.
13660   if (!type->isDependentType())
13661     if (const RecordType *recordType = baseType->getAs<RecordType>())
13662       FinalizeVarWithDestructor(var, recordType);
13663 
13664   // If this variable must be emitted, add it as an initializer for the current
13665   // module.
13666   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13667     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13668 
13669   // Build the bindings if this is a structured binding declaration.
13670   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13671     CheckCompleteDecompositionDeclaration(DD);
13672 }
13673 
13674 /// Check if VD needs to be dllexport/dllimport due to being in a
13675 /// dllexport/import function.
13676 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13677   assert(VD->isStaticLocal());
13678 
13679   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13680 
13681   // Find outermost function when VD is in lambda function.
13682   while (FD && !getDLLAttr(FD) &&
13683          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13684          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13685     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13686   }
13687 
13688   if (!FD)
13689     return;
13690 
13691   // Static locals inherit dll attributes from their function.
13692   if (Attr *A = getDLLAttr(FD)) {
13693     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13694     NewAttr->setInherited(true);
13695     VD->addAttr(NewAttr);
13696   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13697     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13698     NewAttr->setInherited(true);
13699     VD->addAttr(NewAttr);
13700 
13701     // Export this function to enforce exporting this static variable even
13702     // if it is not used in this compilation unit.
13703     if (!FD->hasAttr<DLLExportAttr>())
13704       FD->addAttr(NewAttr);
13705 
13706   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13707     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13708     NewAttr->setInherited(true);
13709     VD->addAttr(NewAttr);
13710   }
13711 }
13712 
13713 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13714 /// any semantic actions necessary after any initializer has been attached.
13715 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13716   // Note that we are no longer parsing the initializer for this declaration.
13717   ParsingInitForAutoVars.erase(ThisDecl);
13718 
13719   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13720   if (!VD)
13721     return;
13722 
13723   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13724   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13725       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13726     if (PragmaClangBSSSection.Valid)
13727       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13728           Context, PragmaClangBSSSection.SectionName,
13729           PragmaClangBSSSection.PragmaLocation,
13730           AttributeCommonInfo::AS_Pragma));
13731     if (PragmaClangDataSection.Valid)
13732       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13733           Context, PragmaClangDataSection.SectionName,
13734           PragmaClangDataSection.PragmaLocation,
13735           AttributeCommonInfo::AS_Pragma));
13736     if (PragmaClangRodataSection.Valid)
13737       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13738           Context, PragmaClangRodataSection.SectionName,
13739           PragmaClangRodataSection.PragmaLocation,
13740           AttributeCommonInfo::AS_Pragma));
13741     if (PragmaClangRelroSection.Valid)
13742       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13743           Context, PragmaClangRelroSection.SectionName,
13744           PragmaClangRelroSection.PragmaLocation,
13745           AttributeCommonInfo::AS_Pragma));
13746   }
13747 
13748   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13749     for (auto *BD : DD->bindings()) {
13750       FinalizeDeclaration(BD);
13751     }
13752   }
13753 
13754   checkAttributesAfterMerging(*this, *VD);
13755 
13756   // Perform TLS alignment check here after attributes attached to the variable
13757   // which may affect the alignment have been processed. Only perform the check
13758   // if the target has a maximum TLS alignment (zero means no constraints).
13759   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13760     // Protect the check so that it's not performed on dependent types and
13761     // dependent alignments (we can't determine the alignment in that case).
13762     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13763       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13764       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13765         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13766           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13767           << (unsigned)MaxAlignChars.getQuantity();
13768       }
13769     }
13770   }
13771 
13772   if (VD->isStaticLocal())
13773     CheckStaticLocalForDllExport(VD);
13774 
13775   // Perform check for initializers of device-side global variables.
13776   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13777   // 7.5). We must also apply the same checks to all __shared__
13778   // variables whether they are local or not. CUDA also allows
13779   // constant initializers for __constant__ and __device__ variables.
13780   if (getLangOpts().CUDA)
13781     checkAllowedCUDAInitializer(VD);
13782 
13783   // Grab the dllimport or dllexport attribute off of the VarDecl.
13784   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13785 
13786   // Imported static data members cannot be defined out-of-line.
13787   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13788     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13789         VD->isThisDeclarationADefinition()) {
13790       // We allow definitions of dllimport class template static data members
13791       // with a warning.
13792       CXXRecordDecl *Context =
13793         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13794       bool IsClassTemplateMember =
13795           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13796           Context->getDescribedClassTemplate();
13797 
13798       Diag(VD->getLocation(),
13799            IsClassTemplateMember
13800                ? diag::warn_attribute_dllimport_static_field_definition
13801                : diag::err_attribute_dllimport_static_field_definition);
13802       Diag(IA->getLocation(), diag::note_attribute);
13803       if (!IsClassTemplateMember)
13804         VD->setInvalidDecl();
13805     }
13806   }
13807 
13808   // dllimport/dllexport variables cannot be thread local, their TLS index
13809   // isn't exported with the variable.
13810   if (DLLAttr && VD->getTLSKind()) {
13811     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13812     if (F && getDLLAttr(F)) {
13813       assert(VD->isStaticLocal());
13814       // But if this is a static local in a dlimport/dllexport function, the
13815       // function will never be inlined, which means the var would never be
13816       // imported, so having it marked import/export is safe.
13817     } else {
13818       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13819                                                                     << DLLAttr;
13820       VD->setInvalidDecl();
13821     }
13822   }
13823 
13824   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13825     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13826       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13827           << Attr;
13828       VD->dropAttr<UsedAttr>();
13829     }
13830   }
13831   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13832     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13833       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13834           << Attr;
13835       VD->dropAttr<RetainAttr>();
13836     }
13837   }
13838 
13839   const DeclContext *DC = VD->getDeclContext();
13840   // If there's a #pragma GCC visibility in scope, and this isn't a class
13841   // member, set the visibility of this variable.
13842   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13843     AddPushedVisibilityAttribute(VD);
13844 
13845   // FIXME: Warn on unused var template partial specializations.
13846   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13847     MarkUnusedFileScopedDecl(VD);
13848 
13849   // Now we have parsed the initializer and can update the table of magic
13850   // tag values.
13851   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13852       !VD->getType()->isIntegralOrEnumerationType())
13853     return;
13854 
13855   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13856     const Expr *MagicValueExpr = VD->getInit();
13857     if (!MagicValueExpr) {
13858       continue;
13859     }
13860     Optional<llvm::APSInt> MagicValueInt;
13861     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13862       Diag(I->getRange().getBegin(),
13863            diag::err_type_tag_for_datatype_not_ice)
13864         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13865       continue;
13866     }
13867     if (MagicValueInt->getActiveBits() > 64) {
13868       Diag(I->getRange().getBegin(),
13869            diag::err_type_tag_for_datatype_too_large)
13870         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13871       continue;
13872     }
13873     uint64_t MagicValue = MagicValueInt->getZExtValue();
13874     RegisterTypeTagForDatatype(I->getArgumentKind(),
13875                                MagicValue,
13876                                I->getMatchingCType(),
13877                                I->getLayoutCompatible(),
13878                                I->getMustBeNull());
13879   }
13880 }
13881 
13882 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13883   auto *VD = dyn_cast<VarDecl>(DD);
13884   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13885 }
13886 
13887 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13888                                                    ArrayRef<Decl *> Group) {
13889   SmallVector<Decl*, 8> Decls;
13890 
13891   if (DS.isTypeSpecOwned())
13892     Decls.push_back(DS.getRepAsDecl());
13893 
13894   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13895   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13896   bool DiagnosedMultipleDecomps = false;
13897   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13898   bool DiagnosedNonDeducedAuto = false;
13899 
13900   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13901     if (Decl *D = Group[i]) {
13902       // For declarators, there are some additional syntactic-ish checks we need
13903       // to perform.
13904       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13905         if (!FirstDeclaratorInGroup)
13906           FirstDeclaratorInGroup = DD;
13907         if (!FirstDecompDeclaratorInGroup)
13908           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13909         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13910             !hasDeducedAuto(DD))
13911           FirstNonDeducedAutoInGroup = DD;
13912 
13913         if (FirstDeclaratorInGroup != DD) {
13914           // A decomposition declaration cannot be combined with any other
13915           // declaration in the same group.
13916           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13917             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13918                  diag::err_decomp_decl_not_alone)
13919                 << FirstDeclaratorInGroup->getSourceRange()
13920                 << DD->getSourceRange();
13921             DiagnosedMultipleDecomps = true;
13922           }
13923 
13924           // A declarator that uses 'auto' in any way other than to declare a
13925           // variable with a deduced type cannot be combined with any other
13926           // declarator in the same group.
13927           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13928             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13929                  diag::err_auto_non_deduced_not_alone)
13930                 << FirstNonDeducedAutoInGroup->getType()
13931                        ->hasAutoForTrailingReturnType()
13932                 << FirstDeclaratorInGroup->getSourceRange()
13933                 << DD->getSourceRange();
13934             DiagnosedNonDeducedAuto = true;
13935           }
13936         }
13937       }
13938 
13939       Decls.push_back(D);
13940     }
13941   }
13942 
13943   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13944     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13945       handleTagNumbering(Tag, S);
13946       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13947           getLangOpts().CPlusPlus)
13948         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13949     }
13950   }
13951 
13952   return BuildDeclaratorGroup(Decls);
13953 }
13954 
13955 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13956 /// group, performing any necessary semantic checking.
13957 Sema::DeclGroupPtrTy
13958 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13959   // C++14 [dcl.spec.auto]p7: (DR1347)
13960   //   If the type that replaces the placeholder type is not the same in each
13961   //   deduction, the program is ill-formed.
13962   if (Group.size() > 1) {
13963     QualType Deduced;
13964     VarDecl *DeducedDecl = nullptr;
13965     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13966       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13967       if (!D || D->isInvalidDecl())
13968         break;
13969       DeducedType *DT = D->getType()->getContainedDeducedType();
13970       if (!DT || DT->getDeducedType().isNull())
13971         continue;
13972       if (Deduced.isNull()) {
13973         Deduced = DT->getDeducedType();
13974         DeducedDecl = D;
13975       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13976         auto *AT = dyn_cast<AutoType>(DT);
13977         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13978                         diag::err_auto_different_deductions)
13979                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13980                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13981                    << D->getDeclName();
13982         if (DeducedDecl->hasInit())
13983           Dia << DeducedDecl->getInit()->getSourceRange();
13984         if (D->getInit())
13985           Dia << D->getInit()->getSourceRange();
13986         D->setInvalidDecl();
13987         break;
13988       }
13989     }
13990   }
13991 
13992   ActOnDocumentableDecls(Group);
13993 
13994   return DeclGroupPtrTy::make(
13995       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13996 }
13997 
13998 void Sema::ActOnDocumentableDecl(Decl *D) {
13999   ActOnDocumentableDecls(D);
14000 }
14001 
14002 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14003   // Don't parse the comment if Doxygen diagnostics are ignored.
14004   if (Group.empty() || !Group[0])
14005     return;
14006 
14007   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14008                       Group[0]->getLocation()) &&
14009       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14010                       Group[0]->getLocation()))
14011     return;
14012 
14013   if (Group.size() >= 2) {
14014     // This is a decl group.  Normally it will contain only declarations
14015     // produced from declarator list.  But in case we have any definitions or
14016     // additional declaration references:
14017     //   'typedef struct S {} S;'
14018     //   'typedef struct S *S;'
14019     //   'struct S *pS;'
14020     // FinalizeDeclaratorGroup adds these as separate declarations.
14021     Decl *MaybeTagDecl = Group[0];
14022     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14023       Group = Group.slice(1);
14024     }
14025   }
14026 
14027   // FIMXE: We assume every Decl in the group is in the same file.
14028   // This is false when preprocessor constructs the group from decls in
14029   // different files (e. g. macros or #include).
14030   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14031 }
14032 
14033 /// Common checks for a parameter-declaration that should apply to both function
14034 /// parameters and non-type template parameters.
14035 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14036   // Check that there are no default arguments inside the type of this
14037   // parameter.
14038   if (getLangOpts().CPlusPlus)
14039     CheckExtraCXXDefaultArguments(D);
14040 
14041   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14042   if (D.getCXXScopeSpec().isSet()) {
14043     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14044       << D.getCXXScopeSpec().getRange();
14045   }
14046 
14047   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14048   // simple identifier except [...irrelevant cases...].
14049   switch (D.getName().getKind()) {
14050   case UnqualifiedIdKind::IK_Identifier:
14051     break;
14052 
14053   case UnqualifiedIdKind::IK_OperatorFunctionId:
14054   case UnqualifiedIdKind::IK_ConversionFunctionId:
14055   case UnqualifiedIdKind::IK_LiteralOperatorId:
14056   case UnqualifiedIdKind::IK_ConstructorName:
14057   case UnqualifiedIdKind::IK_DestructorName:
14058   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14059   case UnqualifiedIdKind::IK_DeductionGuideName:
14060     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14061       << GetNameForDeclarator(D).getName();
14062     break;
14063 
14064   case UnqualifiedIdKind::IK_TemplateId:
14065   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14066     // GetNameForDeclarator would not produce a useful name in this case.
14067     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14068     break;
14069   }
14070 }
14071 
14072 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14073 /// to introduce parameters into function prototype scope.
14074 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14075   const DeclSpec &DS = D.getDeclSpec();
14076 
14077   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14078 
14079   // C++03 [dcl.stc]p2 also permits 'auto'.
14080   StorageClass SC = SC_None;
14081   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14082     SC = SC_Register;
14083     // In C++11, the 'register' storage class specifier is deprecated.
14084     // In C++17, it is not allowed, but we tolerate it as an extension.
14085     if (getLangOpts().CPlusPlus11) {
14086       Diag(DS.getStorageClassSpecLoc(),
14087            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14088                                      : diag::warn_deprecated_register)
14089         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14090     }
14091   } else if (getLangOpts().CPlusPlus &&
14092              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14093     SC = SC_Auto;
14094   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14095     Diag(DS.getStorageClassSpecLoc(),
14096          diag::err_invalid_storage_class_in_func_decl);
14097     D.getMutableDeclSpec().ClearStorageClassSpecs();
14098   }
14099 
14100   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14101     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14102       << DeclSpec::getSpecifierName(TSCS);
14103   if (DS.isInlineSpecified())
14104     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14105         << getLangOpts().CPlusPlus17;
14106   if (DS.hasConstexprSpecifier())
14107     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14108         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14109 
14110   DiagnoseFunctionSpecifiers(DS);
14111 
14112   CheckFunctionOrTemplateParamDeclarator(S, D);
14113 
14114   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14115   QualType parmDeclType = TInfo->getType();
14116 
14117   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14118   IdentifierInfo *II = D.getIdentifier();
14119   if (II) {
14120     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14121                    ForVisibleRedeclaration);
14122     LookupName(R, S);
14123     if (R.isSingleResult()) {
14124       NamedDecl *PrevDecl = R.getFoundDecl();
14125       if (PrevDecl->isTemplateParameter()) {
14126         // Maybe we will complain about the shadowed template parameter.
14127         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14128         // Just pretend that we didn't see the previous declaration.
14129         PrevDecl = nullptr;
14130       } else if (S->isDeclScope(PrevDecl)) {
14131         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14132         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14133 
14134         // Recover by removing the name
14135         II = nullptr;
14136         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14137         D.setInvalidType(true);
14138       }
14139     }
14140   }
14141 
14142   // Temporarily put parameter variables in the translation unit, not
14143   // the enclosing context.  This prevents them from accidentally
14144   // looking like class members in C++.
14145   ParmVarDecl *New =
14146       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14147                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14148 
14149   if (D.isInvalidType())
14150     New->setInvalidDecl();
14151 
14152   assert(S->isFunctionPrototypeScope());
14153   assert(S->getFunctionPrototypeDepth() >= 1);
14154   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14155                     S->getNextFunctionPrototypeIndex());
14156 
14157   // Add the parameter declaration into this scope.
14158   S->AddDecl(New);
14159   if (II)
14160     IdResolver.AddDecl(New);
14161 
14162   ProcessDeclAttributes(S, New, D);
14163 
14164   if (D.getDeclSpec().isModulePrivateSpecified())
14165     Diag(New->getLocation(), diag::err_module_private_local)
14166         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14167         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14168 
14169   if (New->hasAttr<BlocksAttr>()) {
14170     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14171   }
14172 
14173   if (getLangOpts().OpenCL)
14174     deduceOpenCLAddressSpace(New);
14175 
14176   return New;
14177 }
14178 
14179 /// Synthesizes a variable for a parameter arising from a
14180 /// typedef.
14181 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14182                                               SourceLocation Loc,
14183                                               QualType T) {
14184   /* FIXME: setting StartLoc == Loc.
14185      Would it be worth to modify callers so as to provide proper source
14186      location for the unnamed parameters, embedding the parameter's type? */
14187   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14188                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14189                                            SC_None, nullptr);
14190   Param->setImplicit();
14191   return Param;
14192 }
14193 
14194 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14195   // Don't diagnose unused-parameter errors in template instantiations; we
14196   // will already have done so in the template itself.
14197   if (inTemplateInstantiation())
14198     return;
14199 
14200   for (const ParmVarDecl *Parameter : Parameters) {
14201     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14202         !Parameter->hasAttr<UnusedAttr>()) {
14203       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14204         << Parameter->getDeclName();
14205     }
14206   }
14207 }
14208 
14209 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14210     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14211   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14212     return;
14213 
14214   // Warn if the return value is pass-by-value and larger than the specified
14215   // threshold.
14216   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14217     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14218     if (Size > LangOpts.NumLargeByValueCopy)
14219       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14220   }
14221 
14222   // Warn if any parameter is pass-by-value and larger than the specified
14223   // threshold.
14224   for (const ParmVarDecl *Parameter : Parameters) {
14225     QualType T = Parameter->getType();
14226     if (T->isDependentType() || !T.isPODType(Context))
14227       continue;
14228     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14229     if (Size > LangOpts.NumLargeByValueCopy)
14230       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14231           << Parameter << Size;
14232   }
14233 }
14234 
14235 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14236                                   SourceLocation NameLoc, IdentifierInfo *Name,
14237                                   QualType T, TypeSourceInfo *TSInfo,
14238                                   StorageClass SC) {
14239   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14240   if (getLangOpts().ObjCAutoRefCount &&
14241       T.getObjCLifetime() == Qualifiers::OCL_None &&
14242       T->isObjCLifetimeType()) {
14243 
14244     Qualifiers::ObjCLifetime lifetime;
14245 
14246     // Special cases for arrays:
14247     //   - if it's const, use __unsafe_unretained
14248     //   - otherwise, it's an error
14249     if (T->isArrayType()) {
14250       if (!T.isConstQualified()) {
14251         if (DelayedDiagnostics.shouldDelayDiagnostics())
14252           DelayedDiagnostics.add(
14253               sema::DelayedDiagnostic::makeForbiddenType(
14254               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14255         else
14256           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14257               << TSInfo->getTypeLoc().getSourceRange();
14258       }
14259       lifetime = Qualifiers::OCL_ExplicitNone;
14260     } else {
14261       lifetime = T->getObjCARCImplicitLifetime();
14262     }
14263     T = Context.getLifetimeQualifiedType(T, lifetime);
14264   }
14265 
14266   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14267                                          Context.getAdjustedParameterType(T),
14268                                          TSInfo, SC, nullptr);
14269 
14270   // Make a note if we created a new pack in the scope of a lambda, so that
14271   // we know that references to that pack must also be expanded within the
14272   // lambda scope.
14273   if (New->isParameterPack())
14274     if (auto *LSI = getEnclosingLambda())
14275       LSI->LocalPacks.push_back(New);
14276 
14277   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14278       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14279     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14280                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14281 
14282   // Parameters can not be abstract class types.
14283   // For record types, this is done by the AbstractClassUsageDiagnoser once
14284   // the class has been completely parsed.
14285   if (!CurContext->isRecord() &&
14286       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14287                              AbstractParamType))
14288     New->setInvalidDecl();
14289 
14290   // Parameter declarators cannot be interface types. All ObjC objects are
14291   // passed by reference.
14292   if (T->isObjCObjectType()) {
14293     SourceLocation TypeEndLoc =
14294         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14295     Diag(NameLoc,
14296          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14297       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14298     T = Context.getObjCObjectPointerType(T);
14299     New->setType(T);
14300   }
14301 
14302   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14303   // duration shall not be qualified by an address-space qualifier."
14304   // Since all parameters have automatic store duration, they can not have
14305   // an address space.
14306   if (T.getAddressSpace() != LangAS::Default &&
14307       // OpenCL allows function arguments declared to be an array of a type
14308       // to be qualified with an address space.
14309       !(getLangOpts().OpenCL &&
14310         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14311     Diag(NameLoc, diag::err_arg_with_address_space);
14312     New->setInvalidDecl();
14313   }
14314 
14315   // PPC MMA non-pointer types are not allowed as function argument types.
14316   if (Context.getTargetInfo().getTriple().isPPC64() &&
14317       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14318     New->setInvalidDecl();
14319   }
14320 
14321   return New;
14322 }
14323 
14324 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14325                                            SourceLocation LocAfterDecls) {
14326   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14327 
14328   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14329   // in the declaration list shall have at least one declarator, those
14330   // declarators shall only declare identifiers from the identifier list, and
14331   // every identifier in the identifier list shall be declared.
14332   //
14333   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14334   // identifiers it names shall be declared in the declaration list."
14335   //
14336   // This is why we only diagnose in C99 and later. Note, the other conditions
14337   // listed are checked elsewhere.
14338   if (!FTI.hasPrototype) {
14339     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14340       --i;
14341       if (FTI.Params[i].Param == nullptr) {
14342         if (getLangOpts().C99) {
14343           SmallString<256> Code;
14344           llvm::raw_svector_ostream(Code)
14345               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14346           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14347               << FTI.Params[i].Ident
14348               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14349         }
14350 
14351         // Implicitly declare the argument as type 'int' for lack of a better
14352         // type.
14353         AttributeFactory attrs;
14354         DeclSpec DS(attrs);
14355         const char* PrevSpec; // unused
14356         unsigned DiagID; // unused
14357         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14358                            DiagID, Context.getPrintingPolicy());
14359         // Use the identifier location for the type source range.
14360         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14361         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14362         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14363         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14364         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14365       }
14366     }
14367   }
14368 }
14369 
14370 Decl *
14371 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14372                               MultiTemplateParamsArg TemplateParameterLists,
14373                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14374   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14375   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14376   Scope *ParentScope = FnBodyScope->getParent();
14377 
14378   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14379   // we define a non-templated function definition, we will create a declaration
14380   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14381   // The base function declaration will have the equivalent of an `omp declare
14382   // variant` annotation which specifies the mangled definition as a
14383   // specialization function under the OpenMP context defined as part of the
14384   // `omp begin declare variant`.
14385   SmallVector<FunctionDecl *, 4> Bases;
14386   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14387     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14388         ParentScope, D, TemplateParameterLists, Bases);
14389 
14390   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14391   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14392   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14393 
14394   if (!Bases.empty())
14395     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14396 
14397   return Dcl;
14398 }
14399 
14400 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14401   Consumer.HandleInlineFunctionDefinition(D);
14402 }
14403 
14404 static bool
14405 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14406                                 const FunctionDecl *&PossiblePrototype) {
14407   // Don't warn about invalid declarations.
14408   if (FD->isInvalidDecl())
14409     return false;
14410 
14411   // Or declarations that aren't global.
14412   if (!FD->isGlobal())
14413     return false;
14414 
14415   // Don't warn about C++ member functions.
14416   if (isa<CXXMethodDecl>(FD))
14417     return false;
14418 
14419   // Don't warn about 'main'.
14420   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14421     if (IdentifierInfo *II = FD->getIdentifier())
14422       if (II->isStr("main") || II->isStr("efi_main"))
14423         return false;
14424 
14425   // Don't warn about inline functions.
14426   if (FD->isInlined())
14427     return false;
14428 
14429   // Don't warn about function templates.
14430   if (FD->getDescribedFunctionTemplate())
14431     return false;
14432 
14433   // Don't warn about function template specializations.
14434   if (FD->isFunctionTemplateSpecialization())
14435     return false;
14436 
14437   // Don't warn for OpenCL kernels.
14438   if (FD->hasAttr<OpenCLKernelAttr>())
14439     return false;
14440 
14441   // Don't warn on explicitly deleted functions.
14442   if (FD->isDeleted())
14443     return false;
14444 
14445   // Don't warn on implicitly local functions (such as having local-typed
14446   // parameters).
14447   if (!FD->isExternallyVisible())
14448     return false;
14449 
14450   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14451        Prev; Prev = Prev->getPreviousDecl()) {
14452     // Ignore any declarations that occur in function or method
14453     // scope, because they aren't visible from the header.
14454     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14455       continue;
14456 
14457     PossiblePrototype = Prev;
14458     return Prev->getType()->isFunctionNoProtoType();
14459   }
14460 
14461   return true;
14462 }
14463 
14464 void
14465 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14466                                    const FunctionDecl *EffectiveDefinition,
14467                                    SkipBodyInfo *SkipBody) {
14468   const FunctionDecl *Definition = EffectiveDefinition;
14469   if (!Definition &&
14470       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14471     return;
14472 
14473   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14474     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14475       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14476         // A merged copy of the same function, instantiated as a member of
14477         // the same class, is OK.
14478         if (declaresSameEntity(OrigFD, OrigDef) &&
14479             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14480                                cast<Decl>(FD->getLexicalDeclContext())))
14481           return;
14482       }
14483     }
14484   }
14485 
14486   if (canRedefineFunction(Definition, getLangOpts()))
14487     return;
14488 
14489   // Don't emit an error when this is redefinition of a typo-corrected
14490   // definition.
14491   if (TypoCorrectedFunctionDefinitions.count(Definition))
14492     return;
14493 
14494   // If we don't have a visible definition of the function, and it's inline or
14495   // a template, skip the new definition.
14496   if (SkipBody && !hasVisibleDefinition(Definition) &&
14497       (Definition->getFormalLinkage() == InternalLinkage ||
14498        Definition->isInlined() ||
14499        Definition->getDescribedFunctionTemplate() ||
14500        Definition->getNumTemplateParameterLists())) {
14501     SkipBody->ShouldSkip = true;
14502     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14503     if (auto *TD = Definition->getDescribedFunctionTemplate())
14504       makeMergedDefinitionVisible(TD);
14505     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14506     return;
14507   }
14508 
14509   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14510       Definition->getStorageClass() == SC_Extern)
14511     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14512         << FD << getLangOpts().CPlusPlus;
14513   else
14514     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14515 
14516   Diag(Definition->getLocation(), diag::note_previous_definition);
14517   FD->setInvalidDecl();
14518 }
14519 
14520 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14521                                    Sema &S) {
14522   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14523 
14524   LambdaScopeInfo *LSI = S.PushLambdaScope();
14525   LSI->CallOperator = CallOperator;
14526   LSI->Lambda = LambdaClass;
14527   LSI->ReturnType = CallOperator->getReturnType();
14528   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14529 
14530   if (LCD == LCD_None)
14531     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14532   else if (LCD == LCD_ByCopy)
14533     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14534   else if (LCD == LCD_ByRef)
14535     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14536   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14537 
14538   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14539   LSI->Mutable = !CallOperator->isConst();
14540 
14541   // Add the captures to the LSI so they can be noted as already
14542   // captured within tryCaptureVar.
14543   auto I = LambdaClass->field_begin();
14544   for (const auto &C : LambdaClass->captures()) {
14545     if (C.capturesVariable()) {
14546       VarDecl *VD = C.getCapturedVar();
14547       if (VD->isInitCapture())
14548         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14549       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14550       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14551           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14552           /*EllipsisLoc*/C.isPackExpansion()
14553                          ? C.getEllipsisLoc() : SourceLocation(),
14554           I->getType(), /*Invalid*/false);
14555 
14556     } else if (C.capturesThis()) {
14557       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14558                           C.getCaptureKind() == LCK_StarThis);
14559     } else {
14560       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14561                              I->getType());
14562     }
14563     ++I;
14564   }
14565 }
14566 
14567 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14568                                     SkipBodyInfo *SkipBody,
14569                                     FnBodyKind BodyKind) {
14570   if (!D) {
14571     // Parsing the function declaration failed in some way. Push on a fake scope
14572     // anyway so we can try to parse the function body.
14573     PushFunctionScope();
14574     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14575     return D;
14576   }
14577 
14578   FunctionDecl *FD = nullptr;
14579 
14580   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14581     FD = FunTmpl->getTemplatedDecl();
14582   else
14583     FD = cast<FunctionDecl>(D);
14584 
14585   // Do not push if it is a lambda because one is already pushed when building
14586   // the lambda in ActOnStartOfLambdaDefinition().
14587   if (!isLambdaCallOperator(FD))
14588     PushExpressionEvaluationContext(
14589         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14590                           : ExprEvalContexts.back().Context);
14591 
14592   // Check for defining attributes before the check for redefinition.
14593   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14594     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14595     FD->dropAttr<AliasAttr>();
14596     FD->setInvalidDecl();
14597   }
14598   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14599     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14600     FD->dropAttr<IFuncAttr>();
14601     FD->setInvalidDecl();
14602   }
14603 
14604   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14605     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14606         Ctor->isDefaultConstructor() &&
14607         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14608       // If this is an MS ABI dllexport default constructor, instantiate any
14609       // default arguments.
14610       InstantiateDefaultCtorDefaultArgs(Ctor);
14611     }
14612   }
14613 
14614   // See if this is a redefinition. If 'will have body' (or similar) is already
14615   // set, then these checks were already performed when it was set.
14616   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14617       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14618     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14619 
14620     // If we're skipping the body, we're done. Don't enter the scope.
14621     if (SkipBody && SkipBody->ShouldSkip)
14622       return D;
14623   }
14624 
14625   // Mark this function as "will have a body eventually".  This lets users to
14626   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14627   // this function.
14628   FD->setWillHaveBody();
14629 
14630   // If we are instantiating a generic lambda call operator, push
14631   // a LambdaScopeInfo onto the function stack.  But use the information
14632   // that's already been calculated (ActOnLambdaExpr) to prime the current
14633   // LambdaScopeInfo.
14634   // When the template operator is being specialized, the LambdaScopeInfo,
14635   // has to be properly restored so that tryCaptureVariable doesn't try
14636   // and capture any new variables. In addition when calculating potential
14637   // captures during transformation of nested lambdas, it is necessary to
14638   // have the LSI properly restored.
14639   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14640     assert(inTemplateInstantiation() &&
14641            "There should be an active template instantiation on the stack "
14642            "when instantiating a generic lambda!");
14643     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14644   } else {
14645     // Enter a new function scope
14646     PushFunctionScope();
14647   }
14648 
14649   // Builtin functions cannot be defined.
14650   if (unsigned BuiltinID = FD->getBuiltinID()) {
14651     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14652         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14653       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14654       FD->setInvalidDecl();
14655     }
14656   }
14657 
14658   // The return type of a function definition must be complete (C99 6.9.1p3),
14659   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14660   QualType ResultType = FD->getReturnType();
14661   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14662       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14663       RequireCompleteType(FD->getLocation(), ResultType,
14664                           diag::err_func_def_incomplete_result))
14665     FD->setInvalidDecl();
14666 
14667   if (FnBodyScope)
14668     PushDeclContext(FnBodyScope, FD);
14669 
14670   // Check the validity of our function parameters
14671   if (BodyKind != FnBodyKind::Delete)
14672     CheckParmsForFunctionDef(FD->parameters(),
14673                              /*CheckParameterNames=*/true);
14674 
14675   // Add non-parameter declarations already in the function to the current
14676   // scope.
14677   if (FnBodyScope) {
14678     for (Decl *NPD : FD->decls()) {
14679       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14680       if (!NonParmDecl)
14681         continue;
14682       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14683              "parameters should not be in newly created FD yet");
14684 
14685       // If the decl has a name, make it accessible in the current scope.
14686       if (NonParmDecl->getDeclName())
14687         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14688 
14689       // Similarly, dive into enums and fish their constants out, making them
14690       // accessible in this scope.
14691       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14692         for (auto *EI : ED->enumerators())
14693           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14694       }
14695     }
14696   }
14697 
14698   // Introduce our parameters into the function scope
14699   for (auto Param : FD->parameters()) {
14700     Param->setOwningFunction(FD);
14701 
14702     // If this has an identifier, add it to the scope stack.
14703     if (Param->getIdentifier() && FnBodyScope) {
14704       CheckShadow(FnBodyScope, Param);
14705 
14706       PushOnScopeChains(Param, FnBodyScope);
14707     }
14708   }
14709 
14710   // Ensure that the function's exception specification is instantiated.
14711   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14712     ResolveExceptionSpec(D->getLocation(), FPT);
14713 
14714   // dllimport cannot be applied to non-inline function definitions.
14715   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14716       !FD->isTemplateInstantiation()) {
14717     assert(!FD->hasAttr<DLLExportAttr>());
14718     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14719     FD->setInvalidDecl();
14720     return D;
14721   }
14722   // We want to attach documentation to original Decl (which might be
14723   // a function template).
14724   ActOnDocumentableDecl(D);
14725   if (getCurLexicalContext()->isObjCContainer() &&
14726       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14727       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14728     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14729 
14730   return D;
14731 }
14732 
14733 /// Given the set of return statements within a function body,
14734 /// compute the variables that are subject to the named return value
14735 /// optimization.
14736 ///
14737 /// Each of the variables that is subject to the named return value
14738 /// optimization will be marked as NRVO variables in the AST, and any
14739 /// return statement that has a marked NRVO variable as its NRVO candidate can
14740 /// use the named return value optimization.
14741 ///
14742 /// This function applies a very simplistic algorithm for NRVO: if every return
14743 /// statement in the scope of a variable has the same NRVO candidate, that
14744 /// candidate is an NRVO variable.
14745 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14746   ReturnStmt **Returns = Scope->Returns.data();
14747 
14748   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14749     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14750       if (!NRVOCandidate->isNRVOVariable())
14751         Returns[I]->setNRVOCandidate(nullptr);
14752     }
14753   }
14754 }
14755 
14756 bool Sema::canDelayFunctionBody(const Declarator &D) {
14757   // We can't delay parsing the body of a constexpr function template (yet).
14758   if (D.getDeclSpec().hasConstexprSpecifier())
14759     return false;
14760 
14761   // We can't delay parsing the body of a function template with a deduced
14762   // return type (yet).
14763   if (D.getDeclSpec().hasAutoTypeSpec()) {
14764     // If the placeholder introduces a non-deduced trailing return type,
14765     // we can still delay parsing it.
14766     if (D.getNumTypeObjects()) {
14767       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14768       if (Outer.Kind == DeclaratorChunk::Function &&
14769           Outer.Fun.hasTrailingReturnType()) {
14770         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14771         return Ty.isNull() || !Ty->isUndeducedType();
14772       }
14773     }
14774     return false;
14775   }
14776 
14777   return true;
14778 }
14779 
14780 bool Sema::canSkipFunctionBody(Decl *D) {
14781   // We cannot skip the body of a function (or function template) which is
14782   // constexpr, since we may need to evaluate its body in order to parse the
14783   // rest of the file.
14784   // We cannot skip the body of a function with an undeduced return type,
14785   // because any callers of that function need to know the type.
14786   if (const FunctionDecl *FD = D->getAsFunction()) {
14787     if (FD->isConstexpr())
14788       return false;
14789     // We can't simply call Type::isUndeducedType here, because inside template
14790     // auto can be deduced to a dependent type, which is not considered
14791     // "undeduced".
14792     if (FD->getReturnType()->getContainedDeducedType())
14793       return false;
14794   }
14795   return Consumer.shouldSkipFunctionBody(D);
14796 }
14797 
14798 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14799   if (!Decl)
14800     return nullptr;
14801   if (FunctionDecl *FD = Decl->getAsFunction())
14802     FD->setHasSkippedBody();
14803   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14804     MD->setHasSkippedBody();
14805   return Decl;
14806 }
14807 
14808 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14809   return ActOnFinishFunctionBody(D, BodyArg, false);
14810 }
14811 
14812 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14813 /// body.
14814 class ExitFunctionBodyRAII {
14815 public:
14816   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14817   ~ExitFunctionBodyRAII() {
14818     if (!IsLambda)
14819       S.PopExpressionEvaluationContext();
14820   }
14821 
14822 private:
14823   Sema &S;
14824   bool IsLambda = false;
14825 };
14826 
14827 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14828   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14829 
14830   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14831     if (EscapeInfo.count(BD))
14832       return EscapeInfo[BD];
14833 
14834     bool R = false;
14835     const BlockDecl *CurBD = BD;
14836 
14837     do {
14838       R = !CurBD->doesNotEscape();
14839       if (R)
14840         break;
14841       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14842     } while (CurBD);
14843 
14844     return EscapeInfo[BD] = R;
14845   };
14846 
14847   // If the location where 'self' is implicitly retained is inside a escaping
14848   // block, emit a diagnostic.
14849   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14850        S.ImplicitlyRetainedSelfLocs)
14851     if (IsOrNestedInEscapingBlock(P.second))
14852       S.Diag(P.first, diag::warn_implicitly_retains_self)
14853           << FixItHint::CreateInsertion(P.first, "self->");
14854 }
14855 
14856 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14857                                     bool IsInstantiation) {
14858   FunctionScopeInfo *FSI = getCurFunction();
14859   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14860 
14861   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14862     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14863 
14864   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14865   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14866 
14867   if (getLangOpts().Coroutines && FSI->isCoroutine())
14868     CheckCompletedCoroutineBody(FD, Body);
14869 
14870   {
14871     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14872     // one is already popped when finishing the lambda in BuildLambdaExpr().
14873     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14874     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14875 
14876     if (FD) {
14877       FD->setBody(Body);
14878       FD->setWillHaveBody(false);
14879 
14880       if (getLangOpts().CPlusPlus14) {
14881         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14882             FD->getReturnType()->isUndeducedType()) {
14883           // For a function with a deduced result type to return void,
14884           // the result type as written must be 'auto' or 'decltype(auto)',
14885           // possibly cv-qualified or constrained, but not ref-qualified.
14886           if (!FD->getReturnType()->getAs<AutoType>()) {
14887             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14888                 << FD->getReturnType();
14889             FD->setInvalidDecl();
14890           } else {
14891             // Falling off the end of the function is the same as 'return;'.
14892             Expr *Dummy = nullptr;
14893             if (DeduceFunctionTypeFromReturnExpr(
14894                     FD, dcl->getLocation(), Dummy,
14895                     FD->getReturnType()->getAs<AutoType>()))
14896               FD->setInvalidDecl();
14897           }
14898         }
14899       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14900         // In C++11, we don't use 'auto' deduction rules for lambda call
14901         // operators because we don't support return type deduction.
14902         auto *LSI = getCurLambda();
14903         if (LSI->HasImplicitReturnType) {
14904           deduceClosureReturnType(*LSI);
14905 
14906           // C++11 [expr.prim.lambda]p4:
14907           //   [...] if there are no return statements in the compound-statement
14908           //   [the deduced type is] the type void
14909           QualType RetType =
14910               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14911 
14912           // Update the return type to the deduced type.
14913           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14914           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14915                                               Proto->getExtProtoInfo()));
14916         }
14917       }
14918 
14919       // If the function implicitly returns zero (like 'main') or is naked,
14920       // don't complain about missing return statements.
14921       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14922         WP.disableCheckFallThrough();
14923 
14924       // MSVC permits the use of pure specifier (=0) on function definition,
14925       // defined at class scope, warn about this non-standard construct.
14926       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14927         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14928 
14929       if (!FD->isInvalidDecl()) {
14930         // Don't diagnose unused parameters of defaulted, deleted or naked
14931         // functions.
14932         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14933             !FD->hasAttr<NakedAttr>())
14934           DiagnoseUnusedParameters(FD->parameters());
14935         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14936                                                FD->getReturnType(), FD);
14937 
14938         // If this is a structor, we need a vtable.
14939         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14940           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14941         else if (CXXDestructorDecl *Destructor =
14942                      dyn_cast<CXXDestructorDecl>(FD))
14943           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14944 
14945         // Try to apply the named return value optimization. We have to check
14946         // if we can do this here because lambdas keep return statements around
14947         // to deduce an implicit return type.
14948         if (FD->getReturnType()->isRecordType() &&
14949             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14950           computeNRVO(Body, FSI);
14951       }
14952 
14953       // GNU warning -Wmissing-prototypes:
14954       //   Warn if a global function is defined without a previous
14955       //   prototype declaration. This warning is issued even if the
14956       //   definition itself provides a prototype. The aim is to detect
14957       //   global functions that fail to be declared in header files.
14958       const FunctionDecl *PossiblePrototype = nullptr;
14959       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14960         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14961 
14962         if (PossiblePrototype) {
14963           // We found a declaration that is not a prototype,
14964           // but that could be a zero-parameter prototype
14965           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14966             TypeLoc TL = TI->getTypeLoc();
14967             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14968               Diag(PossiblePrototype->getLocation(),
14969                    diag::note_declaration_not_a_prototype)
14970                   << (FD->getNumParams() != 0)
14971                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14972                                                     FTL.getRParenLoc(), "void")
14973                                               : FixItHint{});
14974           }
14975         } else {
14976           // Returns true if the token beginning at this Loc is `const`.
14977           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14978                                   const LangOptions &LangOpts) {
14979             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14980             if (LocInfo.first.isInvalid())
14981               return false;
14982 
14983             bool Invalid = false;
14984             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14985             if (Invalid)
14986               return false;
14987 
14988             if (LocInfo.second > Buffer.size())
14989               return false;
14990 
14991             const char *LexStart = Buffer.data() + LocInfo.second;
14992             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14993 
14994             return StartTok.consume_front("const") &&
14995                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14996                     StartTok.startswith("/*") || StartTok.startswith("//"));
14997           };
14998 
14999           auto findBeginLoc = [&]() {
15000             // If the return type has `const` qualifier, we want to insert
15001             // `static` before `const` (and not before the typename).
15002             if ((FD->getReturnType()->isAnyPointerType() &&
15003                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15004                 FD->getReturnType().isConstQualified()) {
15005               // But only do this if we can determine where the `const` is.
15006 
15007               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15008                                getLangOpts()))
15009 
15010                 return FD->getBeginLoc();
15011             }
15012             return FD->getTypeSpecStartLoc();
15013           };
15014           Diag(FD->getTypeSpecStartLoc(),
15015                diag::note_static_for_internal_linkage)
15016               << /* function */ 1
15017               << (FD->getStorageClass() == SC_None
15018                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15019                       : FixItHint{});
15020         }
15021       }
15022 
15023       // If the function being defined does not have a prototype, then we may
15024       // need to diagnose it as changing behavior in C2x because we now know
15025       // whether the function accepts arguments or not. This only handles the
15026       // case where the definition has no prototype but does have parameters
15027       // and either there is no previous potential prototype, or the previous
15028       // potential prototype also has no actual prototype. This handles cases
15029       // like:
15030       //   void f(); void f(a) int a; {}
15031       //   void g(a) int a; {}
15032       // See MergeFunctionDecl() for other cases of the behavior change
15033       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15034       // type without a prototype.
15035       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15036           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15037                                   !PossiblePrototype->isImplicit()))) {
15038         // The function definition has parameters, so this will change behavior
15039         // in C2x. If there is a possible prototype, it comes before the
15040         // function definition.
15041         // FIXME: The declaration may have already been diagnosed as being
15042         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15043         // there's no way to test for the "changes behavior" condition in
15044         // SemaType.cpp when forming the declaration's function type. So, we do
15045         // this awkward dance instead.
15046         //
15047         // If we have a possible prototype and it declares a function with a
15048         // prototype, we don't want to diagnose it; if we have a possible
15049         // prototype and it has no prototype, it may have already been
15050         // diagnosed in SemaType.cpp as deprecated depending on whether
15051         // -Wstrict-prototypes is enabled. If we already warned about it being
15052         // deprecated, add a note that it also changes behavior. If we didn't
15053         // warn about it being deprecated (because the diagnostic is not
15054         // enabled), warn now that it is deprecated and changes behavior.
15055         bool AddNote = false;
15056         if (PossiblePrototype) {
15057           if (Diags.isIgnored(diag::warn_strict_prototypes,
15058                               PossiblePrototype->getLocation())) {
15059 
15060             PartialDiagnostic PD =
15061                 PDiag(diag::warn_non_prototype_changes_behavior);
15062             if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) {
15063               if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>())
15064                 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
15065             }
15066             Diag(PossiblePrototype->getLocation(), PD);
15067           } else {
15068             AddNote = true;
15069           }
15070         }
15071 
15072         // Because this function definition has no prototype and it has
15073         // parameters, it will definitely change behavior in C2x.
15074         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior);
15075         if (AddNote)
15076           Diag(PossiblePrototype->getLocation(),
15077                diag::note_func_decl_changes_behavior);
15078       }
15079 
15080       // Warn on CPUDispatch with an actual body.
15081       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15082         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15083           if (!CmpndBody->body_empty())
15084             Diag(CmpndBody->body_front()->getBeginLoc(),
15085                  diag::warn_dispatch_body_ignored);
15086 
15087       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15088         const CXXMethodDecl *KeyFunction;
15089         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15090             MD->isVirtual() &&
15091             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15092             MD == KeyFunction->getCanonicalDecl()) {
15093           // Update the key-function state if necessary for this ABI.
15094           if (FD->isInlined() &&
15095               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15096             Context.setNonKeyFunction(MD);
15097 
15098             // If the newly-chosen key function is already defined, then we
15099             // need to mark the vtable as used retroactively.
15100             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15101             const FunctionDecl *Definition;
15102             if (KeyFunction && KeyFunction->isDefined(Definition))
15103               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15104           } else {
15105             // We just defined they key function; mark the vtable as used.
15106             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15107           }
15108         }
15109       }
15110 
15111       assert(
15112           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15113           "Function parsing confused");
15114     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15115       assert(MD == getCurMethodDecl() && "Method parsing confused");
15116       MD->setBody(Body);
15117       if (!MD->isInvalidDecl()) {
15118         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15119                                                MD->getReturnType(), MD);
15120 
15121         if (Body)
15122           computeNRVO(Body, FSI);
15123       }
15124       if (FSI->ObjCShouldCallSuper) {
15125         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15126             << MD->getSelector().getAsString();
15127         FSI->ObjCShouldCallSuper = false;
15128       }
15129       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15130         const ObjCMethodDecl *InitMethod = nullptr;
15131         bool isDesignated =
15132             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15133         assert(isDesignated && InitMethod);
15134         (void)isDesignated;
15135 
15136         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15137           auto IFace = MD->getClassInterface();
15138           if (!IFace)
15139             return false;
15140           auto SuperD = IFace->getSuperClass();
15141           if (!SuperD)
15142             return false;
15143           return SuperD->getIdentifier() ==
15144                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15145         };
15146         // Don't issue this warning for unavailable inits or direct subclasses
15147         // of NSObject.
15148         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15149           Diag(MD->getLocation(),
15150                diag::warn_objc_designated_init_missing_super_call);
15151           Diag(InitMethod->getLocation(),
15152                diag::note_objc_designated_init_marked_here);
15153         }
15154         FSI->ObjCWarnForNoDesignatedInitChain = false;
15155       }
15156       if (FSI->ObjCWarnForNoInitDelegation) {
15157         // Don't issue this warning for unavaialable inits.
15158         if (!MD->isUnavailable())
15159           Diag(MD->getLocation(),
15160                diag::warn_objc_secondary_init_missing_init_call);
15161         FSI->ObjCWarnForNoInitDelegation = false;
15162       }
15163 
15164       diagnoseImplicitlyRetainedSelf(*this);
15165     } else {
15166       // Parsing the function declaration failed in some way. Pop the fake scope
15167       // we pushed on.
15168       PopFunctionScopeInfo(ActivePolicy, dcl);
15169       return nullptr;
15170     }
15171 
15172     if (Body && FSI->HasPotentialAvailabilityViolations)
15173       DiagnoseUnguardedAvailabilityViolations(dcl);
15174 
15175     assert(!FSI->ObjCShouldCallSuper &&
15176            "This should only be set for ObjC methods, which should have been "
15177            "handled in the block above.");
15178 
15179     // Verify and clean out per-function state.
15180     if (Body && (!FD || !FD->isDefaulted())) {
15181       // C++ constructors that have function-try-blocks can't have return
15182       // statements in the handlers of that block. (C++ [except.handle]p14)
15183       // Verify this.
15184       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15185         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15186 
15187       // Verify that gotos and switch cases don't jump into scopes illegally.
15188       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15189         DiagnoseInvalidJumps(Body);
15190 
15191       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15192         if (!Destructor->getParent()->isDependentType())
15193           CheckDestructor(Destructor);
15194 
15195         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15196                                                Destructor->getParent());
15197       }
15198 
15199       // If any errors have occurred, clear out any temporaries that may have
15200       // been leftover. This ensures that these temporaries won't be picked up
15201       // for deletion in some later function.
15202       if (hasUncompilableErrorOccurred() ||
15203           getDiagnostics().getSuppressAllDiagnostics()) {
15204         DiscardCleanupsInEvaluationContext();
15205       }
15206       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15207         // Since the body is valid, issue any analysis-based warnings that are
15208         // enabled.
15209         ActivePolicy = &WP;
15210       }
15211 
15212       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15213           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15214         FD->setInvalidDecl();
15215 
15216       if (FD && FD->hasAttr<NakedAttr>()) {
15217         for (const Stmt *S : Body->children()) {
15218           // Allow local register variables without initializer as they don't
15219           // require prologue.
15220           bool RegisterVariables = false;
15221           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15222             for (const auto *Decl : DS->decls()) {
15223               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15224                 RegisterVariables =
15225                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15226                 if (!RegisterVariables)
15227                   break;
15228               }
15229             }
15230           }
15231           if (RegisterVariables)
15232             continue;
15233           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15234             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15235             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15236             FD->setInvalidDecl();
15237             break;
15238           }
15239         }
15240       }
15241 
15242       assert(ExprCleanupObjects.size() ==
15243                  ExprEvalContexts.back().NumCleanupObjects &&
15244              "Leftover temporaries in function");
15245       assert(!Cleanup.exprNeedsCleanups() &&
15246              "Unaccounted cleanups in function");
15247       assert(MaybeODRUseExprs.empty() &&
15248              "Leftover expressions for odr-use checking");
15249     }
15250   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15251     // the declaration context below. Otherwise, we're unable to transform
15252     // 'this' expressions when transforming immediate context functions.
15253 
15254   if (!IsInstantiation)
15255     PopDeclContext();
15256 
15257   PopFunctionScopeInfo(ActivePolicy, dcl);
15258   // If any errors have occurred, clear out any temporaries that may have
15259   // been leftover. This ensures that these temporaries won't be picked up for
15260   // deletion in some later function.
15261   if (hasUncompilableErrorOccurred()) {
15262     DiscardCleanupsInEvaluationContext();
15263   }
15264 
15265   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15266                                   !LangOpts.OMPTargetTriples.empty())) ||
15267              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15268     auto ES = getEmissionStatus(FD);
15269     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15270         ES == Sema::FunctionEmissionStatus::Unknown)
15271       DeclsToCheckForDeferredDiags.insert(FD);
15272   }
15273 
15274   if (FD && !FD->isDeleted())
15275     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15276 
15277   return dcl;
15278 }
15279 
15280 /// When we finish delayed parsing of an attribute, we must attach it to the
15281 /// relevant Decl.
15282 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15283                                        ParsedAttributes &Attrs) {
15284   // Always attach attributes to the underlying decl.
15285   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15286     D = TD->getTemplatedDecl();
15287   ProcessDeclAttributeList(S, D, Attrs);
15288 
15289   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15290     if (Method->isStatic())
15291       checkThisInStaticMemberFunctionAttributes(Method);
15292 }
15293 
15294 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15295 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15296 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15297                                           IdentifierInfo &II, Scope *S) {
15298   // It is not valid to implicitly define a function in C2x.
15299   assert(LangOpts.implicitFunctionsAllowed() &&
15300          "Implicit function declarations aren't allowed in this language mode");
15301 
15302   // Find the scope in which the identifier is injected and the corresponding
15303   // DeclContext.
15304   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15305   // In that case, we inject the declaration into the translation unit scope
15306   // instead.
15307   Scope *BlockScope = S;
15308   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15309     BlockScope = BlockScope->getParent();
15310 
15311   Scope *ContextScope = BlockScope;
15312   while (!ContextScope->getEntity())
15313     ContextScope = ContextScope->getParent();
15314   ContextRAII SavedContext(*this, ContextScope->getEntity());
15315 
15316   // Before we produce a declaration for an implicitly defined
15317   // function, see whether there was a locally-scoped declaration of
15318   // this name as a function or variable. If so, use that
15319   // (non-visible) declaration, and complain about it.
15320   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15321   if (ExternCPrev) {
15322     // We still need to inject the function into the enclosing block scope so
15323     // that later (non-call) uses can see it.
15324     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15325 
15326     // C89 footnote 38:
15327     //   If in fact it is not defined as having type "function returning int",
15328     //   the behavior is undefined.
15329     if (!isa<FunctionDecl>(ExternCPrev) ||
15330         !Context.typesAreCompatible(
15331             cast<FunctionDecl>(ExternCPrev)->getType(),
15332             Context.getFunctionNoProtoType(Context.IntTy))) {
15333       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15334           << ExternCPrev << !getLangOpts().C99;
15335       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15336       return ExternCPrev;
15337     }
15338   }
15339 
15340   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15341   unsigned diag_id;
15342   if (II.getName().startswith("__builtin_"))
15343     diag_id = diag::warn_builtin_unknown;
15344   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15345   else if (getLangOpts().C99)
15346     diag_id = diag::ext_implicit_function_decl_c99;
15347   else
15348     diag_id = diag::warn_implicit_function_decl;
15349 
15350   TypoCorrection Corrected;
15351   // Because typo correction is expensive, only do it if the implicit
15352   // function declaration is going to be treated as an error.
15353   //
15354   // Perform the corection before issuing the main diagnostic, as some consumers
15355   // use typo-correction callbacks to enhance the main diagnostic.
15356   if (S && !ExternCPrev &&
15357       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15358     DeclFilterCCC<FunctionDecl> CCC{};
15359     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15360                             S, nullptr, CCC, CTK_NonError);
15361   }
15362 
15363   Diag(Loc, diag_id) << &II;
15364   if (Corrected) {
15365     // If the correction is going to suggest an implicitly defined function,
15366     // skip the correction as not being a particularly good idea.
15367     bool Diagnose = true;
15368     if (const auto *D = Corrected.getCorrectionDecl())
15369       Diagnose = !D->isImplicit();
15370     if (Diagnose)
15371       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15372                    /*ErrorRecovery*/ false);
15373   }
15374 
15375   // If we found a prior declaration of this function, don't bother building
15376   // another one. We've already pushed that one into scope, so there's nothing
15377   // more to do.
15378   if (ExternCPrev)
15379     return ExternCPrev;
15380 
15381   // Set a Declarator for the implicit definition: int foo();
15382   const char *Dummy;
15383   AttributeFactory attrFactory;
15384   DeclSpec DS(attrFactory);
15385   unsigned DiagID;
15386   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15387                                   Context.getPrintingPolicy());
15388   (void)Error; // Silence warning.
15389   assert(!Error && "Error setting up implicit decl!");
15390   SourceLocation NoLoc;
15391   Declarator D(DS, DeclaratorContext::Block);
15392   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15393                                              /*IsAmbiguous=*/false,
15394                                              /*LParenLoc=*/NoLoc,
15395                                              /*Params=*/nullptr,
15396                                              /*NumParams=*/0,
15397                                              /*EllipsisLoc=*/NoLoc,
15398                                              /*RParenLoc=*/NoLoc,
15399                                              /*RefQualifierIsLvalueRef=*/true,
15400                                              /*RefQualifierLoc=*/NoLoc,
15401                                              /*MutableLoc=*/NoLoc, EST_None,
15402                                              /*ESpecRange=*/SourceRange(),
15403                                              /*Exceptions=*/nullptr,
15404                                              /*ExceptionRanges=*/nullptr,
15405                                              /*NumExceptions=*/0,
15406                                              /*NoexceptExpr=*/nullptr,
15407                                              /*ExceptionSpecTokens=*/nullptr,
15408                                              /*DeclsInPrototype=*/None, Loc,
15409                                              Loc, D),
15410                 std::move(DS.getAttributes()), SourceLocation());
15411   D.SetIdentifier(&II, Loc);
15412 
15413   // Insert this function into the enclosing block scope.
15414   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15415   FD->setImplicit();
15416 
15417   AddKnownFunctionAttributes(FD);
15418 
15419   return FD;
15420 }
15421 
15422 /// If this function is a C++ replaceable global allocation function
15423 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15424 /// adds any function attributes that we know a priori based on the standard.
15425 ///
15426 /// We need to check for duplicate attributes both here and where user-written
15427 /// attributes are applied to declarations.
15428 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15429     FunctionDecl *FD) {
15430   if (FD->isInvalidDecl())
15431     return;
15432 
15433   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15434       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15435     return;
15436 
15437   Optional<unsigned> AlignmentParam;
15438   bool IsNothrow = false;
15439   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15440     return;
15441 
15442   // C++2a [basic.stc.dynamic.allocation]p4:
15443   //   An allocation function that has a non-throwing exception specification
15444   //   indicates failure by returning a null pointer value. Any other allocation
15445   //   function never returns a null pointer value and indicates failure only by
15446   //   throwing an exception [...]
15447   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15448     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15449 
15450   // C++2a [basic.stc.dynamic.allocation]p2:
15451   //   An allocation function attempts to allocate the requested amount of
15452   //   storage. [...] If the request succeeds, the value returned by a
15453   //   replaceable allocation function is a [...] pointer value p0 different
15454   //   from any previously returned value p1 [...]
15455   //
15456   // However, this particular information is being added in codegen,
15457   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15458 
15459   // C++2a [basic.stc.dynamic.allocation]p2:
15460   //   An allocation function attempts to allocate the requested amount of
15461   //   storage. If it is successful, it returns the address of the start of a
15462   //   block of storage whose length in bytes is at least as large as the
15463   //   requested size.
15464   if (!FD->hasAttr<AllocSizeAttr>()) {
15465     FD->addAttr(AllocSizeAttr::CreateImplicit(
15466         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15467         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15468   }
15469 
15470   // C++2a [basic.stc.dynamic.allocation]p3:
15471   //   For an allocation function [...], the pointer returned on a successful
15472   //   call shall represent the address of storage that is aligned as follows:
15473   //   (3.1) If the allocation function takes an argument of type
15474   //         std​::​align_­val_­t, the storage will have the alignment
15475   //         specified by the value of this argument.
15476   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15477     FD->addAttr(AllocAlignAttr::CreateImplicit(
15478         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15479   }
15480 
15481   // FIXME:
15482   // C++2a [basic.stc.dynamic.allocation]p3:
15483   //   For an allocation function [...], the pointer returned on a successful
15484   //   call shall represent the address of storage that is aligned as follows:
15485   //   (3.2) Otherwise, if the allocation function is named operator new[],
15486   //         the storage is aligned for any object that does not have
15487   //         new-extended alignment ([basic.align]) and is no larger than the
15488   //         requested size.
15489   //   (3.3) Otherwise, the storage is aligned for any object that does not
15490   //         have new-extended alignment and is of the requested size.
15491 }
15492 
15493 /// Adds any function attributes that we know a priori based on
15494 /// the declaration of this function.
15495 ///
15496 /// These attributes can apply both to implicitly-declared builtins
15497 /// (like __builtin___printf_chk) or to library-declared functions
15498 /// like NSLog or printf.
15499 ///
15500 /// We need to check for duplicate attributes both here and where user-written
15501 /// attributes are applied to declarations.
15502 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15503   if (FD->isInvalidDecl())
15504     return;
15505 
15506   // If this is a built-in function, map its builtin attributes to
15507   // actual attributes.
15508   if (unsigned BuiltinID = FD->getBuiltinID()) {
15509     // Handle printf-formatting attributes.
15510     unsigned FormatIdx;
15511     bool HasVAListArg;
15512     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15513       if (!FD->hasAttr<FormatAttr>()) {
15514         const char *fmt = "printf";
15515         unsigned int NumParams = FD->getNumParams();
15516         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15517             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15518           fmt = "NSString";
15519         FD->addAttr(FormatAttr::CreateImplicit(Context,
15520                                                &Context.Idents.get(fmt),
15521                                                FormatIdx+1,
15522                                                HasVAListArg ? 0 : FormatIdx+2,
15523                                                FD->getLocation()));
15524       }
15525     }
15526     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15527                                              HasVAListArg)) {
15528      if (!FD->hasAttr<FormatAttr>())
15529        FD->addAttr(FormatAttr::CreateImplicit(Context,
15530                                               &Context.Idents.get("scanf"),
15531                                               FormatIdx+1,
15532                                               HasVAListArg ? 0 : FormatIdx+2,
15533                                               FD->getLocation()));
15534     }
15535 
15536     // Handle automatically recognized callbacks.
15537     SmallVector<int, 4> Encoding;
15538     if (!FD->hasAttr<CallbackAttr>() &&
15539         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15540       FD->addAttr(CallbackAttr::CreateImplicit(
15541           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15542 
15543     // Mark const if we don't care about errno and that is the only thing
15544     // preventing the function from being const. This allows IRgen to use LLVM
15545     // intrinsics for such functions.
15546     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15547         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15548       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15549 
15550     // We make "fma" on GNU or Windows const because we know it does not set
15551     // errno in those environments even though it could set errno based on the
15552     // C standard.
15553     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15554     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15555         !FD->hasAttr<ConstAttr>()) {
15556       switch (BuiltinID) {
15557       case Builtin::BI__builtin_fma:
15558       case Builtin::BI__builtin_fmaf:
15559       case Builtin::BI__builtin_fmal:
15560       case Builtin::BIfma:
15561       case Builtin::BIfmaf:
15562       case Builtin::BIfmal:
15563         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15564         break;
15565       default:
15566         break;
15567       }
15568     }
15569 
15570     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15571         !FD->hasAttr<ReturnsTwiceAttr>())
15572       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15573                                          FD->getLocation()));
15574     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15575       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15576     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15577       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15578     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15579       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15580     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15581         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15582       // Add the appropriate attribute, depending on the CUDA compilation mode
15583       // and which target the builtin belongs to. For example, during host
15584       // compilation, aux builtins are __device__, while the rest are __host__.
15585       if (getLangOpts().CUDAIsDevice !=
15586           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15587         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15588       else
15589         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15590     }
15591 
15592     // Add known guaranteed alignment for allocation functions.
15593     switch (BuiltinID) {
15594     case Builtin::BImemalign:
15595     case Builtin::BIaligned_alloc:
15596       if (!FD->hasAttr<AllocAlignAttr>())
15597         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15598                                                    FD->getLocation()));
15599       break;
15600     default:
15601       break;
15602     }
15603 
15604     // Add allocsize attribute for allocation functions.
15605     switch (BuiltinID) {
15606     case Builtin::BIcalloc:
15607       FD->addAttr(AllocSizeAttr::CreateImplicit(
15608           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15609       break;
15610     case Builtin::BImemalign:
15611     case Builtin::BIaligned_alloc:
15612     case Builtin::BIrealloc:
15613       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15614                                                 ParamIdx(), FD->getLocation()));
15615       break;
15616     case Builtin::BImalloc:
15617       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15618                                                 ParamIdx(), FD->getLocation()));
15619       break;
15620     default:
15621       break;
15622     }
15623   }
15624 
15625   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15626 
15627   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15628   // throw, add an implicit nothrow attribute to any extern "C" function we come
15629   // across.
15630   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15631       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15632     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15633     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15634       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15635   }
15636 
15637   IdentifierInfo *Name = FD->getIdentifier();
15638   if (!Name)
15639     return;
15640   if ((!getLangOpts().CPlusPlus &&
15641        FD->getDeclContext()->isTranslationUnit()) ||
15642       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15643        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15644        LinkageSpecDecl::lang_c)) {
15645     // Okay: this could be a libc/libm/Objective-C function we know
15646     // about.
15647   } else
15648     return;
15649 
15650   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15651     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15652     // target-specific builtins, perhaps?
15653     if (!FD->hasAttr<FormatAttr>())
15654       FD->addAttr(FormatAttr::CreateImplicit(Context,
15655                                              &Context.Idents.get("printf"), 2,
15656                                              Name->isStr("vasprintf") ? 0 : 3,
15657                                              FD->getLocation()));
15658   }
15659 
15660   if (Name->isStr("__CFStringMakeConstantString")) {
15661     // We already have a __builtin___CFStringMakeConstantString,
15662     // but builds that use -fno-constant-cfstrings don't go through that.
15663     if (!FD->hasAttr<FormatArgAttr>())
15664       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15665                                                 FD->getLocation()));
15666   }
15667 }
15668 
15669 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15670                                     TypeSourceInfo *TInfo) {
15671   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15672   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15673 
15674   if (!TInfo) {
15675     assert(D.isInvalidType() && "no declarator info for valid type");
15676     TInfo = Context.getTrivialTypeSourceInfo(T);
15677   }
15678 
15679   // Scope manipulation handled by caller.
15680   TypedefDecl *NewTD =
15681       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15682                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15683 
15684   // Bail out immediately if we have an invalid declaration.
15685   if (D.isInvalidType()) {
15686     NewTD->setInvalidDecl();
15687     return NewTD;
15688   }
15689 
15690   if (D.getDeclSpec().isModulePrivateSpecified()) {
15691     if (CurContext->isFunctionOrMethod())
15692       Diag(NewTD->getLocation(), diag::err_module_private_local)
15693           << 2 << NewTD
15694           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15695           << FixItHint::CreateRemoval(
15696                  D.getDeclSpec().getModulePrivateSpecLoc());
15697     else
15698       NewTD->setModulePrivate();
15699   }
15700 
15701   // C++ [dcl.typedef]p8:
15702   //   If the typedef declaration defines an unnamed class (or
15703   //   enum), the first typedef-name declared by the declaration
15704   //   to be that class type (or enum type) is used to denote the
15705   //   class type (or enum type) for linkage purposes only.
15706   // We need to check whether the type was declared in the declaration.
15707   switch (D.getDeclSpec().getTypeSpecType()) {
15708   case TST_enum:
15709   case TST_struct:
15710   case TST_interface:
15711   case TST_union:
15712   case TST_class: {
15713     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15714     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15715     break;
15716   }
15717 
15718   default:
15719     break;
15720   }
15721 
15722   return NewTD;
15723 }
15724 
15725 /// Check that this is a valid underlying type for an enum declaration.
15726 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15727   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15728   QualType T = TI->getType();
15729 
15730   if (T->isDependentType())
15731     return false;
15732 
15733   // This doesn't use 'isIntegralType' despite the error message mentioning
15734   // integral type because isIntegralType would also allow enum types in C.
15735   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15736     if (BT->isInteger())
15737       return false;
15738 
15739   if (T->isBitIntType())
15740     return false;
15741 
15742   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15743 }
15744 
15745 /// Check whether this is a valid redeclaration of a previous enumeration.
15746 /// \return true if the redeclaration was invalid.
15747 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15748                                   QualType EnumUnderlyingTy, bool IsFixed,
15749                                   const EnumDecl *Prev) {
15750   if (IsScoped != Prev->isScoped()) {
15751     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15752       << Prev->isScoped();
15753     Diag(Prev->getLocation(), diag::note_previous_declaration);
15754     return true;
15755   }
15756 
15757   if (IsFixed && Prev->isFixed()) {
15758     if (!EnumUnderlyingTy->isDependentType() &&
15759         !Prev->getIntegerType()->isDependentType() &&
15760         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15761                                         Prev->getIntegerType())) {
15762       // TODO: Highlight the underlying type of the redeclaration.
15763       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15764         << EnumUnderlyingTy << Prev->getIntegerType();
15765       Diag(Prev->getLocation(), diag::note_previous_declaration)
15766           << Prev->getIntegerTypeRange();
15767       return true;
15768     }
15769   } else if (IsFixed != Prev->isFixed()) {
15770     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15771       << Prev->isFixed();
15772     Diag(Prev->getLocation(), diag::note_previous_declaration);
15773     return true;
15774   }
15775 
15776   return false;
15777 }
15778 
15779 /// Get diagnostic %select index for tag kind for
15780 /// redeclaration diagnostic message.
15781 /// WARNING: Indexes apply to particular diagnostics only!
15782 ///
15783 /// \returns diagnostic %select index.
15784 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15785   switch (Tag) {
15786   case TTK_Struct: return 0;
15787   case TTK_Interface: return 1;
15788   case TTK_Class:  return 2;
15789   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15790   }
15791 }
15792 
15793 /// Determine if tag kind is a class-key compatible with
15794 /// class for redeclaration (class, struct, or __interface).
15795 ///
15796 /// \returns true iff the tag kind is compatible.
15797 static bool isClassCompatTagKind(TagTypeKind Tag)
15798 {
15799   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15800 }
15801 
15802 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15803                                              TagTypeKind TTK) {
15804   if (isa<TypedefDecl>(PrevDecl))
15805     return NTK_Typedef;
15806   else if (isa<TypeAliasDecl>(PrevDecl))
15807     return NTK_TypeAlias;
15808   else if (isa<ClassTemplateDecl>(PrevDecl))
15809     return NTK_Template;
15810   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15811     return NTK_TypeAliasTemplate;
15812   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15813     return NTK_TemplateTemplateArgument;
15814   switch (TTK) {
15815   case TTK_Struct:
15816   case TTK_Interface:
15817   case TTK_Class:
15818     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15819   case TTK_Union:
15820     return NTK_NonUnion;
15821   case TTK_Enum:
15822     return NTK_NonEnum;
15823   }
15824   llvm_unreachable("invalid TTK");
15825 }
15826 
15827 /// Determine whether a tag with a given kind is acceptable
15828 /// as a redeclaration of the given tag declaration.
15829 ///
15830 /// \returns true if the new tag kind is acceptable, false otherwise.
15831 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15832                                         TagTypeKind NewTag, bool isDefinition,
15833                                         SourceLocation NewTagLoc,
15834                                         const IdentifierInfo *Name) {
15835   // C++ [dcl.type.elab]p3:
15836   //   The class-key or enum keyword present in the
15837   //   elaborated-type-specifier shall agree in kind with the
15838   //   declaration to which the name in the elaborated-type-specifier
15839   //   refers. This rule also applies to the form of
15840   //   elaborated-type-specifier that declares a class-name or
15841   //   friend class since it can be construed as referring to the
15842   //   definition of the class. Thus, in any
15843   //   elaborated-type-specifier, the enum keyword shall be used to
15844   //   refer to an enumeration (7.2), the union class-key shall be
15845   //   used to refer to a union (clause 9), and either the class or
15846   //   struct class-key shall be used to refer to a class (clause 9)
15847   //   declared using the class or struct class-key.
15848   TagTypeKind OldTag = Previous->getTagKind();
15849   if (OldTag != NewTag &&
15850       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15851     return false;
15852 
15853   // Tags are compatible, but we might still want to warn on mismatched tags.
15854   // Non-class tags can't be mismatched at this point.
15855   if (!isClassCompatTagKind(NewTag))
15856     return true;
15857 
15858   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15859   // by our warning analysis. We don't want to warn about mismatches with (eg)
15860   // declarations in system headers that are designed to be specialized, but if
15861   // a user asks us to warn, we should warn if their code contains mismatched
15862   // declarations.
15863   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15864     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15865                                       Loc);
15866   };
15867   if (IsIgnoredLoc(NewTagLoc))
15868     return true;
15869 
15870   auto IsIgnored = [&](const TagDecl *Tag) {
15871     return IsIgnoredLoc(Tag->getLocation());
15872   };
15873   while (IsIgnored(Previous)) {
15874     Previous = Previous->getPreviousDecl();
15875     if (!Previous)
15876       return true;
15877     OldTag = Previous->getTagKind();
15878   }
15879 
15880   bool isTemplate = false;
15881   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15882     isTemplate = Record->getDescribedClassTemplate();
15883 
15884   if (inTemplateInstantiation()) {
15885     if (OldTag != NewTag) {
15886       // In a template instantiation, do not offer fix-its for tag mismatches
15887       // since they usually mess up the template instead of fixing the problem.
15888       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15889         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15890         << getRedeclDiagFromTagKind(OldTag);
15891       // FIXME: Note previous location?
15892     }
15893     return true;
15894   }
15895 
15896   if (isDefinition) {
15897     // On definitions, check all previous tags and issue a fix-it for each
15898     // one that doesn't match the current tag.
15899     if (Previous->getDefinition()) {
15900       // Don't suggest fix-its for redefinitions.
15901       return true;
15902     }
15903 
15904     bool previousMismatch = false;
15905     for (const TagDecl *I : Previous->redecls()) {
15906       if (I->getTagKind() != NewTag) {
15907         // Ignore previous declarations for which the warning was disabled.
15908         if (IsIgnored(I))
15909           continue;
15910 
15911         if (!previousMismatch) {
15912           previousMismatch = true;
15913           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15914             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15915             << getRedeclDiagFromTagKind(I->getTagKind());
15916         }
15917         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15918           << getRedeclDiagFromTagKind(NewTag)
15919           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15920                TypeWithKeyword::getTagTypeKindName(NewTag));
15921       }
15922     }
15923     return true;
15924   }
15925 
15926   // Identify the prevailing tag kind: this is the kind of the definition (if
15927   // there is a non-ignored definition), or otherwise the kind of the prior
15928   // (non-ignored) declaration.
15929   const TagDecl *PrevDef = Previous->getDefinition();
15930   if (PrevDef && IsIgnored(PrevDef))
15931     PrevDef = nullptr;
15932   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15933   if (Redecl->getTagKind() != NewTag) {
15934     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15935       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15936       << getRedeclDiagFromTagKind(OldTag);
15937     Diag(Redecl->getLocation(), diag::note_previous_use);
15938 
15939     // If there is a previous definition, suggest a fix-it.
15940     if (PrevDef) {
15941       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15942         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15943         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15944              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15945     }
15946   }
15947 
15948   return true;
15949 }
15950 
15951 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15952 /// from an outer enclosing namespace or file scope inside a friend declaration.
15953 /// This should provide the commented out code in the following snippet:
15954 ///   namespace N {
15955 ///     struct X;
15956 ///     namespace M {
15957 ///       struct Y { friend struct /*N::*/ X; };
15958 ///     }
15959 ///   }
15960 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15961                                          SourceLocation NameLoc) {
15962   // While the decl is in a namespace, do repeated lookup of that name and see
15963   // if we get the same namespace back.  If we do not, continue until
15964   // translation unit scope, at which point we have a fully qualified NNS.
15965   SmallVector<IdentifierInfo *, 4> Namespaces;
15966   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15967   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15968     // This tag should be declared in a namespace, which can only be enclosed by
15969     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15970     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15971     if (!Namespace || Namespace->isAnonymousNamespace())
15972       return FixItHint();
15973     IdentifierInfo *II = Namespace->getIdentifier();
15974     Namespaces.push_back(II);
15975     NamedDecl *Lookup = SemaRef.LookupSingleName(
15976         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15977     if (Lookup == Namespace)
15978       break;
15979   }
15980 
15981   // Once we have all the namespaces, reverse them to go outermost first, and
15982   // build an NNS.
15983   SmallString<64> Insertion;
15984   llvm::raw_svector_ostream OS(Insertion);
15985   if (DC->isTranslationUnit())
15986     OS << "::";
15987   std::reverse(Namespaces.begin(), Namespaces.end());
15988   for (auto *II : Namespaces)
15989     OS << II->getName() << "::";
15990   return FixItHint::CreateInsertion(NameLoc, Insertion);
15991 }
15992 
15993 /// Determine whether a tag originally declared in context \p OldDC can
15994 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15995 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15996 /// using-declaration).
15997 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15998                                          DeclContext *NewDC) {
15999   OldDC = OldDC->getRedeclContext();
16000   NewDC = NewDC->getRedeclContext();
16001 
16002   if (OldDC->Equals(NewDC))
16003     return true;
16004 
16005   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16006   // encloses the other).
16007   if (S.getLangOpts().MSVCCompat &&
16008       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16009     return true;
16010 
16011   return false;
16012 }
16013 
16014 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16015 /// former case, Name will be non-null.  In the later case, Name will be null.
16016 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16017 /// reference/declaration/definition of a tag.
16018 ///
16019 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16020 /// trailing-type-specifier) other than one in an alias-declaration.
16021 ///
16022 /// \param SkipBody If non-null, will be set to indicate if the caller should
16023 /// skip the definition of this tag and treat it as if it were a declaration.
16024 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16025                      SourceLocation KWLoc, CXXScopeSpec &SS,
16026                      IdentifierInfo *Name, SourceLocation NameLoc,
16027                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16028                      SourceLocation ModulePrivateLoc,
16029                      MultiTemplateParamsArg TemplateParameterLists,
16030                      bool &OwnedDecl, bool &IsDependent,
16031                      SourceLocation ScopedEnumKWLoc,
16032                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16033                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16034                      SkipBodyInfo *SkipBody) {
16035   // If this is not a definition, it must have a name.
16036   IdentifierInfo *OrigName = Name;
16037   assert((Name != nullptr || TUK == TUK_Definition) &&
16038          "Nameless record must be a definition!");
16039   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16040 
16041   OwnedDecl = false;
16042   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16043   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16044 
16045   // FIXME: Check member specializations more carefully.
16046   bool isMemberSpecialization = false;
16047   bool Invalid = false;
16048 
16049   // We only need to do this matching if we have template parameters
16050   // or a scope specifier, which also conveniently avoids this work
16051   // for non-C++ cases.
16052   if (TemplateParameterLists.size() > 0 ||
16053       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16054     if (TemplateParameterList *TemplateParams =
16055             MatchTemplateParametersToScopeSpecifier(
16056                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16057                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16058       if (Kind == TTK_Enum) {
16059         Diag(KWLoc, diag::err_enum_template);
16060         return nullptr;
16061       }
16062 
16063       if (TemplateParams->size() > 0) {
16064         // This is a declaration or definition of a class template (which may
16065         // be a member of another template).
16066 
16067         if (Invalid)
16068           return nullptr;
16069 
16070         OwnedDecl = false;
16071         DeclResult Result = CheckClassTemplate(
16072             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16073             AS, ModulePrivateLoc,
16074             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16075             TemplateParameterLists.data(), SkipBody);
16076         return Result.get();
16077       } else {
16078         // The "template<>" header is extraneous.
16079         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16080           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16081         isMemberSpecialization = true;
16082       }
16083     }
16084 
16085     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16086         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16087       return nullptr;
16088   }
16089 
16090   // Figure out the underlying type if this a enum declaration. We need to do
16091   // this early, because it's needed to detect if this is an incompatible
16092   // redeclaration.
16093   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16094   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16095 
16096   if (Kind == TTK_Enum) {
16097     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16098       // No underlying type explicitly specified, or we failed to parse the
16099       // type, default to int.
16100       EnumUnderlying = Context.IntTy.getTypePtr();
16101     } else if (UnderlyingType.get()) {
16102       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16103       // integral type; any cv-qualification is ignored.
16104       TypeSourceInfo *TI = nullptr;
16105       GetTypeFromParser(UnderlyingType.get(), &TI);
16106       EnumUnderlying = TI;
16107 
16108       if (CheckEnumUnderlyingType(TI))
16109         // Recover by falling back to int.
16110         EnumUnderlying = Context.IntTy.getTypePtr();
16111 
16112       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16113                                           UPPC_FixedUnderlyingType))
16114         EnumUnderlying = Context.IntTy.getTypePtr();
16115 
16116     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16117       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16118       // of 'int'. However, if this is an unfixed forward declaration, don't set
16119       // the underlying type unless the user enables -fms-compatibility. This
16120       // makes unfixed forward declared enums incomplete and is more conforming.
16121       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16122         EnumUnderlying = Context.IntTy.getTypePtr();
16123     }
16124   }
16125 
16126   DeclContext *SearchDC = CurContext;
16127   DeclContext *DC = CurContext;
16128   bool isStdBadAlloc = false;
16129   bool isStdAlignValT = false;
16130 
16131   RedeclarationKind Redecl = forRedeclarationInCurContext();
16132   if (TUK == TUK_Friend || TUK == TUK_Reference)
16133     Redecl = NotForRedeclaration;
16134 
16135   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16136   /// implemented asks for structural equivalence checking, the returned decl
16137   /// here is passed back to the parser, allowing the tag body to be parsed.
16138   auto createTagFromNewDecl = [&]() -> TagDecl * {
16139     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16140     // If there is an identifier, use the location of the identifier as the
16141     // location of the decl, otherwise use the location of the struct/union
16142     // keyword.
16143     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16144     TagDecl *New = nullptr;
16145 
16146     if (Kind == TTK_Enum) {
16147       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16148                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16149       // If this is an undefined enum, bail.
16150       if (TUK != TUK_Definition && !Invalid)
16151         return nullptr;
16152       if (EnumUnderlying) {
16153         EnumDecl *ED = cast<EnumDecl>(New);
16154         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16155           ED->setIntegerTypeSourceInfo(TI);
16156         else
16157           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16158         ED->setPromotionType(ED->getIntegerType());
16159       }
16160     } else { // struct/union
16161       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16162                                nullptr);
16163     }
16164 
16165     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16166       // Add alignment attributes if necessary; these attributes are checked
16167       // when the ASTContext lays out the structure.
16168       //
16169       // It is important for implementing the correct semantics that this
16170       // happen here (in ActOnTag). The #pragma pack stack is
16171       // maintained as a result of parser callbacks which can occur at
16172       // many points during the parsing of a struct declaration (because
16173       // the #pragma tokens are effectively skipped over during the
16174       // parsing of the struct).
16175       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16176         AddAlignmentAttributesForRecord(RD);
16177         AddMsStructLayoutForRecord(RD);
16178       }
16179     }
16180     New->setLexicalDeclContext(CurContext);
16181     return New;
16182   };
16183 
16184   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16185   if (Name && SS.isNotEmpty()) {
16186     // We have a nested-name tag ('struct foo::bar').
16187 
16188     // Check for invalid 'foo::'.
16189     if (SS.isInvalid()) {
16190       Name = nullptr;
16191       goto CreateNewDecl;
16192     }
16193 
16194     // If this is a friend or a reference to a class in a dependent
16195     // context, don't try to make a decl for it.
16196     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16197       DC = computeDeclContext(SS, false);
16198       if (!DC) {
16199         IsDependent = true;
16200         return nullptr;
16201       }
16202     } else {
16203       DC = computeDeclContext(SS, true);
16204       if (!DC) {
16205         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16206           << SS.getRange();
16207         return nullptr;
16208       }
16209     }
16210 
16211     if (RequireCompleteDeclContext(SS, DC))
16212       return nullptr;
16213 
16214     SearchDC = DC;
16215     // Look-up name inside 'foo::'.
16216     LookupQualifiedName(Previous, DC);
16217 
16218     if (Previous.isAmbiguous())
16219       return nullptr;
16220 
16221     if (Previous.empty()) {
16222       // Name lookup did not find anything. However, if the
16223       // nested-name-specifier refers to the current instantiation,
16224       // and that current instantiation has any dependent base
16225       // classes, we might find something at instantiation time: treat
16226       // this as a dependent elaborated-type-specifier.
16227       // But this only makes any sense for reference-like lookups.
16228       if (Previous.wasNotFoundInCurrentInstantiation() &&
16229           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16230         IsDependent = true;
16231         return nullptr;
16232       }
16233 
16234       // A tag 'foo::bar' must already exist.
16235       Diag(NameLoc, diag::err_not_tag_in_scope)
16236         << Kind << Name << DC << SS.getRange();
16237       Name = nullptr;
16238       Invalid = true;
16239       goto CreateNewDecl;
16240     }
16241   } else if (Name) {
16242     // C++14 [class.mem]p14:
16243     //   If T is the name of a class, then each of the following shall have a
16244     //   name different from T:
16245     //    -- every member of class T that is itself a type
16246     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16247         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16248       return nullptr;
16249 
16250     // If this is a named struct, check to see if there was a previous forward
16251     // declaration or definition.
16252     // FIXME: We're looking into outer scopes here, even when we
16253     // shouldn't be. Doing so can result in ambiguities that we
16254     // shouldn't be diagnosing.
16255     LookupName(Previous, S);
16256 
16257     // When declaring or defining a tag, ignore ambiguities introduced
16258     // by types using'ed into this scope.
16259     if (Previous.isAmbiguous() &&
16260         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16261       LookupResult::Filter F = Previous.makeFilter();
16262       while (F.hasNext()) {
16263         NamedDecl *ND = F.next();
16264         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16265                 SearchDC->getRedeclContext()))
16266           F.erase();
16267       }
16268       F.done();
16269     }
16270 
16271     // C++11 [namespace.memdef]p3:
16272     //   If the name in a friend declaration is neither qualified nor
16273     //   a template-id and the declaration is a function or an
16274     //   elaborated-type-specifier, the lookup to determine whether
16275     //   the entity has been previously declared shall not consider
16276     //   any scopes outside the innermost enclosing namespace.
16277     //
16278     // MSVC doesn't implement the above rule for types, so a friend tag
16279     // declaration may be a redeclaration of a type declared in an enclosing
16280     // scope.  They do implement this rule for friend functions.
16281     //
16282     // Does it matter that this should be by scope instead of by
16283     // semantic context?
16284     if (!Previous.empty() && TUK == TUK_Friend) {
16285       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16286       LookupResult::Filter F = Previous.makeFilter();
16287       bool FriendSawTagOutsideEnclosingNamespace = false;
16288       while (F.hasNext()) {
16289         NamedDecl *ND = F.next();
16290         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16291         if (DC->isFileContext() &&
16292             !EnclosingNS->Encloses(ND->getDeclContext())) {
16293           if (getLangOpts().MSVCCompat)
16294             FriendSawTagOutsideEnclosingNamespace = true;
16295           else
16296             F.erase();
16297         }
16298       }
16299       F.done();
16300 
16301       // Diagnose this MSVC extension in the easy case where lookup would have
16302       // unambiguously found something outside the enclosing namespace.
16303       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16304         NamedDecl *ND = Previous.getFoundDecl();
16305         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16306             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16307       }
16308     }
16309 
16310     // Note:  there used to be some attempt at recovery here.
16311     if (Previous.isAmbiguous())
16312       return nullptr;
16313 
16314     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16315       // FIXME: This makes sure that we ignore the contexts associated
16316       // with C structs, unions, and enums when looking for a matching
16317       // tag declaration or definition. See the similar lookup tweak
16318       // in Sema::LookupName; is there a better way to deal with this?
16319       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16320         SearchDC = SearchDC->getParent();
16321     } else if (getLangOpts().CPlusPlus) {
16322       // Inside ObjCContainer want to keep it as a lexical decl context but go
16323       // past it (most often to TranslationUnit) to find the semantic decl
16324       // context.
16325       while (isa<ObjCContainerDecl>(SearchDC))
16326         SearchDC = SearchDC->getParent();
16327     }
16328   } else if (getLangOpts().CPlusPlus) {
16329     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16330     // TagDecl the same way as we skip it for named TagDecl.
16331     while (isa<ObjCContainerDecl>(SearchDC))
16332       SearchDC = SearchDC->getParent();
16333   }
16334 
16335   if (Previous.isSingleResult() &&
16336       Previous.getFoundDecl()->isTemplateParameter()) {
16337     // Maybe we will complain about the shadowed template parameter.
16338     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16339     // Just pretend that we didn't see the previous declaration.
16340     Previous.clear();
16341   }
16342 
16343   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16344       DC->Equals(getStdNamespace())) {
16345     if (Name->isStr("bad_alloc")) {
16346       // This is a declaration of or a reference to "std::bad_alloc".
16347       isStdBadAlloc = true;
16348 
16349       // If std::bad_alloc has been implicitly declared (but made invisible to
16350       // name lookup), fill in this implicit declaration as the previous
16351       // declaration, so that the declarations get chained appropriately.
16352       if (Previous.empty() && StdBadAlloc)
16353         Previous.addDecl(getStdBadAlloc());
16354     } else if (Name->isStr("align_val_t")) {
16355       isStdAlignValT = true;
16356       if (Previous.empty() && StdAlignValT)
16357         Previous.addDecl(getStdAlignValT());
16358     }
16359   }
16360 
16361   // If we didn't find a previous declaration, and this is a reference
16362   // (or friend reference), move to the correct scope.  In C++, we
16363   // also need to do a redeclaration lookup there, just in case
16364   // there's a shadow friend decl.
16365   if (Name && Previous.empty() &&
16366       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16367     if (Invalid) goto CreateNewDecl;
16368     assert(SS.isEmpty());
16369 
16370     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16371       // C++ [basic.scope.pdecl]p5:
16372       //   -- for an elaborated-type-specifier of the form
16373       //
16374       //          class-key identifier
16375       //
16376       //      if the elaborated-type-specifier is used in the
16377       //      decl-specifier-seq or parameter-declaration-clause of a
16378       //      function defined in namespace scope, the identifier is
16379       //      declared as a class-name in the namespace that contains
16380       //      the declaration; otherwise, except as a friend
16381       //      declaration, the identifier is declared in the smallest
16382       //      non-class, non-function-prototype scope that contains the
16383       //      declaration.
16384       //
16385       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16386       // C structs and unions.
16387       //
16388       // It is an error in C++ to declare (rather than define) an enum
16389       // type, including via an elaborated type specifier.  We'll
16390       // diagnose that later; for now, declare the enum in the same
16391       // scope as we would have picked for any other tag type.
16392       //
16393       // GNU C also supports this behavior as part of its incomplete
16394       // enum types extension, while GNU C++ does not.
16395       //
16396       // Find the context where we'll be declaring the tag.
16397       // FIXME: We would like to maintain the current DeclContext as the
16398       // lexical context,
16399       SearchDC = getTagInjectionContext(SearchDC);
16400 
16401       // Find the scope where we'll be declaring the tag.
16402       S = getTagInjectionScope(S, getLangOpts());
16403     } else {
16404       assert(TUK == TUK_Friend);
16405       // C++ [namespace.memdef]p3:
16406       //   If a friend declaration in a non-local class first declares a
16407       //   class or function, the friend class or function is a member of
16408       //   the innermost enclosing namespace.
16409       SearchDC = SearchDC->getEnclosingNamespaceContext();
16410     }
16411 
16412     // In C++, we need to do a redeclaration lookup to properly
16413     // diagnose some problems.
16414     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16415     // hidden declaration so that we don't get ambiguity errors when using a
16416     // type declared by an elaborated-type-specifier.  In C that is not correct
16417     // and we should instead merge compatible types found by lookup.
16418     if (getLangOpts().CPlusPlus) {
16419       // FIXME: This can perform qualified lookups into function contexts,
16420       // which are meaningless.
16421       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16422       LookupQualifiedName(Previous, SearchDC);
16423     } else {
16424       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16425       LookupName(Previous, S);
16426     }
16427   }
16428 
16429   // If we have a known previous declaration to use, then use it.
16430   if (Previous.empty() && SkipBody && SkipBody->Previous)
16431     Previous.addDecl(SkipBody->Previous);
16432 
16433   if (!Previous.empty()) {
16434     NamedDecl *PrevDecl = Previous.getFoundDecl();
16435     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16436 
16437     // It's okay to have a tag decl in the same scope as a typedef
16438     // which hides a tag decl in the same scope.  Finding this
16439     // with a redeclaration lookup can only actually happen in C++.
16440     //
16441     // This is also okay for elaborated-type-specifiers, which is
16442     // technically forbidden by the current standard but which is
16443     // okay according to the likely resolution of an open issue;
16444     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16445     if (getLangOpts().CPlusPlus) {
16446       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16447         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16448           TagDecl *Tag = TT->getDecl();
16449           if (Tag->getDeclName() == Name &&
16450               Tag->getDeclContext()->getRedeclContext()
16451                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16452             PrevDecl = Tag;
16453             Previous.clear();
16454             Previous.addDecl(Tag);
16455             Previous.resolveKind();
16456           }
16457         }
16458       }
16459     }
16460 
16461     // If this is a redeclaration of a using shadow declaration, it must
16462     // declare a tag in the same context. In MSVC mode, we allow a
16463     // redefinition if either context is within the other.
16464     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16465       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16466       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16467           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16468           !(OldTag && isAcceptableTagRedeclContext(
16469                           *this, OldTag->getDeclContext(), SearchDC))) {
16470         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16471         Diag(Shadow->getTargetDecl()->getLocation(),
16472              diag::note_using_decl_target);
16473         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16474             << 0;
16475         // Recover by ignoring the old declaration.
16476         Previous.clear();
16477         goto CreateNewDecl;
16478       }
16479     }
16480 
16481     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16482       // If this is a use of a previous tag, or if the tag is already declared
16483       // in the same scope (so that the definition/declaration completes or
16484       // rementions the tag), reuse the decl.
16485       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16486           isDeclInScope(DirectPrevDecl, SearchDC, S,
16487                         SS.isNotEmpty() || isMemberSpecialization)) {
16488         // Make sure that this wasn't declared as an enum and now used as a
16489         // struct or something similar.
16490         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16491                                           TUK == TUK_Definition, KWLoc,
16492                                           Name)) {
16493           bool SafeToContinue
16494             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16495                Kind != TTK_Enum);
16496           if (SafeToContinue)
16497             Diag(KWLoc, diag::err_use_with_wrong_tag)
16498               << Name
16499               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16500                                               PrevTagDecl->getKindName());
16501           else
16502             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16503           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16504 
16505           if (SafeToContinue)
16506             Kind = PrevTagDecl->getTagKind();
16507           else {
16508             // Recover by making this an anonymous redefinition.
16509             Name = nullptr;
16510             Previous.clear();
16511             Invalid = true;
16512           }
16513         }
16514 
16515         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16516           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16517           if (TUK == TUK_Reference || TUK == TUK_Friend)
16518             return PrevTagDecl;
16519 
16520           QualType EnumUnderlyingTy;
16521           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16522             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16523           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16524             EnumUnderlyingTy = QualType(T, 0);
16525 
16526           // All conflicts with previous declarations are recovered by
16527           // returning the previous declaration, unless this is a definition,
16528           // in which case we want the caller to bail out.
16529           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16530                                      ScopedEnum, EnumUnderlyingTy,
16531                                      IsFixed, PrevEnum))
16532             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16533         }
16534 
16535         // C++11 [class.mem]p1:
16536         //   A member shall not be declared twice in the member-specification,
16537         //   except that a nested class or member class template can be declared
16538         //   and then later defined.
16539         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16540             S->isDeclScope(PrevDecl)) {
16541           Diag(NameLoc, diag::ext_member_redeclared);
16542           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16543         }
16544 
16545         if (!Invalid) {
16546           // If this is a use, just return the declaration we found, unless
16547           // we have attributes.
16548           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16549             if (!Attrs.empty()) {
16550               // FIXME: Diagnose these attributes. For now, we create a new
16551               // declaration to hold them.
16552             } else if (TUK == TUK_Reference &&
16553                        (PrevTagDecl->getFriendObjectKind() ==
16554                             Decl::FOK_Undeclared ||
16555                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16556                        SS.isEmpty()) {
16557               // This declaration is a reference to an existing entity, but
16558               // has different visibility from that entity: it either makes
16559               // a friend visible or it makes a type visible in a new module.
16560               // In either case, create a new declaration. We only do this if
16561               // the declaration would have meant the same thing if no prior
16562               // declaration were found, that is, if it was found in the same
16563               // scope where we would have injected a declaration.
16564               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16565                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16566                 return PrevTagDecl;
16567               // This is in the injected scope, create a new declaration in
16568               // that scope.
16569               S = getTagInjectionScope(S, getLangOpts());
16570             } else {
16571               return PrevTagDecl;
16572             }
16573           }
16574 
16575           // Diagnose attempts to redefine a tag.
16576           if (TUK == TUK_Definition) {
16577             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16578               // If we're defining a specialization and the previous definition
16579               // is from an implicit instantiation, don't emit an error
16580               // here; we'll catch this in the general case below.
16581               bool IsExplicitSpecializationAfterInstantiation = false;
16582               if (isMemberSpecialization) {
16583                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16584                   IsExplicitSpecializationAfterInstantiation =
16585                     RD->getTemplateSpecializationKind() !=
16586                     TSK_ExplicitSpecialization;
16587                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16588                   IsExplicitSpecializationAfterInstantiation =
16589                     ED->getTemplateSpecializationKind() !=
16590                     TSK_ExplicitSpecialization;
16591               }
16592 
16593               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16594               // not keep more that one definition around (merge them). However,
16595               // ensure the decl passes the structural compatibility check in
16596               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16597               NamedDecl *Hidden = nullptr;
16598               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16599                 // There is a definition of this tag, but it is not visible. We
16600                 // explicitly make use of C++'s one definition rule here, and
16601                 // assume that this definition is identical to the hidden one
16602                 // we already have. Make the existing definition visible and
16603                 // use it in place of this one.
16604                 if (!getLangOpts().CPlusPlus) {
16605                   // Postpone making the old definition visible until after we
16606                   // complete parsing the new one and do the structural
16607                   // comparison.
16608                   SkipBody->CheckSameAsPrevious = true;
16609                   SkipBody->New = createTagFromNewDecl();
16610                   SkipBody->Previous = Def;
16611                   return Def;
16612                 } else {
16613                   SkipBody->ShouldSkip = true;
16614                   SkipBody->Previous = Def;
16615                   makeMergedDefinitionVisible(Hidden);
16616                   // Carry on and handle it like a normal definition. We'll
16617                   // skip starting the definitiion later.
16618                 }
16619               } else if (!IsExplicitSpecializationAfterInstantiation) {
16620                 // A redeclaration in function prototype scope in C isn't
16621                 // visible elsewhere, so merely issue a warning.
16622                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16623                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16624                 else
16625                   Diag(NameLoc, diag::err_redefinition) << Name;
16626                 notePreviousDefinition(Def,
16627                                        NameLoc.isValid() ? NameLoc : KWLoc);
16628                 // If this is a redefinition, recover by making this
16629                 // struct be anonymous, which will make any later
16630                 // references get the previous definition.
16631                 Name = nullptr;
16632                 Previous.clear();
16633                 Invalid = true;
16634               }
16635             } else {
16636               // If the type is currently being defined, complain
16637               // about a nested redefinition.
16638               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16639               if (TD->isBeingDefined()) {
16640                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16641                 Diag(PrevTagDecl->getLocation(),
16642                      diag::note_previous_definition);
16643                 Name = nullptr;
16644                 Previous.clear();
16645                 Invalid = true;
16646               }
16647             }
16648 
16649             // Okay, this is definition of a previously declared or referenced
16650             // tag. We're going to create a new Decl for it.
16651           }
16652 
16653           // Okay, we're going to make a redeclaration.  If this is some kind
16654           // of reference, make sure we build the redeclaration in the same DC
16655           // as the original, and ignore the current access specifier.
16656           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16657             SearchDC = PrevTagDecl->getDeclContext();
16658             AS = AS_none;
16659           }
16660         }
16661         // If we get here we have (another) forward declaration or we
16662         // have a definition.  Just create a new decl.
16663 
16664       } else {
16665         // If we get here, this is a definition of a new tag type in a nested
16666         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16667         // new decl/type.  We set PrevDecl to NULL so that the entities
16668         // have distinct types.
16669         Previous.clear();
16670       }
16671       // If we get here, we're going to create a new Decl. If PrevDecl
16672       // is non-NULL, it's a definition of the tag declared by
16673       // PrevDecl. If it's NULL, we have a new definition.
16674 
16675     // Otherwise, PrevDecl is not a tag, but was found with tag
16676     // lookup.  This is only actually possible in C++, where a few
16677     // things like templates still live in the tag namespace.
16678     } else {
16679       // Use a better diagnostic if an elaborated-type-specifier
16680       // found the wrong kind of type on the first
16681       // (non-redeclaration) lookup.
16682       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16683           !Previous.isForRedeclaration()) {
16684         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16685         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16686                                                        << Kind;
16687         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16688         Invalid = true;
16689 
16690       // Otherwise, only diagnose if the declaration is in scope.
16691       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16692                                 SS.isNotEmpty() || isMemberSpecialization)) {
16693         // do nothing
16694 
16695       // Diagnose implicit declarations introduced by elaborated types.
16696       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16697         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16698         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16699         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16700         Invalid = true;
16701 
16702       // Otherwise it's a declaration.  Call out a particularly common
16703       // case here.
16704       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16705         unsigned Kind = 0;
16706         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16707         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16708           << Name << Kind << TND->getUnderlyingType();
16709         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16710         Invalid = true;
16711 
16712       // Otherwise, diagnose.
16713       } else {
16714         // The tag name clashes with something else in the target scope,
16715         // issue an error and recover by making this tag be anonymous.
16716         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16717         notePreviousDefinition(PrevDecl, NameLoc);
16718         Name = nullptr;
16719         Invalid = true;
16720       }
16721 
16722       // The existing declaration isn't relevant to us; we're in a
16723       // new scope, so clear out the previous declaration.
16724       Previous.clear();
16725     }
16726   }
16727 
16728 CreateNewDecl:
16729 
16730   TagDecl *PrevDecl = nullptr;
16731   if (Previous.isSingleResult())
16732     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16733 
16734   // If there is an identifier, use the location of the identifier as the
16735   // location of the decl, otherwise use the location of the struct/union
16736   // keyword.
16737   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16738 
16739   // Otherwise, create a new declaration. If there is a previous
16740   // declaration of the same entity, the two will be linked via
16741   // PrevDecl.
16742   TagDecl *New;
16743 
16744   if (Kind == TTK_Enum) {
16745     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16746     // enum X { A, B, C } D;    D should chain to X.
16747     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16748                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16749                            ScopedEnumUsesClassTag, IsFixed);
16750 
16751     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16752       StdAlignValT = cast<EnumDecl>(New);
16753 
16754     // If this is an undefined enum, warn.
16755     if (TUK != TUK_Definition && !Invalid) {
16756       TagDecl *Def;
16757       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16758         // C++0x: 7.2p2: opaque-enum-declaration.
16759         // Conflicts are diagnosed above. Do nothing.
16760       }
16761       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16762         Diag(Loc, diag::ext_forward_ref_enum_def)
16763           << New;
16764         Diag(Def->getLocation(), diag::note_previous_definition);
16765       } else {
16766         unsigned DiagID = diag::ext_forward_ref_enum;
16767         if (getLangOpts().MSVCCompat)
16768           DiagID = diag::ext_ms_forward_ref_enum;
16769         else if (getLangOpts().CPlusPlus)
16770           DiagID = diag::err_forward_ref_enum;
16771         Diag(Loc, DiagID);
16772       }
16773     }
16774 
16775     if (EnumUnderlying) {
16776       EnumDecl *ED = cast<EnumDecl>(New);
16777       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16778         ED->setIntegerTypeSourceInfo(TI);
16779       else
16780         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16781       ED->setPromotionType(ED->getIntegerType());
16782       assert(ED->isComplete() && "enum with type should be complete");
16783     }
16784   } else {
16785     // struct/union/class
16786 
16787     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16788     // struct X { int A; } D;    D should chain to X.
16789     if (getLangOpts().CPlusPlus) {
16790       // FIXME: Look for a way to use RecordDecl for simple structs.
16791       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16792                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16793 
16794       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16795         StdBadAlloc = cast<CXXRecordDecl>(New);
16796     } else
16797       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16798                                cast_or_null<RecordDecl>(PrevDecl));
16799   }
16800 
16801   // C++11 [dcl.type]p3:
16802   //   A type-specifier-seq shall not define a class or enumeration [...].
16803   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16804       TUK == TUK_Definition) {
16805     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16806       << Context.getTagDeclType(New);
16807     Invalid = true;
16808   }
16809 
16810   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16811       DC->getDeclKind() == Decl::Enum) {
16812     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16813       << Context.getTagDeclType(New);
16814     Invalid = true;
16815   }
16816 
16817   // Maybe add qualifier info.
16818   if (SS.isNotEmpty()) {
16819     if (SS.isSet()) {
16820       // If this is either a declaration or a definition, check the
16821       // nested-name-specifier against the current context.
16822       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16823           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16824                                        isMemberSpecialization))
16825         Invalid = true;
16826 
16827       New->setQualifierInfo(SS.getWithLocInContext(Context));
16828       if (TemplateParameterLists.size() > 0) {
16829         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16830       }
16831     }
16832     else
16833       Invalid = true;
16834   }
16835 
16836   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16837     // Add alignment attributes if necessary; these attributes are checked when
16838     // the ASTContext lays out the structure.
16839     //
16840     // It is important for implementing the correct semantics that this
16841     // happen here (in ActOnTag). The #pragma pack stack is
16842     // maintained as a result of parser callbacks which can occur at
16843     // many points during the parsing of a struct declaration (because
16844     // the #pragma tokens are effectively skipped over during the
16845     // parsing of the struct).
16846     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16847       AddAlignmentAttributesForRecord(RD);
16848       AddMsStructLayoutForRecord(RD);
16849     }
16850   }
16851 
16852   if (ModulePrivateLoc.isValid()) {
16853     if (isMemberSpecialization)
16854       Diag(New->getLocation(), diag::err_module_private_specialization)
16855         << 2
16856         << FixItHint::CreateRemoval(ModulePrivateLoc);
16857     // __module_private__ does not apply to local classes. However, we only
16858     // diagnose this as an error when the declaration specifiers are
16859     // freestanding. Here, we just ignore the __module_private__.
16860     else if (!SearchDC->isFunctionOrMethod())
16861       New->setModulePrivate();
16862   }
16863 
16864   // If this is a specialization of a member class (of a class template),
16865   // check the specialization.
16866   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16867     Invalid = true;
16868 
16869   // If we're declaring or defining a tag in function prototype scope in C,
16870   // note that this type can only be used within the function and add it to
16871   // the list of decls to inject into the function definition scope.
16872   if ((Name || Kind == TTK_Enum) &&
16873       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16874     if (getLangOpts().CPlusPlus) {
16875       // C++ [dcl.fct]p6:
16876       //   Types shall not be defined in return or parameter types.
16877       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16878         Diag(Loc, diag::err_type_defined_in_param_type)
16879             << Name;
16880         Invalid = true;
16881       }
16882     } else if (!PrevDecl) {
16883       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16884     }
16885   }
16886 
16887   if (Invalid)
16888     New->setInvalidDecl();
16889 
16890   // Set the lexical context. If the tag has a C++ scope specifier, the
16891   // lexical context will be different from the semantic context.
16892   New->setLexicalDeclContext(CurContext);
16893 
16894   // Mark this as a friend decl if applicable.
16895   // In Microsoft mode, a friend declaration also acts as a forward
16896   // declaration so we always pass true to setObjectOfFriendDecl to make
16897   // the tag name visible.
16898   if (TUK == TUK_Friend)
16899     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16900 
16901   // Set the access specifier.
16902   if (!Invalid && SearchDC->isRecord())
16903     SetMemberAccessSpecifier(New, PrevDecl, AS);
16904 
16905   if (PrevDecl)
16906     CheckRedeclarationInModule(New, PrevDecl);
16907 
16908   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16909     New->startDefinition();
16910 
16911   ProcessDeclAttributeList(S, New, Attrs);
16912   AddPragmaAttributes(S, New);
16913 
16914   // If this has an identifier, add it to the scope stack.
16915   if (TUK == TUK_Friend) {
16916     // We might be replacing an existing declaration in the lookup tables;
16917     // if so, borrow its access specifier.
16918     if (PrevDecl)
16919       New->setAccess(PrevDecl->getAccess());
16920 
16921     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16922     DC->makeDeclVisibleInContext(New);
16923     if (Name) // can be null along some error paths
16924       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16925         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16926   } else if (Name) {
16927     S = getNonFieldDeclScope(S);
16928     PushOnScopeChains(New, S, true);
16929   } else {
16930     CurContext->addDecl(New);
16931   }
16932 
16933   // If this is the C FILE type, notify the AST context.
16934   if (IdentifierInfo *II = New->getIdentifier())
16935     if (!New->isInvalidDecl() &&
16936         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16937         II->isStr("FILE"))
16938       Context.setFILEDecl(New);
16939 
16940   if (PrevDecl)
16941     mergeDeclAttributes(New, PrevDecl);
16942 
16943   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16944     inferGslOwnerPointerAttribute(CXXRD);
16945 
16946   // If there's a #pragma GCC visibility in scope, set the visibility of this
16947   // record.
16948   AddPushedVisibilityAttribute(New);
16949 
16950   if (isMemberSpecialization && !New->isInvalidDecl())
16951     CompleteMemberSpecialization(New, Previous);
16952 
16953   OwnedDecl = true;
16954   // In C++, don't return an invalid declaration. We can't recover well from
16955   // the cases where we make the type anonymous.
16956   if (Invalid && getLangOpts().CPlusPlus) {
16957     if (New->isBeingDefined())
16958       if (auto RD = dyn_cast<RecordDecl>(New))
16959         RD->completeDefinition();
16960     return nullptr;
16961   } else if (SkipBody && SkipBody->ShouldSkip) {
16962     return SkipBody->Previous;
16963   } else {
16964     return New;
16965   }
16966 }
16967 
16968 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16969   AdjustDeclIfTemplate(TagD);
16970   TagDecl *Tag = cast<TagDecl>(TagD);
16971 
16972   // Enter the tag context.
16973   PushDeclContext(S, Tag);
16974 
16975   ActOnDocumentableDecl(TagD);
16976 
16977   // If there's a #pragma GCC visibility in scope, set the visibility of this
16978   // record.
16979   AddPushedVisibilityAttribute(Tag);
16980 }
16981 
16982 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16983   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16984     return false;
16985 
16986   // Make the previous decl visible.
16987   makeMergedDefinitionVisible(SkipBody.Previous);
16988   return true;
16989 }
16990 
16991 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
16992   assert(IDecl->getLexicalParent() == CurContext &&
16993       "The next DeclContext should be lexically contained in the current one.");
16994   CurContext = IDecl;
16995 }
16996 
16997 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16998                                            SourceLocation FinalLoc,
16999                                            bool IsFinalSpelledSealed,
17000                                            bool IsAbstract,
17001                                            SourceLocation LBraceLoc) {
17002   AdjustDeclIfTemplate(TagD);
17003   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17004 
17005   FieldCollector->StartClass();
17006 
17007   if (!Record->getIdentifier())
17008     return;
17009 
17010   if (IsAbstract)
17011     Record->markAbstract();
17012 
17013   if (FinalLoc.isValid()) {
17014     Record->addAttr(FinalAttr::Create(
17015         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17016         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17017   }
17018   // C++ [class]p2:
17019   //   [...] The class-name is also inserted into the scope of the
17020   //   class itself; this is known as the injected-class-name. For
17021   //   purposes of access checking, the injected-class-name is treated
17022   //   as if it were a public member name.
17023   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17024       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17025       Record->getLocation(), Record->getIdentifier(),
17026       /*PrevDecl=*/nullptr,
17027       /*DelayTypeCreation=*/true);
17028   Context.getTypeDeclType(InjectedClassName, Record);
17029   InjectedClassName->setImplicit();
17030   InjectedClassName->setAccess(AS_public);
17031   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17032       InjectedClassName->setDescribedClassTemplate(Template);
17033   PushOnScopeChains(InjectedClassName, S);
17034   assert(InjectedClassName->isInjectedClassName() &&
17035          "Broken injected-class-name");
17036 }
17037 
17038 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17039                                     SourceRange BraceRange) {
17040   AdjustDeclIfTemplate(TagD);
17041   TagDecl *Tag = cast<TagDecl>(TagD);
17042   Tag->setBraceRange(BraceRange);
17043 
17044   // Make sure we "complete" the definition even it is invalid.
17045   if (Tag->isBeingDefined()) {
17046     assert(Tag->isInvalidDecl() && "We should already have completed it");
17047     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17048       RD->completeDefinition();
17049   }
17050 
17051   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17052     FieldCollector->FinishClass();
17053     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17054       auto *Def = RD->getDefinition();
17055       assert(Def && "The record is expected to have a completed definition");
17056       unsigned NumInitMethods = 0;
17057       for (auto *Method : Def->methods()) {
17058         if (!Method->getIdentifier())
17059             continue;
17060         if (Method->getName() == "__init")
17061           NumInitMethods++;
17062       }
17063       if (NumInitMethods > 1 || !Def->hasInitMethod())
17064         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17065     }
17066   }
17067 
17068   // Exit this scope of this tag's definition.
17069   PopDeclContext();
17070 
17071   if (getCurLexicalContext()->isObjCContainer() &&
17072       Tag->getDeclContext()->isFileContext())
17073     Tag->setTopLevelDeclInObjCContainer();
17074 
17075   // Notify the consumer that we've defined a tag.
17076   if (!Tag->isInvalidDecl())
17077     Consumer.HandleTagDeclDefinition(Tag);
17078 
17079   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17080   // from XLs and instead matches the XL #pragma pack(1) behavior.
17081   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17082       AlignPackStack.hasValue()) {
17083     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17084     // Only diagnose #pragma align(packed).
17085     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17086       return;
17087     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17088     if (!RD)
17089       return;
17090     // Only warn if there is at least 1 bitfield member.
17091     if (llvm::any_of(RD->fields(),
17092                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17093       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17094   }
17095 }
17096 
17097 void Sema::ActOnObjCContainerFinishDefinition() {
17098   // Exit this scope of this interface definition.
17099   PopDeclContext();
17100 }
17101 
17102 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17103   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17104   OriginalLexicalContext = ObjCCtx;
17105   ActOnObjCContainerFinishDefinition();
17106 }
17107 
17108 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17109   ActOnObjCContainerStartDefinition(ObjCCtx);
17110   OriginalLexicalContext = nullptr;
17111 }
17112 
17113 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17114   AdjustDeclIfTemplate(TagD);
17115   TagDecl *Tag = cast<TagDecl>(TagD);
17116   Tag->setInvalidDecl();
17117 
17118   // Make sure we "complete" the definition even it is invalid.
17119   if (Tag->isBeingDefined()) {
17120     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17121       RD->completeDefinition();
17122   }
17123 
17124   // We're undoing ActOnTagStartDefinition here, not
17125   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17126   // the FieldCollector.
17127 
17128   PopDeclContext();
17129 }
17130 
17131 // Note that FieldName may be null for anonymous bitfields.
17132 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17133                                 IdentifierInfo *FieldName,
17134                                 QualType FieldTy, bool IsMsStruct,
17135                                 Expr *BitWidth, bool *ZeroWidth) {
17136   assert(BitWidth);
17137   if (BitWidth->containsErrors())
17138     return ExprError();
17139 
17140   // Default to true; that shouldn't confuse checks for emptiness
17141   if (ZeroWidth)
17142     *ZeroWidth = true;
17143 
17144   // C99 6.7.2.1p4 - verify the field type.
17145   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17146   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17147     // Handle incomplete and sizeless types with a specific error.
17148     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17149                                  diag::err_field_incomplete_or_sizeless))
17150       return ExprError();
17151     if (FieldName)
17152       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17153         << FieldName << FieldTy << BitWidth->getSourceRange();
17154     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17155       << FieldTy << BitWidth->getSourceRange();
17156   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17157                                              UPPC_BitFieldWidth))
17158     return ExprError();
17159 
17160   // If the bit-width is type- or value-dependent, don't try to check
17161   // it now.
17162   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17163     return BitWidth;
17164 
17165   llvm::APSInt Value;
17166   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17167   if (ICE.isInvalid())
17168     return ICE;
17169   BitWidth = ICE.get();
17170 
17171   if (Value != 0 && ZeroWidth)
17172     *ZeroWidth = false;
17173 
17174   // Zero-width bitfield is ok for anonymous field.
17175   if (Value == 0 && FieldName)
17176     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17177 
17178   if (Value.isSigned() && Value.isNegative()) {
17179     if (FieldName)
17180       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17181                << FieldName << toString(Value, 10);
17182     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17183       << toString(Value, 10);
17184   }
17185 
17186   // The size of the bit-field must not exceed our maximum permitted object
17187   // size.
17188   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17189     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17190            << !FieldName << FieldName << toString(Value, 10);
17191   }
17192 
17193   if (!FieldTy->isDependentType()) {
17194     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17195     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17196     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17197 
17198     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17199     // ABI.
17200     bool CStdConstraintViolation =
17201         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17202     bool MSBitfieldViolation =
17203         Value.ugt(TypeStorageSize) &&
17204         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17205     if (CStdConstraintViolation || MSBitfieldViolation) {
17206       unsigned DiagWidth =
17207           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17208       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17209              << (bool)FieldName << FieldName << toString(Value, 10)
17210              << !CStdConstraintViolation << DiagWidth;
17211     }
17212 
17213     // Warn on types where the user might conceivably expect to get all
17214     // specified bits as value bits: that's all integral types other than
17215     // 'bool'.
17216     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17217       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17218           << FieldName << toString(Value, 10)
17219           << (unsigned)TypeWidth;
17220     }
17221   }
17222 
17223   return BitWidth;
17224 }
17225 
17226 /// ActOnField - Each field of a C struct/union is passed into this in order
17227 /// to create a FieldDecl object for it.
17228 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17229                        Declarator &D, Expr *BitfieldWidth) {
17230   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17231                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17232                                /*InitStyle=*/ICIS_NoInit, AS_public);
17233   return Res;
17234 }
17235 
17236 /// HandleField - Analyze a field of a C struct or a C++ data member.
17237 ///
17238 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17239                              SourceLocation DeclStart,
17240                              Declarator &D, Expr *BitWidth,
17241                              InClassInitStyle InitStyle,
17242                              AccessSpecifier AS) {
17243   if (D.isDecompositionDeclarator()) {
17244     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17245     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17246       << Decomp.getSourceRange();
17247     return nullptr;
17248   }
17249 
17250   IdentifierInfo *II = D.getIdentifier();
17251   SourceLocation Loc = DeclStart;
17252   if (II) Loc = D.getIdentifierLoc();
17253 
17254   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17255   QualType T = TInfo->getType();
17256   if (getLangOpts().CPlusPlus) {
17257     CheckExtraCXXDefaultArguments(D);
17258 
17259     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17260                                         UPPC_DataMemberType)) {
17261       D.setInvalidType();
17262       T = Context.IntTy;
17263       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17264     }
17265   }
17266 
17267   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17268 
17269   if (D.getDeclSpec().isInlineSpecified())
17270     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17271         << getLangOpts().CPlusPlus17;
17272   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17273     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17274          diag::err_invalid_thread)
17275       << DeclSpec::getSpecifierName(TSCS);
17276 
17277   // Check to see if this name was declared as a member previously
17278   NamedDecl *PrevDecl = nullptr;
17279   LookupResult Previous(*this, II, Loc, LookupMemberName,
17280                         ForVisibleRedeclaration);
17281   LookupName(Previous, S);
17282   switch (Previous.getResultKind()) {
17283     case LookupResult::Found:
17284     case LookupResult::FoundUnresolvedValue:
17285       PrevDecl = Previous.getAsSingle<NamedDecl>();
17286       break;
17287 
17288     case LookupResult::FoundOverloaded:
17289       PrevDecl = Previous.getRepresentativeDecl();
17290       break;
17291 
17292     case LookupResult::NotFound:
17293     case LookupResult::NotFoundInCurrentInstantiation:
17294     case LookupResult::Ambiguous:
17295       break;
17296   }
17297   Previous.suppressDiagnostics();
17298 
17299   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17300     // Maybe we will complain about the shadowed template parameter.
17301     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17302     // Just pretend that we didn't see the previous declaration.
17303     PrevDecl = nullptr;
17304   }
17305 
17306   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17307     PrevDecl = nullptr;
17308 
17309   bool Mutable
17310     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17311   SourceLocation TSSL = D.getBeginLoc();
17312   FieldDecl *NewFD
17313     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17314                      TSSL, AS, PrevDecl, &D);
17315 
17316   if (NewFD->isInvalidDecl())
17317     Record->setInvalidDecl();
17318 
17319   if (D.getDeclSpec().isModulePrivateSpecified())
17320     NewFD->setModulePrivate();
17321 
17322   if (NewFD->isInvalidDecl() && PrevDecl) {
17323     // Don't introduce NewFD into scope; there's already something
17324     // with the same name in the same scope.
17325   } else if (II) {
17326     PushOnScopeChains(NewFD, S);
17327   } else
17328     Record->addDecl(NewFD);
17329 
17330   return NewFD;
17331 }
17332 
17333 /// Build a new FieldDecl and check its well-formedness.
17334 ///
17335 /// This routine builds a new FieldDecl given the fields name, type,
17336 /// record, etc. \p PrevDecl should refer to any previous declaration
17337 /// with the same name and in the same scope as the field to be
17338 /// created.
17339 ///
17340 /// \returns a new FieldDecl.
17341 ///
17342 /// \todo The Declarator argument is a hack. It will be removed once
17343 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17344                                 TypeSourceInfo *TInfo,
17345                                 RecordDecl *Record, SourceLocation Loc,
17346                                 bool Mutable, Expr *BitWidth,
17347                                 InClassInitStyle InitStyle,
17348                                 SourceLocation TSSL,
17349                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17350                                 Declarator *D) {
17351   IdentifierInfo *II = Name.getAsIdentifierInfo();
17352   bool InvalidDecl = false;
17353   if (D) InvalidDecl = D->isInvalidType();
17354 
17355   // If we receive a broken type, recover by assuming 'int' and
17356   // marking this declaration as invalid.
17357   if (T.isNull() || T->containsErrors()) {
17358     InvalidDecl = true;
17359     T = Context.IntTy;
17360   }
17361 
17362   QualType EltTy = Context.getBaseElementType(T);
17363   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17364     if (RequireCompleteSizedType(Loc, EltTy,
17365                                  diag::err_field_incomplete_or_sizeless)) {
17366       // Fields of incomplete type force their record to be invalid.
17367       Record->setInvalidDecl();
17368       InvalidDecl = true;
17369     } else {
17370       NamedDecl *Def;
17371       EltTy->isIncompleteType(&Def);
17372       if (Def && Def->isInvalidDecl()) {
17373         Record->setInvalidDecl();
17374         InvalidDecl = true;
17375       }
17376     }
17377   }
17378 
17379   // TR 18037 does not allow fields to be declared with address space
17380   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17381       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17382     Diag(Loc, diag::err_field_with_address_space);
17383     Record->setInvalidDecl();
17384     InvalidDecl = true;
17385   }
17386 
17387   if (LangOpts.OpenCL) {
17388     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17389     // used as structure or union field: image, sampler, event or block types.
17390     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17391         T->isBlockPointerType()) {
17392       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17393       Record->setInvalidDecl();
17394       InvalidDecl = true;
17395     }
17396     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17397     // is enabled.
17398     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17399                         "__cl_clang_bitfields", LangOpts)) {
17400       Diag(Loc, diag::err_opencl_bitfields);
17401       InvalidDecl = true;
17402     }
17403   }
17404 
17405   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17406   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17407       T.hasQualifiers()) {
17408     InvalidDecl = true;
17409     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17410   }
17411 
17412   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17413   // than a variably modified type.
17414   if (!InvalidDecl && T->isVariablyModifiedType()) {
17415     if (!tryToFixVariablyModifiedVarType(
17416             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17417       InvalidDecl = true;
17418   }
17419 
17420   // Fields can not have abstract class types
17421   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17422                                              diag::err_abstract_type_in_decl,
17423                                              AbstractFieldType))
17424     InvalidDecl = true;
17425 
17426   bool ZeroWidth = false;
17427   if (InvalidDecl)
17428     BitWidth = nullptr;
17429   // If this is declared as a bit-field, check the bit-field.
17430   if (BitWidth) {
17431     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17432                               &ZeroWidth).get();
17433     if (!BitWidth) {
17434       InvalidDecl = true;
17435       BitWidth = nullptr;
17436       ZeroWidth = false;
17437     }
17438   }
17439 
17440   // Check that 'mutable' is consistent with the type of the declaration.
17441   if (!InvalidDecl && Mutable) {
17442     unsigned DiagID = 0;
17443     if (T->isReferenceType())
17444       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17445                                         : diag::err_mutable_reference;
17446     else if (T.isConstQualified())
17447       DiagID = diag::err_mutable_const;
17448 
17449     if (DiagID) {
17450       SourceLocation ErrLoc = Loc;
17451       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17452         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17453       Diag(ErrLoc, DiagID);
17454       if (DiagID != diag::ext_mutable_reference) {
17455         Mutable = false;
17456         InvalidDecl = true;
17457       }
17458     }
17459   }
17460 
17461   // C++11 [class.union]p8 (DR1460):
17462   //   At most one variant member of a union may have a
17463   //   brace-or-equal-initializer.
17464   if (InitStyle != ICIS_NoInit)
17465     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17466 
17467   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17468                                        BitWidth, Mutable, InitStyle);
17469   if (InvalidDecl)
17470     NewFD->setInvalidDecl();
17471 
17472   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17473     Diag(Loc, diag::err_duplicate_member) << II;
17474     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17475     NewFD->setInvalidDecl();
17476   }
17477 
17478   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17479     if (Record->isUnion()) {
17480       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17481         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17482         if (RDecl->getDefinition()) {
17483           // C++ [class.union]p1: An object of a class with a non-trivial
17484           // constructor, a non-trivial copy constructor, a non-trivial
17485           // destructor, or a non-trivial copy assignment operator
17486           // cannot be a member of a union, nor can an array of such
17487           // objects.
17488           if (CheckNontrivialField(NewFD))
17489             NewFD->setInvalidDecl();
17490         }
17491       }
17492 
17493       // C++ [class.union]p1: If a union contains a member of reference type,
17494       // the program is ill-formed, except when compiling with MSVC extensions
17495       // enabled.
17496       if (EltTy->isReferenceType()) {
17497         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17498                                     diag::ext_union_member_of_reference_type :
17499                                     diag::err_union_member_of_reference_type)
17500           << NewFD->getDeclName() << EltTy;
17501         if (!getLangOpts().MicrosoftExt)
17502           NewFD->setInvalidDecl();
17503       }
17504     }
17505   }
17506 
17507   // FIXME: We need to pass in the attributes given an AST
17508   // representation, not a parser representation.
17509   if (D) {
17510     // FIXME: The current scope is almost... but not entirely... correct here.
17511     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17512 
17513     if (NewFD->hasAttrs())
17514       CheckAlignasUnderalignment(NewFD);
17515   }
17516 
17517   // In auto-retain/release, infer strong retension for fields of
17518   // retainable type.
17519   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17520     NewFD->setInvalidDecl();
17521 
17522   if (T.isObjCGCWeak())
17523     Diag(Loc, diag::warn_attribute_weak_on_field);
17524 
17525   // PPC MMA non-pointer types are not allowed as field types.
17526   if (Context.getTargetInfo().getTriple().isPPC64() &&
17527       CheckPPCMMAType(T, NewFD->getLocation()))
17528     NewFD->setInvalidDecl();
17529 
17530   NewFD->setAccess(AS);
17531   return NewFD;
17532 }
17533 
17534 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17535   assert(FD);
17536   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17537 
17538   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17539     return false;
17540 
17541   QualType EltTy = Context.getBaseElementType(FD->getType());
17542   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17543     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17544     if (RDecl->getDefinition()) {
17545       // We check for copy constructors before constructors
17546       // because otherwise we'll never get complaints about
17547       // copy constructors.
17548 
17549       CXXSpecialMember member = CXXInvalid;
17550       // We're required to check for any non-trivial constructors. Since the
17551       // implicit default constructor is suppressed if there are any
17552       // user-declared constructors, we just need to check that there is a
17553       // trivial default constructor and a trivial copy constructor. (We don't
17554       // worry about move constructors here, since this is a C++98 check.)
17555       if (RDecl->hasNonTrivialCopyConstructor())
17556         member = CXXCopyConstructor;
17557       else if (!RDecl->hasTrivialDefaultConstructor())
17558         member = CXXDefaultConstructor;
17559       else if (RDecl->hasNonTrivialCopyAssignment())
17560         member = CXXCopyAssignment;
17561       else if (RDecl->hasNonTrivialDestructor())
17562         member = CXXDestructor;
17563 
17564       if (member != CXXInvalid) {
17565         if (!getLangOpts().CPlusPlus11 &&
17566             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17567           // Objective-C++ ARC: it is an error to have a non-trivial field of
17568           // a union. However, system headers in Objective-C programs
17569           // occasionally have Objective-C lifetime objects within unions,
17570           // and rather than cause the program to fail, we make those
17571           // members unavailable.
17572           SourceLocation Loc = FD->getLocation();
17573           if (getSourceManager().isInSystemHeader(Loc)) {
17574             if (!FD->hasAttr<UnavailableAttr>())
17575               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17576                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17577             return false;
17578           }
17579         }
17580 
17581         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17582                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17583                diag::err_illegal_union_or_anon_struct_member)
17584           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17585         DiagnoseNontrivial(RDecl, member);
17586         return !getLangOpts().CPlusPlus11;
17587       }
17588     }
17589   }
17590 
17591   return false;
17592 }
17593 
17594 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17595 ///  AST enum value.
17596 static ObjCIvarDecl::AccessControl
17597 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17598   switch (ivarVisibility) {
17599   default: llvm_unreachable("Unknown visitibility kind");
17600   case tok::objc_private: return ObjCIvarDecl::Private;
17601   case tok::objc_public: return ObjCIvarDecl::Public;
17602   case tok::objc_protected: return ObjCIvarDecl::Protected;
17603   case tok::objc_package: return ObjCIvarDecl::Package;
17604   }
17605 }
17606 
17607 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17608 /// in order to create an IvarDecl object for it.
17609 Decl *Sema::ActOnIvar(Scope *S,
17610                                 SourceLocation DeclStart,
17611                                 Declarator &D, Expr *BitfieldWidth,
17612                                 tok::ObjCKeywordKind Visibility) {
17613 
17614   IdentifierInfo *II = D.getIdentifier();
17615   Expr *BitWidth = (Expr*)BitfieldWidth;
17616   SourceLocation Loc = DeclStart;
17617   if (II) Loc = D.getIdentifierLoc();
17618 
17619   // FIXME: Unnamed fields can be handled in various different ways, for
17620   // example, unnamed unions inject all members into the struct namespace!
17621 
17622   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17623   QualType T = TInfo->getType();
17624 
17625   if (BitWidth) {
17626     // 6.7.2.1p3, 6.7.2.1p4
17627     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17628     if (!BitWidth)
17629       D.setInvalidType();
17630   } else {
17631     // Not a bitfield.
17632 
17633     // validate II.
17634 
17635   }
17636   if (T->isReferenceType()) {
17637     Diag(Loc, diag::err_ivar_reference_type);
17638     D.setInvalidType();
17639   }
17640   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17641   // than a variably modified type.
17642   else if (T->isVariablyModifiedType()) {
17643     if (!tryToFixVariablyModifiedVarType(
17644             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17645       D.setInvalidType();
17646   }
17647 
17648   // Get the visibility (access control) for this ivar.
17649   ObjCIvarDecl::AccessControl ac =
17650     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17651                                         : ObjCIvarDecl::None;
17652   // Must set ivar's DeclContext to its enclosing interface.
17653   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17654   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17655     return nullptr;
17656   ObjCContainerDecl *EnclosingContext;
17657   if (ObjCImplementationDecl *IMPDecl =
17658       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17659     if (LangOpts.ObjCRuntime.isFragile()) {
17660     // Case of ivar declared in an implementation. Context is that of its class.
17661       EnclosingContext = IMPDecl->getClassInterface();
17662       assert(EnclosingContext && "Implementation has no class interface!");
17663     }
17664     else
17665       EnclosingContext = EnclosingDecl;
17666   } else {
17667     if (ObjCCategoryDecl *CDecl =
17668         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17669       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17670         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17671         return nullptr;
17672       }
17673     }
17674     EnclosingContext = EnclosingDecl;
17675   }
17676 
17677   // Construct the decl.
17678   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17679                                              DeclStart, Loc, II, T,
17680                                              TInfo, ac, (Expr *)BitfieldWidth);
17681 
17682   if (II) {
17683     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17684                                            ForVisibleRedeclaration);
17685     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17686         && !isa<TagDecl>(PrevDecl)) {
17687       Diag(Loc, diag::err_duplicate_member) << II;
17688       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17689       NewID->setInvalidDecl();
17690     }
17691   }
17692 
17693   // Process attributes attached to the ivar.
17694   ProcessDeclAttributes(S, NewID, D);
17695 
17696   if (D.isInvalidType())
17697     NewID->setInvalidDecl();
17698 
17699   // In ARC, infer 'retaining' for ivars of retainable type.
17700   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17701     NewID->setInvalidDecl();
17702 
17703   if (D.getDeclSpec().isModulePrivateSpecified())
17704     NewID->setModulePrivate();
17705 
17706   if (II) {
17707     // FIXME: When interfaces are DeclContexts, we'll need to add
17708     // these to the interface.
17709     S->AddDecl(NewID);
17710     IdResolver.AddDecl(NewID);
17711   }
17712 
17713   if (LangOpts.ObjCRuntime.isNonFragile() &&
17714       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17715     Diag(Loc, diag::warn_ivars_in_interface);
17716 
17717   return NewID;
17718 }
17719 
17720 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17721 /// class and class extensions. For every class \@interface and class
17722 /// extension \@interface, if the last ivar is a bitfield of any type,
17723 /// then add an implicit `char :0` ivar to the end of that interface.
17724 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17725                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17726   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17727     return;
17728 
17729   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17730   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17731 
17732   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17733     return;
17734   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17735   if (!ID) {
17736     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17737       if (!CD->IsClassExtension())
17738         return;
17739     }
17740     // No need to add this to end of @implementation.
17741     else
17742       return;
17743   }
17744   // All conditions are met. Add a new bitfield to the tail end of ivars.
17745   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17746   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17747 
17748   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17749                               DeclLoc, DeclLoc, nullptr,
17750                               Context.CharTy,
17751                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17752                                                                DeclLoc),
17753                               ObjCIvarDecl::Private, BW,
17754                               true);
17755   AllIvarDecls.push_back(Ivar);
17756 }
17757 
17758 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17759                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17760                        SourceLocation RBrac,
17761                        const ParsedAttributesView &Attrs) {
17762   assert(EnclosingDecl && "missing record or interface decl");
17763 
17764   // If this is an Objective-C @implementation or category and we have
17765   // new fields here we should reset the layout of the interface since
17766   // it will now change.
17767   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17768     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17769     switch (DC->getKind()) {
17770     default: break;
17771     case Decl::ObjCCategory:
17772       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17773       break;
17774     case Decl::ObjCImplementation:
17775       Context.
17776         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17777       break;
17778     }
17779   }
17780 
17781   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17782   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17783 
17784   // Start counting up the number of named members; make sure to include
17785   // members of anonymous structs and unions in the total.
17786   unsigned NumNamedMembers = 0;
17787   if (Record) {
17788     for (const auto *I : Record->decls()) {
17789       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17790         if (IFD->getDeclName())
17791           ++NumNamedMembers;
17792     }
17793   }
17794 
17795   // Verify that all the fields are okay.
17796   SmallVector<FieldDecl*, 32> RecFields;
17797 
17798   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17799        i != end; ++i) {
17800     FieldDecl *FD = cast<FieldDecl>(*i);
17801 
17802     // Get the type for the field.
17803     const Type *FDTy = FD->getType().getTypePtr();
17804 
17805     if (!FD->isAnonymousStructOrUnion()) {
17806       // Remember all fields written by the user.
17807       RecFields.push_back(FD);
17808     }
17809 
17810     // If the field is already invalid for some reason, don't emit more
17811     // diagnostics about it.
17812     if (FD->isInvalidDecl()) {
17813       EnclosingDecl->setInvalidDecl();
17814       continue;
17815     }
17816 
17817     // C99 6.7.2.1p2:
17818     //   A structure or union shall not contain a member with
17819     //   incomplete or function type (hence, a structure shall not
17820     //   contain an instance of itself, but may contain a pointer to
17821     //   an instance of itself), except that the last member of a
17822     //   structure with more than one named member may have incomplete
17823     //   array type; such a structure (and any union containing,
17824     //   possibly recursively, a member that is such a structure)
17825     //   shall not be a member of a structure or an element of an
17826     //   array.
17827     bool IsLastField = (i + 1 == Fields.end());
17828     if (FDTy->isFunctionType()) {
17829       // Field declared as a function.
17830       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17831         << FD->getDeclName();
17832       FD->setInvalidDecl();
17833       EnclosingDecl->setInvalidDecl();
17834       continue;
17835     } else if (FDTy->isIncompleteArrayType() &&
17836                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17837       if (Record) {
17838         // Flexible array member.
17839         // Microsoft and g++ is more permissive regarding flexible array.
17840         // It will accept flexible array in union and also
17841         // as the sole element of a struct/class.
17842         unsigned DiagID = 0;
17843         if (!Record->isUnion() && !IsLastField) {
17844           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17845             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17846           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17847           FD->setInvalidDecl();
17848           EnclosingDecl->setInvalidDecl();
17849           continue;
17850         } else if (Record->isUnion())
17851           DiagID = getLangOpts().MicrosoftExt
17852                        ? diag::ext_flexible_array_union_ms
17853                        : getLangOpts().CPlusPlus
17854                              ? diag::ext_flexible_array_union_gnu
17855                              : diag::err_flexible_array_union;
17856         else if (NumNamedMembers < 1)
17857           DiagID = getLangOpts().MicrosoftExt
17858                        ? diag::ext_flexible_array_empty_aggregate_ms
17859                        : getLangOpts().CPlusPlus
17860                              ? diag::ext_flexible_array_empty_aggregate_gnu
17861                              : diag::err_flexible_array_empty_aggregate;
17862 
17863         if (DiagID)
17864           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17865                                           << Record->getTagKind();
17866         // While the layout of types that contain virtual bases is not specified
17867         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17868         // virtual bases after the derived members.  This would make a flexible
17869         // array member declared at the end of an object not adjacent to the end
17870         // of the type.
17871         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17872           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17873               << FD->getDeclName() << Record->getTagKind();
17874         if (!getLangOpts().C99)
17875           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17876             << FD->getDeclName() << Record->getTagKind();
17877 
17878         // If the element type has a non-trivial destructor, we would not
17879         // implicitly destroy the elements, so disallow it for now.
17880         //
17881         // FIXME: GCC allows this. We should probably either implicitly delete
17882         // the destructor of the containing class, or just allow this.
17883         QualType BaseElem = Context.getBaseElementType(FD->getType());
17884         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17885           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17886             << FD->getDeclName() << FD->getType();
17887           FD->setInvalidDecl();
17888           EnclosingDecl->setInvalidDecl();
17889           continue;
17890         }
17891         // Okay, we have a legal flexible array member at the end of the struct.
17892         Record->setHasFlexibleArrayMember(true);
17893       } else {
17894         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17895         // unless they are followed by another ivar. That check is done
17896         // elsewhere, after synthesized ivars are known.
17897       }
17898     } else if (!FDTy->isDependentType() &&
17899                RequireCompleteSizedType(
17900                    FD->getLocation(), FD->getType(),
17901                    diag::err_field_incomplete_or_sizeless)) {
17902       // Incomplete type
17903       FD->setInvalidDecl();
17904       EnclosingDecl->setInvalidDecl();
17905       continue;
17906     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17907       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17908         // A type which contains a flexible array member is considered to be a
17909         // flexible array member.
17910         Record->setHasFlexibleArrayMember(true);
17911         if (!Record->isUnion()) {
17912           // If this is a struct/class and this is not the last element, reject
17913           // it.  Note that GCC supports variable sized arrays in the middle of
17914           // structures.
17915           if (!IsLastField)
17916             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17917               << FD->getDeclName() << FD->getType();
17918           else {
17919             // We support flexible arrays at the end of structs in
17920             // other structs as an extension.
17921             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17922               << FD->getDeclName();
17923           }
17924         }
17925       }
17926       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17927           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17928                                  diag::err_abstract_type_in_decl,
17929                                  AbstractIvarType)) {
17930         // Ivars can not have abstract class types
17931         FD->setInvalidDecl();
17932       }
17933       if (Record && FDTTy->getDecl()->hasObjectMember())
17934         Record->setHasObjectMember(true);
17935       if (Record && FDTTy->getDecl()->hasVolatileMember())
17936         Record->setHasVolatileMember(true);
17937     } else if (FDTy->isObjCObjectType()) {
17938       /// A field cannot be an Objective-c object
17939       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17940         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17941       QualType T = Context.getObjCObjectPointerType(FD->getType());
17942       FD->setType(T);
17943     } else if (Record && Record->isUnion() &&
17944                FD->getType().hasNonTrivialObjCLifetime() &&
17945                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17946                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17947                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17948                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17949       // For backward compatibility, fields of C unions declared in system
17950       // headers that have non-trivial ObjC ownership qualifications are marked
17951       // as unavailable unless the qualifier is explicit and __strong. This can
17952       // break ABI compatibility between programs compiled with ARC and MRR, but
17953       // is a better option than rejecting programs using those unions under
17954       // ARC.
17955       FD->addAttr(UnavailableAttr::CreateImplicit(
17956           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17957           FD->getLocation()));
17958     } else if (getLangOpts().ObjC &&
17959                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17960                !Record->hasObjectMember()) {
17961       if (FD->getType()->isObjCObjectPointerType() ||
17962           FD->getType().isObjCGCStrong())
17963         Record->setHasObjectMember(true);
17964       else if (Context.getAsArrayType(FD->getType())) {
17965         QualType BaseType = Context.getBaseElementType(FD->getType());
17966         if (BaseType->isRecordType() &&
17967             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17968           Record->setHasObjectMember(true);
17969         else if (BaseType->isObjCObjectPointerType() ||
17970                  BaseType.isObjCGCStrong())
17971                Record->setHasObjectMember(true);
17972       }
17973     }
17974 
17975     if (Record && !getLangOpts().CPlusPlus &&
17976         !shouldIgnoreForRecordTriviality(FD)) {
17977       QualType FT = FD->getType();
17978       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17979         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17980         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17981             Record->isUnion())
17982           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17983       }
17984       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17985       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17986         Record->setNonTrivialToPrimitiveCopy(true);
17987         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17988           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17989       }
17990       if (FT.isDestructedType()) {
17991         Record->setNonTrivialToPrimitiveDestroy(true);
17992         Record->setParamDestroyedInCallee(true);
17993         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17994           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17995       }
17996 
17997       if (const auto *RT = FT->getAs<RecordType>()) {
17998         if (RT->getDecl()->getArgPassingRestrictions() ==
17999             RecordDecl::APK_CanNeverPassInRegs)
18000           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18001       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18002         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18003     }
18004 
18005     if (Record && FD->getType().isVolatileQualified())
18006       Record->setHasVolatileMember(true);
18007     // Keep track of the number of named members.
18008     if (FD->getIdentifier())
18009       ++NumNamedMembers;
18010   }
18011 
18012   // Okay, we successfully defined 'Record'.
18013   if (Record) {
18014     bool Completed = false;
18015     if (CXXRecord) {
18016       if (!CXXRecord->isInvalidDecl()) {
18017         // Set access bits correctly on the directly-declared conversions.
18018         for (CXXRecordDecl::conversion_iterator
18019                I = CXXRecord->conversion_begin(),
18020                E = CXXRecord->conversion_end(); I != E; ++I)
18021           I.setAccess((*I)->getAccess());
18022       }
18023 
18024       // Add any implicitly-declared members to this class.
18025       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18026 
18027       if (!CXXRecord->isDependentType()) {
18028         if (!CXXRecord->isInvalidDecl()) {
18029           // If we have virtual base classes, we may end up finding multiple
18030           // final overriders for a given virtual function. Check for this
18031           // problem now.
18032           if (CXXRecord->getNumVBases()) {
18033             CXXFinalOverriderMap FinalOverriders;
18034             CXXRecord->getFinalOverriders(FinalOverriders);
18035 
18036             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18037                                              MEnd = FinalOverriders.end();
18038                  M != MEnd; ++M) {
18039               for (OverridingMethods::iterator SO = M->second.begin(),
18040                                             SOEnd = M->second.end();
18041                    SO != SOEnd; ++SO) {
18042                 assert(SO->second.size() > 0 &&
18043                        "Virtual function without overriding functions?");
18044                 if (SO->second.size() == 1)
18045                   continue;
18046 
18047                 // C++ [class.virtual]p2:
18048                 //   In a derived class, if a virtual member function of a base
18049                 //   class subobject has more than one final overrider the
18050                 //   program is ill-formed.
18051                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18052                   << (const NamedDecl *)M->first << Record;
18053                 Diag(M->first->getLocation(),
18054                      diag::note_overridden_virtual_function);
18055                 for (OverridingMethods::overriding_iterator
18056                           OM = SO->second.begin(),
18057                        OMEnd = SO->second.end();
18058                      OM != OMEnd; ++OM)
18059                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18060                     << (const NamedDecl *)M->first << OM->Method->getParent();
18061 
18062                 Record->setInvalidDecl();
18063               }
18064             }
18065             CXXRecord->completeDefinition(&FinalOverriders);
18066             Completed = true;
18067           }
18068         }
18069       }
18070     }
18071 
18072     if (!Completed)
18073       Record->completeDefinition();
18074 
18075     // Handle attributes before checking the layout.
18076     ProcessDeclAttributeList(S, Record, Attrs);
18077 
18078     // Check to see if a FieldDecl is a pointer to a function.
18079     auto IsFunctionPointer = [&](const Decl *D) {
18080       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18081       if (!FD)
18082         return false;
18083       QualType FieldType = FD->getType().getDesugaredType(Context);
18084       if (isa<PointerType>(FieldType)) {
18085         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18086         return PointeeType.getDesugaredType(Context)->isFunctionType();
18087       }
18088       return false;
18089     };
18090 
18091     // Maybe randomize the record's decls. We automatically randomize a record
18092     // of function pointers, unless it has the "no_randomize_layout" attribute.
18093     if (!getLangOpts().CPlusPlus &&
18094         (Record->hasAttr<RandomizeLayoutAttr>() ||
18095          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18096           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18097         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18098         !Record->isRandomized()) {
18099       SmallVector<Decl *, 32> NewDeclOrdering;
18100       if (randstruct::randomizeStructureLayout(Context, Record,
18101                                                NewDeclOrdering))
18102         Record->reorderDecls(NewDeclOrdering);
18103     }
18104 
18105     // We may have deferred checking for a deleted destructor. Check now.
18106     if (CXXRecord) {
18107       auto *Dtor = CXXRecord->getDestructor();
18108       if (Dtor && Dtor->isImplicit() &&
18109           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18110         CXXRecord->setImplicitDestructorIsDeleted();
18111         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18112       }
18113     }
18114 
18115     if (Record->hasAttrs()) {
18116       CheckAlignasUnderalignment(Record);
18117 
18118       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18119         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18120                                            IA->getRange(), IA->getBestCase(),
18121                                            IA->getInheritanceModel());
18122     }
18123 
18124     // Check if the structure/union declaration is a type that can have zero
18125     // size in C. For C this is a language extension, for C++ it may cause
18126     // compatibility problems.
18127     bool CheckForZeroSize;
18128     if (!getLangOpts().CPlusPlus) {
18129       CheckForZeroSize = true;
18130     } else {
18131       // For C++ filter out types that cannot be referenced in C code.
18132       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18133       CheckForZeroSize =
18134           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18135           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18136           CXXRecord->isCLike();
18137     }
18138     if (CheckForZeroSize) {
18139       bool ZeroSize = true;
18140       bool IsEmpty = true;
18141       unsigned NonBitFields = 0;
18142       for (RecordDecl::field_iterator I = Record->field_begin(),
18143                                       E = Record->field_end();
18144            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18145         IsEmpty = false;
18146         if (I->isUnnamedBitfield()) {
18147           if (!I->isZeroLengthBitField(Context))
18148             ZeroSize = false;
18149         } else {
18150           ++NonBitFields;
18151           QualType FieldType = I->getType();
18152           if (FieldType->isIncompleteType() ||
18153               !Context.getTypeSizeInChars(FieldType).isZero())
18154             ZeroSize = false;
18155         }
18156       }
18157 
18158       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18159       // allowed in C++, but warn if its declaration is inside
18160       // extern "C" block.
18161       if (ZeroSize) {
18162         Diag(RecLoc, getLangOpts().CPlusPlus ?
18163                          diag::warn_zero_size_struct_union_in_extern_c :
18164                          diag::warn_zero_size_struct_union_compat)
18165           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18166       }
18167 
18168       // Structs without named members are extension in C (C99 6.7.2.1p7),
18169       // but are accepted by GCC.
18170       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18171         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18172                                diag::ext_no_named_members_in_struct_union)
18173           << Record->isUnion();
18174       }
18175     }
18176   } else {
18177     ObjCIvarDecl **ClsFields =
18178       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18179     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18180       ID->setEndOfDefinitionLoc(RBrac);
18181       // Add ivar's to class's DeclContext.
18182       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18183         ClsFields[i]->setLexicalDeclContext(ID);
18184         ID->addDecl(ClsFields[i]);
18185       }
18186       // Must enforce the rule that ivars in the base classes may not be
18187       // duplicates.
18188       if (ID->getSuperClass())
18189         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18190     } else if (ObjCImplementationDecl *IMPDecl =
18191                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18192       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18193       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18194         // Ivar declared in @implementation never belongs to the implementation.
18195         // Only it is in implementation's lexical context.
18196         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18197       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18198       IMPDecl->setIvarLBraceLoc(LBrac);
18199       IMPDecl->setIvarRBraceLoc(RBrac);
18200     } else if (ObjCCategoryDecl *CDecl =
18201                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18202       // case of ivars in class extension; all other cases have been
18203       // reported as errors elsewhere.
18204       // FIXME. Class extension does not have a LocEnd field.
18205       // CDecl->setLocEnd(RBrac);
18206       // Add ivar's to class extension's DeclContext.
18207       // Diagnose redeclaration of private ivars.
18208       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18209       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18210         if (IDecl) {
18211           if (const ObjCIvarDecl *ClsIvar =
18212               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18213             Diag(ClsFields[i]->getLocation(),
18214                  diag::err_duplicate_ivar_declaration);
18215             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18216             continue;
18217           }
18218           for (const auto *Ext : IDecl->known_extensions()) {
18219             if (const ObjCIvarDecl *ClsExtIvar
18220                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18221               Diag(ClsFields[i]->getLocation(),
18222                    diag::err_duplicate_ivar_declaration);
18223               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18224               continue;
18225             }
18226           }
18227         }
18228         ClsFields[i]->setLexicalDeclContext(CDecl);
18229         CDecl->addDecl(ClsFields[i]);
18230       }
18231       CDecl->setIvarLBraceLoc(LBrac);
18232       CDecl->setIvarRBraceLoc(RBrac);
18233     }
18234   }
18235 }
18236 
18237 /// Determine whether the given integral value is representable within
18238 /// the given type T.
18239 static bool isRepresentableIntegerValue(ASTContext &Context,
18240                                         llvm::APSInt &Value,
18241                                         QualType T) {
18242   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18243          "Integral type required!");
18244   unsigned BitWidth = Context.getIntWidth(T);
18245 
18246   if (Value.isUnsigned() || Value.isNonNegative()) {
18247     if (T->isSignedIntegerOrEnumerationType())
18248       --BitWidth;
18249     return Value.getActiveBits() <= BitWidth;
18250   }
18251   return Value.getMinSignedBits() <= BitWidth;
18252 }
18253 
18254 // Given an integral type, return the next larger integral type
18255 // (or a NULL type of no such type exists).
18256 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18257   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18258   // enum checking below.
18259   assert((T->isIntegralType(Context) ||
18260          T->isEnumeralType()) && "Integral type required!");
18261   const unsigned NumTypes = 4;
18262   QualType SignedIntegralTypes[NumTypes] = {
18263     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18264   };
18265   QualType UnsignedIntegralTypes[NumTypes] = {
18266     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18267     Context.UnsignedLongLongTy
18268   };
18269 
18270   unsigned BitWidth = Context.getTypeSize(T);
18271   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18272                                                         : UnsignedIntegralTypes;
18273   for (unsigned I = 0; I != NumTypes; ++I)
18274     if (Context.getTypeSize(Types[I]) > BitWidth)
18275       return Types[I];
18276 
18277   return QualType();
18278 }
18279 
18280 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18281                                           EnumConstantDecl *LastEnumConst,
18282                                           SourceLocation IdLoc,
18283                                           IdentifierInfo *Id,
18284                                           Expr *Val) {
18285   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18286   llvm::APSInt EnumVal(IntWidth);
18287   QualType EltTy;
18288 
18289   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18290     Val = nullptr;
18291 
18292   if (Val)
18293     Val = DefaultLvalueConversion(Val).get();
18294 
18295   if (Val) {
18296     if (Enum->isDependentType() || Val->isTypeDependent() ||
18297         Val->containsErrors())
18298       EltTy = Context.DependentTy;
18299     else {
18300       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18301       // underlying type, but do allow it in all other contexts.
18302       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18303         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18304         // constant-expression in the enumerator-definition shall be a converted
18305         // constant expression of the underlying type.
18306         EltTy = Enum->getIntegerType();
18307         ExprResult Converted =
18308           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18309                                            CCEK_Enumerator);
18310         if (Converted.isInvalid())
18311           Val = nullptr;
18312         else
18313           Val = Converted.get();
18314       } else if (!Val->isValueDependent() &&
18315                  !(Val =
18316                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18317                            .get())) {
18318         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18319       } else {
18320         if (Enum->isComplete()) {
18321           EltTy = Enum->getIntegerType();
18322 
18323           // In Obj-C and Microsoft mode, require the enumeration value to be
18324           // representable in the underlying type of the enumeration. In C++11,
18325           // we perform a non-narrowing conversion as part of converted constant
18326           // expression checking.
18327           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18328             if (Context.getTargetInfo()
18329                     .getTriple()
18330                     .isWindowsMSVCEnvironment()) {
18331               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18332             } else {
18333               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18334             }
18335           }
18336 
18337           // Cast to the underlying type.
18338           Val = ImpCastExprToType(Val, EltTy,
18339                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18340                                                          : CK_IntegralCast)
18341                     .get();
18342         } else if (getLangOpts().CPlusPlus) {
18343           // C++11 [dcl.enum]p5:
18344           //   If the underlying type is not fixed, the type of each enumerator
18345           //   is the type of its initializing value:
18346           //     - If an initializer is specified for an enumerator, the
18347           //       initializing value has the same type as the expression.
18348           EltTy = Val->getType();
18349         } else {
18350           // C99 6.7.2.2p2:
18351           //   The expression that defines the value of an enumeration constant
18352           //   shall be an integer constant expression that has a value
18353           //   representable as an int.
18354 
18355           // Complain if the value is not representable in an int.
18356           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18357             Diag(IdLoc, diag::ext_enum_value_not_int)
18358               << toString(EnumVal, 10) << Val->getSourceRange()
18359               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18360           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18361             // Force the type of the expression to 'int'.
18362             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18363           }
18364           EltTy = Val->getType();
18365         }
18366       }
18367     }
18368   }
18369 
18370   if (!Val) {
18371     if (Enum->isDependentType())
18372       EltTy = Context.DependentTy;
18373     else if (!LastEnumConst) {
18374       // C++0x [dcl.enum]p5:
18375       //   If the underlying type is not fixed, the type of each enumerator
18376       //   is the type of its initializing value:
18377       //     - If no initializer is specified for the first enumerator, the
18378       //       initializing value has an unspecified integral type.
18379       //
18380       // GCC uses 'int' for its unspecified integral type, as does
18381       // C99 6.7.2.2p3.
18382       if (Enum->isFixed()) {
18383         EltTy = Enum->getIntegerType();
18384       }
18385       else {
18386         EltTy = Context.IntTy;
18387       }
18388     } else {
18389       // Assign the last value + 1.
18390       EnumVal = LastEnumConst->getInitVal();
18391       ++EnumVal;
18392       EltTy = LastEnumConst->getType();
18393 
18394       // Check for overflow on increment.
18395       if (EnumVal < LastEnumConst->getInitVal()) {
18396         // C++0x [dcl.enum]p5:
18397         //   If the underlying type is not fixed, the type of each enumerator
18398         //   is the type of its initializing value:
18399         //
18400         //     - Otherwise the type of the initializing value is the same as
18401         //       the type of the initializing value of the preceding enumerator
18402         //       unless the incremented value is not representable in that type,
18403         //       in which case the type is an unspecified integral type
18404         //       sufficient to contain the incremented value. If no such type
18405         //       exists, the program is ill-formed.
18406         QualType T = getNextLargerIntegralType(Context, EltTy);
18407         if (T.isNull() || Enum->isFixed()) {
18408           // There is no integral type larger enough to represent this
18409           // value. Complain, then allow the value to wrap around.
18410           EnumVal = LastEnumConst->getInitVal();
18411           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18412           ++EnumVal;
18413           if (Enum->isFixed())
18414             // When the underlying type is fixed, this is ill-formed.
18415             Diag(IdLoc, diag::err_enumerator_wrapped)
18416               << toString(EnumVal, 10)
18417               << EltTy;
18418           else
18419             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18420               << toString(EnumVal, 10);
18421         } else {
18422           EltTy = T;
18423         }
18424 
18425         // Retrieve the last enumerator's value, extent that type to the
18426         // type that is supposed to be large enough to represent the incremented
18427         // value, then increment.
18428         EnumVal = LastEnumConst->getInitVal();
18429         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18430         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18431         ++EnumVal;
18432 
18433         // If we're not in C++, diagnose the overflow of enumerator values,
18434         // which in C99 means that the enumerator value is not representable in
18435         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18436         // permits enumerator values that are representable in some larger
18437         // integral type.
18438         if (!getLangOpts().CPlusPlus && !T.isNull())
18439           Diag(IdLoc, diag::warn_enum_value_overflow);
18440       } else if (!getLangOpts().CPlusPlus &&
18441                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18442         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18443         Diag(IdLoc, diag::ext_enum_value_not_int)
18444           << toString(EnumVal, 10) << 1;
18445       }
18446     }
18447   }
18448 
18449   if (!EltTy->isDependentType()) {
18450     // Make the enumerator value match the signedness and size of the
18451     // enumerator's type.
18452     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18453     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18454   }
18455 
18456   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18457                                   Val, EnumVal);
18458 }
18459 
18460 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18461                                                 SourceLocation IILoc) {
18462   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18463       !getLangOpts().CPlusPlus)
18464     return SkipBodyInfo();
18465 
18466   // We have an anonymous enum definition. Look up the first enumerator to
18467   // determine if we should merge the definition with an existing one and
18468   // skip the body.
18469   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18470                                          forRedeclarationInCurContext());
18471   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18472   if (!PrevECD)
18473     return SkipBodyInfo();
18474 
18475   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18476   NamedDecl *Hidden;
18477   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18478     SkipBodyInfo Skip;
18479     Skip.Previous = Hidden;
18480     return Skip;
18481   }
18482 
18483   return SkipBodyInfo();
18484 }
18485 
18486 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18487                               SourceLocation IdLoc, IdentifierInfo *Id,
18488                               const ParsedAttributesView &Attrs,
18489                               SourceLocation EqualLoc, Expr *Val) {
18490   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18491   EnumConstantDecl *LastEnumConst =
18492     cast_or_null<EnumConstantDecl>(lastEnumConst);
18493 
18494   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18495   // we find one that is.
18496   S = getNonFieldDeclScope(S);
18497 
18498   // Verify that there isn't already something declared with this name in this
18499   // scope.
18500   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18501   LookupName(R, S);
18502   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18503 
18504   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18505     // Maybe we will complain about the shadowed template parameter.
18506     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18507     // Just pretend that we didn't see the previous declaration.
18508     PrevDecl = nullptr;
18509   }
18510 
18511   // C++ [class.mem]p15:
18512   // If T is the name of a class, then each of the following shall have a name
18513   // different from T:
18514   // - every enumerator of every member of class T that is an unscoped
18515   // enumerated type
18516   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18517     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18518                             DeclarationNameInfo(Id, IdLoc));
18519 
18520   EnumConstantDecl *New =
18521     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18522   if (!New)
18523     return nullptr;
18524 
18525   if (PrevDecl) {
18526     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18527       // Check for other kinds of shadowing not already handled.
18528       CheckShadow(New, PrevDecl, R);
18529     }
18530 
18531     // When in C++, we may get a TagDecl with the same name; in this case the
18532     // enum constant will 'hide' the tag.
18533     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18534            "Received TagDecl when not in C++!");
18535     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18536       if (isa<EnumConstantDecl>(PrevDecl))
18537         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18538       else
18539         Diag(IdLoc, diag::err_redefinition) << Id;
18540       notePreviousDefinition(PrevDecl, IdLoc);
18541       return nullptr;
18542     }
18543   }
18544 
18545   // Process attributes.
18546   ProcessDeclAttributeList(S, New, Attrs);
18547   AddPragmaAttributes(S, New);
18548 
18549   // Register this decl in the current scope stack.
18550   New->setAccess(TheEnumDecl->getAccess());
18551   PushOnScopeChains(New, S);
18552 
18553   ActOnDocumentableDecl(New);
18554 
18555   return New;
18556 }
18557 
18558 // Returns true when the enum initial expression does not trigger the
18559 // duplicate enum warning.  A few common cases are exempted as follows:
18560 // Element2 = Element1
18561 // Element2 = Element1 + 1
18562 // Element2 = Element1 - 1
18563 // Where Element2 and Element1 are from the same enum.
18564 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18565   Expr *InitExpr = ECD->getInitExpr();
18566   if (!InitExpr)
18567     return true;
18568   InitExpr = InitExpr->IgnoreImpCasts();
18569 
18570   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18571     if (!BO->isAdditiveOp())
18572       return true;
18573     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18574     if (!IL)
18575       return true;
18576     if (IL->getValue() != 1)
18577       return true;
18578 
18579     InitExpr = BO->getLHS();
18580   }
18581 
18582   // This checks if the elements are from the same enum.
18583   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18584   if (!DRE)
18585     return true;
18586 
18587   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18588   if (!EnumConstant)
18589     return true;
18590 
18591   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18592       Enum)
18593     return true;
18594 
18595   return false;
18596 }
18597 
18598 // Emits a warning when an element is implicitly set a value that
18599 // a previous element has already been set to.
18600 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18601                                         EnumDecl *Enum, QualType EnumType) {
18602   // Avoid anonymous enums
18603   if (!Enum->getIdentifier())
18604     return;
18605 
18606   // Only check for small enums.
18607   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18608     return;
18609 
18610   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18611     return;
18612 
18613   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18614   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18615 
18616   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18617 
18618   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18619   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18620 
18621   // Use int64_t as a key to avoid needing special handling for map keys.
18622   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18623     llvm::APSInt Val = D->getInitVal();
18624     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18625   };
18626 
18627   DuplicatesVector DupVector;
18628   ValueToVectorMap EnumMap;
18629 
18630   // Populate the EnumMap with all values represented by enum constants without
18631   // an initializer.
18632   for (auto *Element : Elements) {
18633     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18634 
18635     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18636     // this constant.  Skip this enum since it may be ill-formed.
18637     if (!ECD) {
18638       return;
18639     }
18640 
18641     // Constants with initalizers are handled in the next loop.
18642     if (ECD->getInitExpr())
18643       continue;
18644 
18645     // Duplicate values are handled in the next loop.
18646     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18647   }
18648 
18649   if (EnumMap.size() == 0)
18650     return;
18651 
18652   // Create vectors for any values that has duplicates.
18653   for (auto *Element : Elements) {
18654     // The last loop returned if any constant was null.
18655     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18656     if (!ValidDuplicateEnum(ECD, Enum))
18657       continue;
18658 
18659     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18660     if (Iter == EnumMap.end())
18661       continue;
18662 
18663     DeclOrVector& Entry = Iter->second;
18664     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18665       // Ensure constants are different.
18666       if (D == ECD)
18667         continue;
18668 
18669       // Create new vector and push values onto it.
18670       auto Vec = std::make_unique<ECDVector>();
18671       Vec->push_back(D);
18672       Vec->push_back(ECD);
18673 
18674       // Update entry to point to the duplicates vector.
18675       Entry = Vec.get();
18676 
18677       // Store the vector somewhere we can consult later for quick emission of
18678       // diagnostics.
18679       DupVector.emplace_back(std::move(Vec));
18680       continue;
18681     }
18682 
18683     ECDVector *Vec = Entry.get<ECDVector*>();
18684     // Make sure constants are not added more than once.
18685     if (*Vec->begin() == ECD)
18686       continue;
18687 
18688     Vec->push_back(ECD);
18689   }
18690 
18691   // Emit diagnostics.
18692   for (const auto &Vec : DupVector) {
18693     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18694 
18695     // Emit warning for one enum constant.
18696     auto *FirstECD = Vec->front();
18697     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18698       << FirstECD << toString(FirstECD->getInitVal(), 10)
18699       << FirstECD->getSourceRange();
18700 
18701     // Emit one note for each of the remaining enum constants with
18702     // the same value.
18703     for (auto *ECD : llvm::drop_begin(*Vec))
18704       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18705         << ECD << toString(ECD->getInitVal(), 10)
18706         << ECD->getSourceRange();
18707   }
18708 }
18709 
18710 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18711                              bool AllowMask) const {
18712   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18713   assert(ED->isCompleteDefinition() && "expected enum definition");
18714 
18715   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18716   llvm::APInt &FlagBits = R.first->second;
18717 
18718   if (R.second) {
18719     for (auto *E : ED->enumerators()) {
18720       const auto &EVal = E->getInitVal();
18721       // Only single-bit enumerators introduce new flag values.
18722       if (EVal.isPowerOf2())
18723         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18724     }
18725   }
18726 
18727   // A value is in a flag enum if either its bits are a subset of the enum's
18728   // flag bits (the first condition) or we are allowing masks and the same is
18729   // true of its complement (the second condition). When masks are allowed, we
18730   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18731   //
18732   // While it's true that any value could be used as a mask, the assumption is
18733   // that a mask will have all of the insignificant bits set. Anything else is
18734   // likely a logic error.
18735   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18736   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18737 }
18738 
18739 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18740                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18741                          const ParsedAttributesView &Attrs) {
18742   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18743   QualType EnumType = Context.getTypeDeclType(Enum);
18744 
18745   ProcessDeclAttributeList(S, Enum, Attrs);
18746 
18747   if (Enum->isDependentType()) {
18748     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18749       EnumConstantDecl *ECD =
18750         cast_or_null<EnumConstantDecl>(Elements[i]);
18751       if (!ECD) continue;
18752 
18753       ECD->setType(EnumType);
18754     }
18755 
18756     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18757     return;
18758   }
18759 
18760   // TODO: If the result value doesn't fit in an int, it must be a long or long
18761   // long value.  ISO C does not support this, but GCC does as an extension,
18762   // emit a warning.
18763   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18764   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18765   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18766 
18767   // Verify that all the values are okay, compute the size of the values, and
18768   // reverse the list.
18769   unsigned NumNegativeBits = 0;
18770   unsigned NumPositiveBits = 0;
18771 
18772   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18773     EnumConstantDecl *ECD =
18774       cast_or_null<EnumConstantDecl>(Elements[i]);
18775     if (!ECD) continue;  // Already issued a diagnostic.
18776 
18777     const llvm::APSInt &InitVal = ECD->getInitVal();
18778 
18779     // Keep track of the size of positive and negative values.
18780     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18781       NumPositiveBits = std::max(NumPositiveBits,
18782                                  (unsigned)InitVal.getActiveBits());
18783     else
18784       NumNegativeBits = std::max(NumNegativeBits,
18785                                  (unsigned)InitVal.getMinSignedBits());
18786   }
18787 
18788   // Figure out the type that should be used for this enum.
18789   QualType BestType;
18790   unsigned BestWidth;
18791 
18792   // C++0x N3000 [conv.prom]p3:
18793   //   An rvalue of an unscoped enumeration type whose underlying
18794   //   type is not fixed can be converted to an rvalue of the first
18795   //   of the following types that can represent all the values of
18796   //   the enumeration: int, unsigned int, long int, unsigned long
18797   //   int, long long int, or unsigned long long int.
18798   // C99 6.4.4.3p2:
18799   //   An identifier declared as an enumeration constant has type int.
18800   // The C99 rule is modified by a gcc extension
18801   QualType BestPromotionType;
18802 
18803   bool Packed = Enum->hasAttr<PackedAttr>();
18804   // -fshort-enums is the equivalent to specifying the packed attribute on all
18805   // enum definitions.
18806   if (LangOpts.ShortEnums)
18807     Packed = true;
18808 
18809   // If the enum already has a type because it is fixed or dictated by the
18810   // target, promote that type instead of analyzing the enumerators.
18811   if (Enum->isComplete()) {
18812     BestType = Enum->getIntegerType();
18813     if (BestType->isPromotableIntegerType())
18814       BestPromotionType = Context.getPromotedIntegerType(BestType);
18815     else
18816       BestPromotionType = BestType;
18817 
18818     BestWidth = Context.getIntWidth(BestType);
18819   }
18820   else if (NumNegativeBits) {
18821     // If there is a negative value, figure out the smallest integer type (of
18822     // int/long/longlong) that fits.
18823     // If it's packed, check also if it fits a char or a short.
18824     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18825       BestType = Context.SignedCharTy;
18826       BestWidth = CharWidth;
18827     } else if (Packed && NumNegativeBits <= ShortWidth &&
18828                NumPositiveBits < ShortWidth) {
18829       BestType = Context.ShortTy;
18830       BestWidth = ShortWidth;
18831     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18832       BestType = Context.IntTy;
18833       BestWidth = IntWidth;
18834     } else {
18835       BestWidth = Context.getTargetInfo().getLongWidth();
18836 
18837       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18838         BestType = Context.LongTy;
18839       } else {
18840         BestWidth = Context.getTargetInfo().getLongLongWidth();
18841 
18842         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18843           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18844         BestType = Context.LongLongTy;
18845       }
18846     }
18847     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18848   } else {
18849     // If there is no negative value, figure out the smallest type that fits
18850     // all of the enumerator values.
18851     // If it's packed, check also if it fits a char or a short.
18852     if (Packed && NumPositiveBits <= CharWidth) {
18853       BestType = Context.UnsignedCharTy;
18854       BestPromotionType = Context.IntTy;
18855       BestWidth = CharWidth;
18856     } else if (Packed && NumPositiveBits <= ShortWidth) {
18857       BestType = Context.UnsignedShortTy;
18858       BestPromotionType = Context.IntTy;
18859       BestWidth = ShortWidth;
18860     } else if (NumPositiveBits <= IntWidth) {
18861       BestType = Context.UnsignedIntTy;
18862       BestWidth = IntWidth;
18863       BestPromotionType
18864         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18865                            ? Context.UnsignedIntTy : Context.IntTy;
18866     } else if (NumPositiveBits <=
18867                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18868       BestType = Context.UnsignedLongTy;
18869       BestPromotionType
18870         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18871                            ? Context.UnsignedLongTy : Context.LongTy;
18872     } else {
18873       BestWidth = Context.getTargetInfo().getLongLongWidth();
18874       assert(NumPositiveBits <= BestWidth &&
18875              "How could an initializer get larger than ULL?");
18876       BestType = Context.UnsignedLongLongTy;
18877       BestPromotionType
18878         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18879                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18880     }
18881   }
18882 
18883   // Loop over all of the enumerator constants, changing their types to match
18884   // the type of the enum if needed.
18885   for (auto *D : Elements) {
18886     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18887     if (!ECD) continue;  // Already issued a diagnostic.
18888 
18889     // Standard C says the enumerators have int type, but we allow, as an
18890     // extension, the enumerators to be larger than int size.  If each
18891     // enumerator value fits in an int, type it as an int, otherwise type it the
18892     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18893     // that X has type 'int', not 'unsigned'.
18894 
18895     // Determine whether the value fits into an int.
18896     llvm::APSInt InitVal = ECD->getInitVal();
18897 
18898     // If it fits into an integer type, force it.  Otherwise force it to match
18899     // the enum decl type.
18900     QualType NewTy;
18901     unsigned NewWidth;
18902     bool NewSign;
18903     if (!getLangOpts().CPlusPlus &&
18904         !Enum->isFixed() &&
18905         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18906       NewTy = Context.IntTy;
18907       NewWidth = IntWidth;
18908       NewSign = true;
18909     } else if (ECD->getType() == BestType) {
18910       // Already the right type!
18911       if (getLangOpts().CPlusPlus)
18912         // C++ [dcl.enum]p4: Following the closing brace of an
18913         // enum-specifier, each enumerator has the type of its
18914         // enumeration.
18915         ECD->setType(EnumType);
18916       continue;
18917     } else {
18918       NewTy = BestType;
18919       NewWidth = BestWidth;
18920       NewSign = BestType->isSignedIntegerOrEnumerationType();
18921     }
18922 
18923     // Adjust the APSInt value.
18924     InitVal = InitVal.extOrTrunc(NewWidth);
18925     InitVal.setIsSigned(NewSign);
18926     ECD->setInitVal(InitVal);
18927 
18928     // Adjust the Expr initializer and type.
18929     if (ECD->getInitExpr() &&
18930         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18931       ECD->setInitExpr(ImplicitCastExpr::Create(
18932           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18933           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18934     if (getLangOpts().CPlusPlus)
18935       // C++ [dcl.enum]p4: Following the closing brace of an
18936       // enum-specifier, each enumerator has the type of its
18937       // enumeration.
18938       ECD->setType(EnumType);
18939     else
18940       ECD->setType(NewTy);
18941   }
18942 
18943   Enum->completeDefinition(BestType, BestPromotionType,
18944                            NumPositiveBits, NumNegativeBits);
18945 
18946   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18947 
18948   if (Enum->isClosedFlag()) {
18949     for (Decl *D : Elements) {
18950       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18951       if (!ECD) continue;  // Already issued a diagnostic.
18952 
18953       llvm::APSInt InitVal = ECD->getInitVal();
18954       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18955           !IsValueInFlagEnum(Enum, InitVal, true))
18956         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18957           << ECD << Enum;
18958     }
18959   }
18960 
18961   // Now that the enum type is defined, ensure it's not been underaligned.
18962   if (Enum->hasAttrs())
18963     CheckAlignasUnderalignment(Enum);
18964 }
18965 
18966 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18967                                   SourceLocation StartLoc,
18968                                   SourceLocation EndLoc) {
18969   StringLiteral *AsmString = cast<StringLiteral>(expr);
18970 
18971   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18972                                                    AsmString, StartLoc,
18973                                                    EndLoc);
18974   CurContext->addDecl(New);
18975   return New;
18976 }
18977 
18978 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18979                                       IdentifierInfo* AliasName,
18980                                       SourceLocation PragmaLoc,
18981                                       SourceLocation NameLoc,
18982                                       SourceLocation AliasNameLoc) {
18983   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18984                                          LookupOrdinaryName);
18985   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18986                            AttributeCommonInfo::AS_Pragma);
18987   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18988       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18989 
18990   // If a declaration that:
18991   // 1) declares a function or a variable
18992   // 2) has external linkage
18993   // already exists, add a label attribute to it.
18994   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18995     if (isDeclExternC(PrevDecl))
18996       PrevDecl->addAttr(Attr);
18997     else
18998       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18999           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19000   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19001   } else
19002     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19003 }
19004 
19005 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19006                              SourceLocation PragmaLoc,
19007                              SourceLocation NameLoc) {
19008   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19009 
19010   if (PrevDecl) {
19011     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19012   } else {
19013     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19014   }
19015 }
19016 
19017 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19018                                 IdentifierInfo* AliasName,
19019                                 SourceLocation PragmaLoc,
19020                                 SourceLocation NameLoc,
19021                                 SourceLocation AliasNameLoc) {
19022   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19023                                     LookupOrdinaryName);
19024   WeakInfo W = WeakInfo(Name, NameLoc);
19025 
19026   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19027     if (!PrevDecl->hasAttr<AliasAttr>())
19028       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19029         DeclApplyPragmaWeak(TUScope, ND, W);
19030   } else {
19031     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19032   }
19033 }
19034 
19035 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19036   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19037 }
19038 
19039 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19040                                                      bool Final) {
19041   assert(FD && "Expected non-null FunctionDecl");
19042 
19043   // SYCL functions can be template, so we check if they have appropriate
19044   // attribute prior to checking if it is a template.
19045   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19046     return FunctionEmissionStatus::Emitted;
19047 
19048   // Templates are emitted when they're instantiated.
19049   if (FD->isDependentContext())
19050     return FunctionEmissionStatus::TemplateDiscarded;
19051 
19052   // Check whether this function is an externally visible definition.
19053   auto IsEmittedForExternalSymbol = [this, FD]() {
19054     // We have to check the GVA linkage of the function's *definition* -- if we
19055     // only have a declaration, we don't know whether or not the function will
19056     // be emitted, because (say) the definition could include "inline".
19057     FunctionDecl *Def = FD->getDefinition();
19058 
19059     return Def && !isDiscardableGVALinkage(
19060                       getASTContext().GetGVALinkageForFunction(Def));
19061   };
19062 
19063   if (LangOpts.OpenMPIsDevice) {
19064     // In OpenMP device mode we will not emit host only functions, or functions
19065     // we don't need due to their linkage.
19066     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19067         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19068     // DevTy may be changed later by
19069     //  #pragma omp declare target to(*) device_type(*).
19070     // Therefore DevTy having no value does not imply host. The emission status
19071     // will be checked again at the end of compilation unit with Final = true.
19072     if (DevTy.hasValue())
19073       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19074         return FunctionEmissionStatus::OMPDiscarded;
19075     // If we have an explicit value for the device type, or we are in a target
19076     // declare context, we need to emit all extern and used symbols.
19077     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
19078       if (IsEmittedForExternalSymbol())
19079         return FunctionEmissionStatus::Emitted;
19080     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19081     // we'll omit it.
19082     if (Final)
19083       return FunctionEmissionStatus::OMPDiscarded;
19084   } else if (LangOpts.OpenMP > 45) {
19085     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19086     // function. In 5.0, no_host was introduced which might cause a function to
19087     // be ommitted.
19088     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19089         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19090     if (DevTy.hasValue())
19091       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19092         return FunctionEmissionStatus::OMPDiscarded;
19093   }
19094 
19095   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19096     return FunctionEmissionStatus::Emitted;
19097 
19098   if (LangOpts.CUDA) {
19099     // When compiling for device, host functions are never emitted.  Similarly,
19100     // when compiling for host, device and global functions are never emitted.
19101     // (Technically, we do emit a host-side stub for global functions, but this
19102     // doesn't count for our purposes here.)
19103     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19104     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19105       return FunctionEmissionStatus::CUDADiscarded;
19106     if (!LangOpts.CUDAIsDevice &&
19107         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19108       return FunctionEmissionStatus::CUDADiscarded;
19109 
19110     if (IsEmittedForExternalSymbol())
19111       return FunctionEmissionStatus::Emitted;
19112   }
19113 
19114   // Otherwise, the function is known-emitted if it's in our set of
19115   // known-emitted functions.
19116   return FunctionEmissionStatus::Unknown;
19117 }
19118 
19119 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19120   // Host-side references to a __global__ function refer to the stub, so the
19121   // function itself is never emitted and therefore should not be marked.
19122   // If we have host fn calls kernel fn calls host+device, the HD function
19123   // does not get instantiated on the host. We model this by omitting at the
19124   // call to the kernel from the callgraph. This ensures that, when compiling
19125   // for host, only HD functions actually called from the host get marked as
19126   // known-emitted.
19127   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19128          IdentifyCUDATarget(Callee) == CFT_Global;
19129 }
19130