1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw___ibm128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   UsingShadowDecl *FoundUsingShadow = nullptr;
376   switch (Result.getResultKind()) {
377   case LookupResult::NotFound:
378   case LookupResult::NotFoundInCurrentInstantiation:
379     if (CorrectedII) {
380       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381                                AllowDeducedTemplate);
382       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383                                               S, SS, CCC, CTK_ErrorRecovery);
384       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385       TemplateTy Template;
386       bool MemberOfUnknownSpecialization;
387       UnqualifiedId TemplateName;
388       TemplateName.setIdentifier(NewII, NameLoc);
389       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390       CXXScopeSpec NewSS, *NewSSPtr = SS;
391       if (SS && NNS) {
392         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393         NewSSPtr = &NewSS;
394       }
395       if (Correction && (NNS || NewII != &II) &&
396           // Ignore a correction to a template type as the to-be-corrected
397           // identifier is not a template (typo correction for template names
398           // is handled elsewhere).
399           !(getLangOpts().CPlusPlus && NewSSPtr &&
400             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401                            Template, MemberOfUnknownSpecialization))) {
402         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403                                     isClassName, HasTrailingDot, ObjectTypePtr,
404                                     IsCtorOrDtorName,
405                                     WantNontrivialTypeSourceInfo,
406                                     IsClassTemplateDeductionContext);
407         if (Ty) {
408           diagnoseTypo(Correction,
409                        PDiag(diag::err_unknown_type_or_class_name_suggest)
410                          << Result.getLookupName() << isClassName);
411           if (SS && NNS)
412             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413           *CorrectedII = NewII;
414           return Ty;
415         }
416       }
417     }
418     // If typo correction failed or was not performed, fall through
419     LLVM_FALLTHROUGH;
420   case LookupResult::FoundOverloaded:
421   case LookupResult::FoundUnresolvedValue:
422     Result.suppressDiagnostics();
423     return nullptr;
424 
425   case LookupResult::Ambiguous:
426     // Recover from type-hiding ambiguities by hiding the type.  We'll
427     // do the lookup again when looking for an object, and we can
428     // diagnose the error then.  If we don't do this, then the error
429     // about hiding the type will be immediately followed by an error
430     // that only makes sense if the identifier was treated like a type.
431     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432       Result.suppressDiagnostics();
433       return nullptr;
434     }
435 
436     // Look to see if we have a type anywhere in the list of results.
437     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438          Res != ResEnd; ++Res) {
439       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441               RealRes) ||
442           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
443         if (!IIDecl ||
444             // Make the selection of the recovery decl deterministic.
445             RealRes->getLocation() < IIDecl->getLocation()) {
446           IIDecl = RealRes;
447           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448         }
449       }
450     }
451 
452     if (!IIDecl) {
453       // None of the entities we found is a type, so there is no way
454       // to even assume that the result is a type. In this case, don't
455       // complain about the ambiguity. The parser will either try to
456       // perform this lookup again (e.g., as an object name), which
457       // will produce the ambiguity, or will complain that it expected
458       // a type name.
459       Result.suppressDiagnostics();
460       return nullptr;
461     }
462 
463     // We found a type within the ambiguous lookup; diagnose the
464     // ambiguity and then return that type. This might be the right
465     // answer, or it might not be, but it suppresses any attempt to
466     // perform the name lookup again.
467     break;
468 
469   case LookupResult::Found:
470     IIDecl = Result.getFoundDecl();
471     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472     break;
473   }
474 
475   assert(IIDecl && "Didn't find decl");
476 
477   QualType T;
478   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479     // C++ [class.qual]p2: A lookup that would find the injected-class-name
480     // instead names the constructors of the class, except when naming a class.
481     // This is ill-formed when we're not actually forming a ctor or dtor name.
482     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485         FoundRD->isInjectedClassName() &&
486         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
487       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488           << &II << /*Type*/1;
489 
490     DiagnoseUseOfDecl(IIDecl, NameLoc);
491 
492     T = Context.getTypeDeclType(TD);
493     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496     if (!HasTrailingDot)
497       T = Context.getObjCInterfaceType(IDecl);
498     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500     (void)DiagnoseUseOfDecl(UD, NameLoc);
501     // Recover with 'int'
502     T = Context.IntTy;
503     FoundUsingShadow = nullptr;
504   } else if (AllowDeducedTemplate) {
505     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506       // FIXME: TemplateName should include FoundUsingShadow sugar.
507       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
508                                                        QualType(), false);
509       // Don't wrap in a further UsingType.
510       FoundUsingShadow = nullptr;
511     }
512   }
513 
514   if (T.isNull()) {
515     // If it's not plausibly a type, suppress diagnostics.
516     Result.suppressDiagnostics();
517     return nullptr;
518   }
519 
520   if (FoundUsingShadow)
521     T = Context.getUsingType(FoundUsingShadow, T);
522 
523   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524   // constructor or destructor name (in such a case, the scope specifier
525   // will be attached to the enclosing Expr or Decl node).
526   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
527       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528     if (WantNontrivialTypeSourceInfo) {
529       // Construct a type with type-source information.
530       TypeLocBuilder Builder;
531       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532 
533       T = getElaboratedType(ETK_None, *SS, T);
534       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
535       ElabTL.setElaboratedKeywordLoc(SourceLocation());
536       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538     } else {
539       T = getElaboratedType(ETK_None, *SS, T);
540     }
541   }
542 
543   return ParsedType::make(T);
544 }
545 
546 // Builds a fake NNS for the given decl context.
547 static NestedNameSpecifier *
548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
549   for (;; DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     auto *ND = dyn_cast<NamespaceDecl>(DC);
552     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
553       return NestedNameSpecifier::Create(Context, nullptr, ND);
554     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556                                          RD->getTypeForDecl());
557     else if (isa<TranslationUnitDecl>(DC))
558       return NestedNameSpecifier::GlobalSpecifier(Context);
559   }
560   llvm_unreachable("something isn't in TU scope?");
561 }
562 
563 /// Find the parent class with dependent bases of the innermost enclosing method
564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565 /// up allowing unqualified dependent type names at class-level, which MSVC
566 /// correctly rejects.
567 static const CXXRecordDecl *
568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
569   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
570     DC = DC->getPrimaryContext();
571     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572       if (MD->getParent()->hasAnyDependentBases())
573         return MD->getParent();
574   }
575   return nullptr;
576 }
577 
578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
579                                           SourceLocation NameLoc,
580                                           bool IsTemplateTypeArg) {
581   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582 
583   NestedNameSpecifier *NNS = nullptr;
584   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
585     // If we weren't able to parse a default template argument, delay lookup
586     // until instantiation time by making a non-dependent DependentTypeName. We
587     // pretend we saw a NestedNameSpecifier referring to the current scope, and
588     // lookup is retried.
589     // FIXME: This hurts our diagnostic quality, since we get errors like "no
590     // type named 'Foo' in 'current_namespace'" when the user didn't write any
591     // name specifiers.
592     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594   } else if (const CXXRecordDecl *RD =
595                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
596     // Build a DependentNameType that will perform lookup into RD at
597     // instantiation time.
598     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599                                       RD->getTypeForDecl());
600 
601     // Diagnose that this identifier was undeclared, and retry the lookup during
602     // template instantiation.
603     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604                                                                       << RD;
605   } else {
606     // This is not a situation that we should recover from.
607     return ParsedType();
608   }
609 
610   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611 
612   // Build type location information.  We synthesized the qualifier, so we have
613   // to build a fake NestedNameSpecifierLoc.
614   NestedNameSpecifierLocBuilder NNSLocBuilder;
615   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617 
618   TypeLocBuilder Builder;
619   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620   DepTL.setNameLoc(NameLoc);
621   DepTL.setElaboratedKeywordLoc(SourceLocation());
622   DepTL.setQualifierLoc(QualifierLoc);
623   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624 }
625 
626 /// isTagName() - This method is called *for error recovery purposes only*
627 /// to determine if the specified name is a valid tag name ("struct foo").  If
628 /// so, this returns the TST for the tag corresponding to it (TST_enum,
629 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
630 /// cases in C where the user forgot to specify the tag.
631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
632   // Do a tag name lookup in this scope.
633   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634   LookupName(R, S, false);
635   R.suppressDiagnostics();
636   if (R.getResultKind() == LookupResult::Found)
637     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638       switch (TD->getTagKind()) {
639       case TTK_Struct: return DeclSpec::TST_struct;
640       case TTK_Interface: return DeclSpec::TST_interface;
641       case TTK_Union:  return DeclSpec::TST_union;
642       case TTK_Class:  return DeclSpec::TST_class;
643       case TTK_Enum:   return DeclSpec::TST_enum;
644       }
645     }
646 
647   return DeclSpec::TST_unspecified;
648 }
649 
650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
652 /// then downgrade the missing typename error to a warning.
653 /// This is needed for MSVC compatibility; Example:
654 /// @code
655 /// template<class T> class A {
656 /// public:
657 ///   typedef int TYPE;
658 /// };
659 /// template<class T> class B : public A<T> {
660 /// public:
661 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
662 /// };
663 /// @endcode
664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
665   if (CurContext->isRecord()) {
666     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
667       return true;
668 
669     const Type *Ty = SS->getScopeRep()->getAsType();
670 
671     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672     for (const auto &Base : RD->bases())
673       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674         return true;
675     return S->isFunctionPrototypeScope();
676   }
677   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678 }
679 
680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
681                                    SourceLocation IILoc,
682                                    Scope *S,
683                                    CXXScopeSpec *SS,
684                                    ParsedType &SuggestedType,
685                                    bool IsTemplateName) {
686   // Don't report typename errors for editor placeholders.
687   if (II->isEditorPlaceholder())
688     return;
689   // We don't have anything to suggest (yet).
690   SuggestedType = nullptr;
691 
692   // There may have been a typo in the name of the type. Look up typo
693   // results, in case we have something that we can suggest.
694   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695                            /*AllowTemplates=*/IsTemplateName,
696                            /*AllowNonTemplates=*/!IsTemplateName);
697   if (TypoCorrection Corrected =
698           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699                       CCC, CTK_ErrorRecovery)) {
700     // FIXME: Support error recovery for the template-name case.
701     bool CanRecover = !IsTemplateName;
702     if (Corrected.isKeyword()) {
703       // We corrected to a keyword.
704       diagnoseTypo(Corrected,
705                    PDiag(IsTemplateName ? diag::err_no_template_suggest
706                                         : diag::err_unknown_typename_suggest)
707                        << II);
708       II = Corrected.getCorrectionAsIdentifierInfo();
709     } else {
710       // We found a similarly-named type or interface; suggest that.
711       if (!SS || !SS->isSet()) {
712         diagnoseTypo(Corrected,
713                      PDiag(IsTemplateName ? diag::err_no_template_suggest
714                                           : diag::err_unknown_typename_suggest)
715                          << II, CanRecover);
716       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719                                 II->getName().equals(CorrectedStr);
720         diagnoseTypo(Corrected,
721                      PDiag(IsTemplateName
722                                ? diag::err_no_member_template_suggest
723                                : diag::err_unknown_nested_typename_suggest)
724                          << II << DC << DroppedSpecifier << SS->getRange(),
725                      CanRecover);
726       } else {
727         llvm_unreachable("could not have corrected a typo here");
728       }
729 
730       if (!CanRecover)
731         return;
732 
733       CXXScopeSpec tmpSS;
734       if (Corrected.getCorrectionSpecifier())
735         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736                           SourceRange(IILoc));
737       // FIXME: Support class template argument deduction here.
738       SuggestedType =
739           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741                       /*IsCtorOrDtorName=*/false,
742                       /*WantNontrivialTypeSourceInfo=*/true);
743     }
744     return;
745   }
746 
747   if (getLangOpts().CPlusPlus && !IsTemplateName) {
748     // See if II is a class template that the user forgot to pass arguments to.
749     UnqualifiedId Name;
750     Name.setIdentifier(II, IILoc);
751     CXXScopeSpec EmptySS;
752     TemplateTy TemplateResult;
753     bool MemberOfUnknownSpecialization;
754     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755                        Name, nullptr, true, TemplateResult,
756                        MemberOfUnknownSpecialization) == TNK_Type_template) {
757       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758       return;
759     }
760   }
761 
762   // FIXME: Should we move the logic that tries to recover from a missing tag
763   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764 
765   if (!SS || (!SS->isSet() && !SS->isInvalid()))
766     Diag(IILoc, IsTemplateName ? diag::err_no_template
767                                : diag::err_unknown_typename)
768         << II;
769   else if (DeclContext *DC = computeDeclContext(*SS, false))
770     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771                                : diag::err_typename_nested_not_found)
772         << II << DC << SS->getRange();
773   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774     SuggestedType =
775         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776   } else if (isDependentScopeSpecifier(*SS)) {
777     unsigned DiagID = diag::err_typename_missing;
778     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779       DiagID = diag::ext_typename_missing;
780 
781     Diag(SS->getRange().getBegin(), DiagID)
782       << SS->getScopeRep() << II->getName()
783       << SourceRange(SS->getRange().getBegin(), IILoc)
784       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785     SuggestedType = ActOnTypenameType(S, SourceLocation(),
786                                       *SS, *II, IILoc).get();
787   } else {
788     assert(SS && SS->isInvalid() &&
789            "Invalid scope specifier has already been diagnosed");
790   }
791 }
792 
793 /// Determine whether the given result set contains either a type name
794 /// or
795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797                        NextToken.is(tok::less);
798 
799   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801       return true;
802 
803     if (CheckTemplate && isa<TemplateDecl>(*I))
804       return true;
805   }
806 
807   return false;
808 }
809 
810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811                                     Scope *S, CXXScopeSpec &SS,
812                                     IdentifierInfo *&Name,
813                                     SourceLocation NameLoc) {
814   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815   SemaRef.LookupParsedName(R, S, &SS);
816   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817     StringRef FixItTagName;
818     switch (Tag->getTagKind()) {
819       case TTK_Class:
820         FixItTagName = "class ";
821         break;
822 
823       case TTK_Enum:
824         FixItTagName = "enum ";
825         break;
826 
827       case TTK_Struct:
828         FixItTagName = "struct ";
829         break;
830 
831       case TTK_Interface:
832         FixItTagName = "__interface ";
833         break;
834 
835       case TTK_Union:
836         FixItTagName = "union ";
837         break;
838     }
839 
840     StringRef TagName = FixItTagName.drop_back();
841     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844 
845     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846          I != IEnd; ++I)
847       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848         << Name << TagName;
849 
850     // Replace lookup results with just the tag decl.
851     Result.clear(Sema::LookupTagName);
852     SemaRef.LookupParsedName(Result, S, &SS);
853     return true;
854   }
855 
856   return false;
857 }
858 
859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
860                                             IdentifierInfo *&Name,
861                                             SourceLocation NameLoc,
862                                             const Token &NextToken,
863                                             CorrectionCandidateCallback *CCC) {
864   DeclarationNameInfo NameInfo(Name, NameLoc);
865   ObjCMethodDecl *CurMethod = getCurMethodDecl();
866 
867   assert(NextToken.isNot(tok::coloncolon) &&
868          "parse nested name specifiers before calling ClassifyName");
869   if (getLangOpts().CPlusPlus && SS.isSet() &&
870       isCurrentClassName(*Name, S, &SS)) {
871     // Per [class.qual]p2, this names the constructors of SS, not the
872     // injected-class-name. We don't have a classification for that.
873     // There's not much point caching this result, since the parser
874     // will reject it later.
875     return NameClassification::Unknown();
876   }
877 
878   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879   LookupParsedName(Result, S, &SS, !CurMethod);
880 
881   if (SS.isInvalid())
882     return NameClassification::Error();
883 
884   // For unqualified lookup in a class template in MSVC mode, look into
885   // dependent base classes where the primary class template is known.
886   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887     if (ParsedType TypeInBase =
888             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889       return TypeInBase;
890   }
891 
892   // Perform lookup for Objective-C instance variables (including automatically
893   // synthesized instance variables), if we're in an Objective-C method.
894   // FIXME: This lookup really, really needs to be folded in to the normal
895   // unqualified lookup mechanism.
896   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898     if (Ivar.isInvalid())
899       return NameClassification::Error();
900     if (Ivar.isUsable())
901       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902 
903     // We defer builtin creation until after ivar lookup inside ObjC methods.
904     if (Result.empty())
905       LookupBuiltin(Result);
906   }
907 
908   bool SecondTry = false;
909   bool IsFilteredTemplateName = false;
910 
911 Corrected:
912   switch (Result.getResultKind()) {
913   case LookupResult::NotFound:
914     // If an unqualified-id is followed by a '(', then we have a function
915     // call.
916     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917       // In C++, this is an ADL-only call.
918       // FIXME: Reference?
919       if (getLangOpts().CPlusPlus)
920         return NameClassification::UndeclaredNonType();
921 
922       // C90 6.3.2.2:
923       //   If the expression that precedes the parenthesized argument list in a
924       //   function call consists solely of an identifier, and if no
925       //   declaration is visible for this identifier, the identifier is
926       //   implicitly declared exactly as if, in the innermost block containing
927       //   the function call, the declaration
928       //
929       //     extern int identifier ();
930       //
931       //   appeared.
932       //
933       // We also allow this in C99 as an extension.
934       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935         return NameClassification::NonType(D);
936     }
937 
938     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
939       // In C++20 onwards, this could be an ADL-only call to a function
940       // template, and we're required to assume that this is a template name.
941       //
942       // FIXME: Find a way to still do typo correction in this case.
943       TemplateName Template =
944           Context.getAssumedTemplateName(NameInfo.getName());
945       return NameClassification::UndeclaredTemplate(Template);
946     }
947 
948     // In C, we first see whether there is a tag type by the same name, in
949     // which case it's likely that the user just forgot to write "enum",
950     // "struct", or "union".
951     if (!getLangOpts().CPlusPlus && !SecondTry &&
952         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
953       break;
954     }
955 
956     // Perform typo correction to determine if there is another name that is
957     // close to this name.
958     if (!SecondTry && CCC) {
959       SecondTry = true;
960       if (TypoCorrection Corrected =
961               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962                           &SS, *CCC, CTK_ErrorRecovery)) {
963         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964         unsigned QualifiedDiag = diag::err_no_member_suggest;
965 
966         NamedDecl *FirstDecl = Corrected.getFoundDecl();
967         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
969             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970           UnqualifiedDiag = diag::err_no_template_suggest;
971           QualifiedDiag = diag::err_no_member_template_suggest;
972         } else if (UnderlyingFirstDecl &&
973                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
974                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976           UnqualifiedDiag = diag::err_unknown_typename_suggest;
977           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978         }
979 
980         if (SS.isEmpty()) {
981           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982         } else {// FIXME: is this even reachable? Test it.
983           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985                                   Name->getName().equals(CorrectedStr);
986           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987                                     << Name << computeDeclContext(SS, false)
988                                     << DroppedSpecifier << SS.getRange());
989         }
990 
991         // Update the name, so that the caller has the new name.
992         Name = Corrected.getCorrectionAsIdentifierInfo();
993 
994         // Typo correction corrected to a keyword.
995         if (Corrected.isKeyword())
996           return Name;
997 
998         // Also update the LookupResult...
999         // FIXME: This should probably go away at some point
1000         Result.clear();
1001         Result.setLookupName(Corrected.getCorrection());
1002         if (FirstDecl)
1003           Result.addDecl(FirstDecl);
1004 
1005         // If we found an Objective-C instance variable, let
1006         // LookupInObjCMethod build the appropriate expression to
1007         // reference the ivar.
1008         // FIXME: This is a gross hack.
1009         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010           DeclResult R =
1011               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012           if (R.isInvalid())
1013             return NameClassification::Error();
1014           if (R.isUsable())
1015             return NameClassification::NonType(Ivar);
1016         }
1017 
1018         goto Corrected;
1019       }
1020     }
1021 
1022     // We failed to correct; just fall through and let the parser deal with it.
1023     Result.suppressDiagnostics();
1024     return NameClassification::Unknown();
1025 
1026   case LookupResult::NotFoundInCurrentInstantiation: {
1027     // We performed name lookup into the current instantiation, and there were
1028     // dependent bases, so we treat this result the same way as any other
1029     // dependent nested-name-specifier.
1030 
1031     // C++ [temp.res]p2:
1032     //   A name used in a template declaration or definition and that is
1033     //   dependent on a template-parameter is assumed not to name a type
1034     //   unless the applicable name lookup finds a type name or the name is
1035     //   qualified by the keyword typename.
1036     //
1037     // FIXME: If the next token is '<', we might want to ask the parser to
1038     // perform some heroics to see if we actually have a
1039     // template-argument-list, which would indicate a missing 'template'
1040     // keyword here.
1041     return NameClassification::DependentNonType();
1042   }
1043 
1044   case LookupResult::Found:
1045   case LookupResult::FoundOverloaded:
1046   case LookupResult::FoundUnresolvedValue:
1047     break;
1048 
1049   case LookupResult::Ambiguous:
1050     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1051         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052                                       /*AllowDependent=*/false)) {
1053       // C++ [temp.local]p3:
1054       //   A lookup that finds an injected-class-name (10.2) can result in an
1055       //   ambiguity in certain cases (for example, if it is found in more than
1056       //   one base class). If all of the injected-class-names that are found
1057       //   refer to specializations of the same class template, and if the name
1058       //   is followed by a template-argument-list, the reference refers to the
1059       //   class template itself and not a specialization thereof, and is not
1060       //   ambiguous.
1061       //
1062       // This filtering can make an ambiguous result into an unambiguous one,
1063       // so try again after filtering out template names.
1064       FilterAcceptableTemplateNames(Result);
1065       if (!Result.isAmbiguous()) {
1066         IsFilteredTemplateName = true;
1067         break;
1068       }
1069     }
1070 
1071     // Diagnose the ambiguity and return an error.
1072     return NameClassification::Error();
1073   }
1074 
1075   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076       (IsFilteredTemplateName ||
1077        hasAnyAcceptableTemplateNames(
1078            Result, /*AllowFunctionTemplates=*/true,
1079            /*AllowDependent=*/false,
1080            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081                getLangOpts().CPlusPlus20))) {
1082     // C++ [temp.names]p3:
1083     //   After name lookup (3.4) finds that a name is a template-name or that
1084     //   an operator-function-id or a literal- operator-id refers to a set of
1085     //   overloaded functions any member of which is a function template if
1086     //   this is followed by a <, the < is always taken as the delimiter of a
1087     //   template-argument-list and never as the less-than operator.
1088     // C++2a [temp.names]p2:
1089     //   A name is also considered to refer to a template if it is an
1090     //   unqualified-id followed by a < and name lookup finds either one
1091     //   or more functions or finds nothing.
1092     if (!IsFilteredTemplateName)
1093       FilterAcceptableTemplateNames(Result);
1094 
1095     bool IsFunctionTemplate;
1096     bool IsVarTemplate;
1097     TemplateName Template;
1098     if (Result.end() - Result.begin() > 1) {
1099       IsFunctionTemplate = true;
1100       Template = Context.getOverloadedTemplateName(Result.begin(),
1101                                                    Result.end());
1102     } else if (!Result.empty()) {
1103       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104           *Result.begin(), /*AllowFunctionTemplates=*/true,
1105           /*AllowDependent=*/false));
1106       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107       IsVarTemplate = isa<VarTemplateDecl>(TD);
1108 
1109       if (SS.isNotEmpty())
1110         Template =
1111             Context.getQualifiedTemplateName(SS.getScopeRep(),
1112                                              /*TemplateKeyword=*/false, TD);
1113       else
1114         Template = TemplateName(TD);
1115     } else {
1116       // All results were non-template functions. This is a function template
1117       // name.
1118       IsFunctionTemplate = true;
1119       Template = Context.getAssumedTemplateName(NameInfo.getName());
1120     }
1121 
1122     if (IsFunctionTemplate) {
1123       // Function templates always go through overload resolution, at which
1124       // point we'll perform the various checks (e.g., accessibility) we need
1125       // to based on which function we selected.
1126       Result.suppressDiagnostics();
1127 
1128       return NameClassification::FunctionTemplate(Template);
1129     }
1130 
1131     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132                          : NameClassification::TypeTemplate(Template);
1133   }
1134 
1135   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136     QualType T = Context.getTypeDeclType(Type);
1137     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138       T = Context.getUsingType(USD, T);
1139 
1140     if (SS.isEmpty()) // No elaborated type, trivial location info
1141       return ParsedType::make(T);
1142 
1143     TypeLocBuilder Builder;
1144     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145     T = getElaboratedType(ETK_None, SS, T);
1146     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1147     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1148     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150   };
1151 
1152   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154     DiagnoseUseOfDecl(Type, NameLoc);
1155     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156     return BuildTypeFor(Type, *Result.begin());
1157   }
1158 
1159   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160   if (!Class) {
1161     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162     if (ObjCCompatibleAliasDecl *Alias =
1163             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164       Class = Alias->getClassInterface();
1165   }
1166 
1167   if (Class) {
1168     DiagnoseUseOfDecl(Class, NameLoc);
1169 
1170     if (NextToken.is(tok::period)) {
1171       // Interface. <something> is parsed as a property reference expression.
1172       // Just return "unknown" as a fall-through for now.
1173       Result.suppressDiagnostics();
1174       return NameClassification::Unknown();
1175     }
1176 
1177     QualType T = Context.getObjCInterfaceType(Class);
1178     return ParsedType::make(T);
1179   }
1180 
1181   if (isa<ConceptDecl>(FirstDecl))
1182     return NameClassification::Concept(
1183         TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 
1185   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187     return NameClassification::Error();
1188   }
1189 
1190   // We can have a type template here if we're classifying a template argument.
1191   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192       !isa<VarTemplateDecl>(FirstDecl))
1193     return NameClassification::TypeTemplate(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   // Check for a tag type hidden by a non-type decl in a few cases where it
1197   // seems likely a type is wanted instead of the non-type that was found.
1198   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199   if ((NextToken.is(tok::identifier) ||
1200        (NextIsOp &&
1201         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204     DiagnoseUseOfDecl(Type, NameLoc);
1205     return BuildTypeFor(Type, *Result.begin());
1206   }
1207 
1208   // If we already know which single declaration is referenced, just annotate
1209   // that declaration directly. Defer resolving even non-overloaded class
1210   // member accesses, as we need to defer certain access checks until we know
1211   // the context.
1212   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1214     return NameClassification::NonType(Result.getRepresentativeDecl());
1215 
1216   // Otherwise, this is an overload set that we will need to resolve later.
1217   Result.suppressDiagnostics();
1218   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221       Result.begin(), Result.end()));
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1226                                              SourceLocation NameLoc) {
1227   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228   CXXScopeSpec SS;
1229   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231 }
1232 
1233 ExprResult
1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1235                                             IdentifierInfo *Name,
1236                                             SourceLocation NameLoc,
1237                                             bool IsAddressOfOperand) {
1238   DeclarationNameInfo NameInfo(Name, NameLoc);
1239   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240                                     NameInfo, IsAddressOfOperand,
1241                                     /*TemplateArgs=*/nullptr);
1242 }
1243 
1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1245                                               NamedDecl *Found,
1246                                               SourceLocation NameLoc,
1247                                               const Token &NextToken) {
1248   if (getCurMethodDecl() && SS.isEmpty())
1249     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250       return BuildIvarRefExpr(S, NameLoc, Ivar);
1251 
1252   // Reconstruct the lookup result.
1253   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254   Result.addDecl(Found);
1255   Result.resolveKind();
1256 
1257   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258   return BuildDeclarationNameExpr(SS, Result, ADL);
1259 }
1260 
1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1262   // For an implicit class member access, transform the result into a member
1263   // access expression if necessary.
1264   auto *ULE = cast<UnresolvedLookupExpr>(E);
1265   if ((*ULE->decls_begin())->isCXXClassMember()) {
1266     CXXScopeSpec SS;
1267     SS.Adopt(ULE->getQualifierLoc());
1268 
1269     // Reconstruct the lookup result.
1270     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271                         LookupOrdinaryName);
1272     Result.setNamingClass(ULE->getNamingClass());
1273     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274       Result.addDecl(*I, I.getAccess());
1275     Result.resolveKind();
1276     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277                                            nullptr, S);
1278   }
1279 
1280   // Otherwise, this is already in the form we needed, and no further checks
1281   // are necessary.
1282   return ULE;
1283 }
1284 
1285 Sema::TemplateNameKindForDiagnostics
1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1287   auto *TD = Name.getAsTemplateDecl();
1288   if (!TD)
1289     return TemplateNameKindForDiagnostics::DependentTemplate;
1290   if (isa<ClassTemplateDecl>(TD))
1291     return TemplateNameKindForDiagnostics::ClassTemplate;
1292   if (isa<FunctionTemplateDecl>(TD))
1293     return TemplateNameKindForDiagnostics::FunctionTemplate;
1294   if (isa<VarTemplateDecl>(TD))
1295     return TemplateNameKindForDiagnostics::VarTemplate;
1296   if (isa<TypeAliasTemplateDecl>(TD))
1297     return TemplateNameKindForDiagnostics::AliasTemplate;
1298   if (isa<TemplateTemplateParmDecl>(TD))
1299     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300   if (isa<ConceptDecl>(TD))
1301     return TemplateNameKindForDiagnostics::Concept;
1302   return TemplateNameKindForDiagnostics::DependentTemplate;
1303 }
1304 
1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1306   assert(DC->getLexicalParent() == CurContext &&
1307       "The next DeclContext should be lexically contained in the current one.");
1308   CurContext = DC;
1309   S->setEntity(DC);
1310 }
1311 
1312 void Sema::PopDeclContext() {
1313   assert(CurContext && "DeclContext imbalance!");
1314 
1315   CurContext = CurContext->getLexicalParent();
1316   assert(CurContext && "Popped translation unit!");
1317 }
1318 
1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1320                                                                     Decl *D) {
1321   // Unlike PushDeclContext, the context to which we return is not necessarily
1322   // the containing DC of TD, because the new context will be some pre-existing
1323   // TagDecl definition instead of a fresh one.
1324   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325   CurContext = cast<TagDecl>(D)->getDefinition();
1326   assert(CurContext && "skipping definition of undefined tag");
1327   // Start lookups from the parent of the current context; we don't want to look
1328   // into the pre-existing complete definition.
1329   S->setEntity(CurContext->getLookupParent());
1330   return Result;
1331 }
1332 
1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1334   CurContext = static_cast<decltype(CurContext)>(Context);
1335 }
1336 
1337 /// EnterDeclaratorContext - Used when we must lookup names in the context
1338 /// of a declarator's nested name specifier.
1339 ///
1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1341   // C++0x [basic.lookup.unqual]p13:
1342   //   A name used in the definition of a static data member of class
1343   //   X (after the qualified-id of the static member) is looked up as
1344   //   if the name was used in a member function of X.
1345   // C++0x [basic.lookup.unqual]p14:
1346   //   If a variable member of a namespace is defined outside of the
1347   //   scope of its namespace then any name used in the definition of
1348   //   the variable member (after the declarator-id) is looked up as
1349   //   if the definition of the variable member occurred in its
1350   //   namespace.
1351   // Both of these imply that we should push a scope whose context
1352   // is the semantic context of the declaration.  We can't use
1353   // PushDeclContext here because that context is not necessarily
1354   // lexically contained in the current context.  Fortunately,
1355   // the containing scope should have the appropriate information.
1356 
1357   assert(!S->getEntity() && "scope already has entity");
1358 
1359 #ifndef NDEBUG
1360   Scope *Ancestor = S->getParent();
1361   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363 #endif
1364 
1365   CurContext = DC;
1366   S->setEntity(DC);
1367 
1368   if (S->getParent()->isTemplateParamScope()) {
1369     // Also set the corresponding entities for all immediately-enclosing
1370     // template parameter scopes.
1371     EnterTemplatedContext(S->getParent(), DC);
1372   }
1373 }
1374 
1375 void Sema::ExitDeclaratorContext(Scope *S) {
1376   assert(S->getEntity() == CurContext && "Context imbalance!");
1377 
1378   // Switch back to the lexical context.  The safety of this is
1379   // enforced by an assert in EnterDeclaratorContext.
1380   Scope *Ancestor = S->getParent();
1381   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382   CurContext = Ancestor->getEntity();
1383 
1384   // We don't need to do anything with the scope, which is going to
1385   // disappear.
1386 }
1387 
1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1389   assert(S->isTemplateParamScope() &&
1390          "expected to be initializing a template parameter scope");
1391 
1392   // C++20 [temp.local]p7:
1393   //   In the definition of a member of a class template that appears outside
1394   //   of the class template definition, the name of a member of the class
1395   //   template hides the name of a template-parameter of any enclosing class
1396   //   templates (but not a template-parameter of the member if the member is a
1397   //   class or function template).
1398   // C++20 [temp.local]p9:
1399   //   In the definition of a class template or in the definition of a member
1400   //   of such a template that appears outside of the template definition, for
1401   //   each non-dependent base class (13.8.2.1), if the name of the base class
1402   //   or the name of a member of the base class is the same as the name of a
1403   //   template-parameter, the base class name or member name hides the
1404   //   template-parameter name (6.4.10).
1405   //
1406   // This means that a template parameter scope should be searched immediately
1407   // after searching the DeclContext for which it is a template parameter
1408   // scope. For example, for
1409   //   template<typename T> template<typename U> template<typename V>
1410   //     void N::A<T>::B<U>::f(...)
1411   // we search V then B<U> (and base classes) then U then A<T> (and base
1412   // classes) then T then N then ::.
1413   unsigned ScopeDepth = getTemplateDepth(S);
1414   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415     DeclContext *SearchDCAfterScope = DC;
1416     for (; DC; DC = DC->getLookupParent()) {
1417       if (const TemplateParameterList *TPL =
1418               cast<Decl>(DC)->getDescribedTemplateParams()) {
1419         unsigned DCDepth = TPL->getDepth() + 1;
1420         if (DCDepth > ScopeDepth)
1421           continue;
1422         if (ScopeDepth == DCDepth)
1423           SearchDCAfterScope = DC = DC->getLookupParent();
1424         break;
1425       }
1426     }
1427     S->setLookupEntity(SearchDCAfterScope);
1428   }
1429 }
1430 
1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1432   // We assume that the caller has already called
1433   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434   FunctionDecl *FD = D->getAsFunction();
1435   if (!FD)
1436     return;
1437 
1438   // Same implementation as PushDeclContext, but enters the context
1439   // from the lexical parent, rather than the top-level class.
1440   assert(CurContext == FD->getLexicalParent() &&
1441     "The next DeclContext should be lexically contained in the current one.");
1442   CurContext = FD;
1443   S->setEntity(CurContext);
1444 
1445   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446     ParmVarDecl *Param = FD->getParamDecl(P);
1447     // If the parameter has an identifier, then add it to the scope
1448     if (Param->getIdentifier()) {
1449       S->AddDecl(Param);
1450       IdResolver.AddDecl(Param);
1451     }
1452   }
1453 }
1454 
1455 void Sema::ActOnExitFunctionContext() {
1456   // Same implementation as PopDeclContext, but returns to the lexical parent,
1457   // rather than the top-level class.
1458   assert(CurContext && "DeclContext imbalance!");
1459   CurContext = CurContext->getLexicalParent();
1460   assert(CurContext && "Popped translation unit!");
1461 }
1462 
1463 /// Determine whether overloading is allowed for a new function
1464 /// declaration considering prior declarations of the same name.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether a new declaration actually overloads a previous one.
1468 /// It will return true in C++ (where overloads are alway permitted)
1469 /// or, as a C extension, when either the new declaration or a
1470 /// previous one is declared with the 'overloadable' attribute.
1471 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1472                                        ASTContext &Context,
1473                                        const FunctionDecl *New) {
1474   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1475     return true;
1476 
1477   // Multiversion function declarations are not overloads in the
1478   // usual sense of that term, but lookup will report that an
1479   // overload set was found if more than one multiversion function
1480   // declaration is present for the same name. It is therefore
1481   // inadequate to assume that some prior declaration(s) had
1482   // the overloadable attribute; checking is required. Since one
1483   // declaration is permitted to omit the attribute, it is necessary
1484   // to check at least two; hence the 'any_of' check below. Note that
1485   // the overloadable attribute is implicitly added to declarations
1486   // that were required to have it but did not.
1487   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1488     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1489       return ND->hasAttr<OverloadableAttr>();
1490     });
1491   } else if (Previous.getResultKind() == LookupResult::Found)
1492     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1493 
1494   return false;
1495 }
1496 
1497 /// Add this decl to the scope shadowed decl chains.
1498 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1499   // Move up the scope chain until we find the nearest enclosing
1500   // non-transparent context. The declaration will be introduced into this
1501   // scope.
1502   while (S->getEntity() && S->getEntity()->isTransparentContext())
1503     S = S->getParent();
1504 
1505   // Add scoped declarations into their context, so that they can be
1506   // found later. Declarations without a context won't be inserted
1507   // into any context.
1508   if (AddToContext)
1509     CurContext->addDecl(D);
1510 
1511   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1512   // are function-local declarations.
1513   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1514     return;
1515 
1516   // Template instantiations should also not be pushed into scope.
1517   if (isa<FunctionDecl>(D) &&
1518       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1519     return;
1520 
1521   // If this replaces anything in the current scope,
1522   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1523                                IEnd = IdResolver.end();
1524   for (; I != IEnd; ++I) {
1525     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1526       S->RemoveDecl(*I);
1527       IdResolver.RemoveDecl(*I);
1528 
1529       // Should only need to replace one decl.
1530       break;
1531     }
1532   }
1533 
1534   S->AddDecl(D);
1535 
1536   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1537     // Implicitly-generated labels may end up getting generated in an order that
1538     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1539     // the label at the appropriate place in the identifier chain.
1540     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1541       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1542       if (IDC == CurContext) {
1543         if (!S->isDeclScope(*I))
1544           continue;
1545       } else if (IDC->Encloses(CurContext))
1546         break;
1547     }
1548 
1549     IdResolver.InsertDeclAfter(I, D);
1550   } else {
1551     IdResolver.AddDecl(D);
1552   }
1553   warnOnReservedIdentifier(D);
1554 }
1555 
1556 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1557                          bool AllowInlineNamespace) {
1558   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1559 }
1560 
1561 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1562   DeclContext *TargetDC = DC->getPrimaryContext();
1563   do {
1564     if (DeclContext *ScopeDC = S->getEntity())
1565       if (ScopeDC->getPrimaryContext() == TargetDC)
1566         return S;
1567   } while ((S = S->getParent()));
1568 
1569   return nullptr;
1570 }
1571 
1572 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1573                                             DeclContext*,
1574                                             ASTContext&);
1575 
1576 /// Filters out lookup results that don't fall within the given scope
1577 /// as determined by isDeclInScope.
1578 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1579                                 bool ConsiderLinkage,
1580                                 bool AllowInlineNamespace) {
1581   LookupResult::Filter F = R.makeFilter();
1582   while (F.hasNext()) {
1583     NamedDecl *D = F.next();
1584 
1585     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586       continue;
1587 
1588     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589       continue;
1590 
1591     F.erase();
1592   }
1593 
1594   F.done();
1595 }
1596 
1597 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1598 /// have compatible owning modules.
1599 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1600   // [module.interface]p7:
1601   // A declaration is attached to a module as follows:
1602   // - If the declaration is a non-dependent friend declaration that nominates a
1603   // function with a declarator-id that is a qualified-id or template-id or that
1604   // nominates a class other than with an elaborated-type-specifier with neither
1605   // a nested-name-specifier nor a simple-template-id, it is attached to the
1606   // module to which the friend is attached ([basic.link]).
1607   if (New->getFriendObjectKind() &&
1608       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1609     New->setLocalOwningModule(Old->getOwningModule());
1610     makeMergedDefinitionVisible(New);
1611     return false;
1612   }
1613 
1614   Module *NewM = New->getOwningModule();
1615   Module *OldM = Old->getOwningModule();
1616 
1617   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1618     NewM = NewM->Parent;
1619   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1620     OldM = OldM->Parent;
1621 
1622   // If we have a decl in a module partition, it is part of the containing
1623   // module (which is the only thing that can be importing it).
1624   if (NewM && OldM &&
1625       (OldM->Kind == Module::ModulePartitionInterface ||
1626        OldM->Kind == Module::ModulePartitionImplementation)) {
1627     return false;
1628   }
1629 
1630   if (NewM == OldM)
1631     return false;
1632 
1633   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1634   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1635   if (NewIsModuleInterface || OldIsModuleInterface) {
1636     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1637     //   if a declaration of D [...] appears in the purview of a module, all
1638     //   other such declarations shall appear in the purview of the same module
1639     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1640       << New
1641       << NewIsModuleInterface
1642       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1643       << OldIsModuleInterface
1644       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1645     Diag(Old->getLocation(), diag::note_previous_declaration);
1646     New->setInvalidDecl();
1647     return true;
1648   }
1649 
1650   return false;
1651 }
1652 
1653 // [module.interface]p6:
1654 // A redeclaration of an entity X is implicitly exported if X was introduced by
1655 // an exported declaration; otherwise it shall not be exported.
1656 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1657   // [module.interface]p1:
1658   // An export-declaration shall inhabit a namespace scope.
1659   //
1660   // So it is meaningless to talk about redeclaration which is not at namespace
1661   // scope.
1662   if (!New->getLexicalDeclContext()
1663            ->getNonTransparentContext()
1664            ->isFileContext() ||
1665       !Old->getLexicalDeclContext()
1666            ->getNonTransparentContext()
1667            ->isFileContext())
1668     return false;
1669 
1670   bool IsNewExported = New->isInExportDeclContext();
1671   bool IsOldExported = Old->isInExportDeclContext();
1672 
1673   // It should be irrevelant if both of them are not exported.
1674   if (!IsNewExported && !IsOldExported)
1675     return false;
1676 
1677   if (IsOldExported)
1678     return false;
1679 
1680   assert(IsNewExported);
1681 
1682   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
1683   Diag(Old->getLocation(), diag::note_previous_declaration);
1684   return true;
1685 }
1686 
1687 // A wrapper function for checking the semantic restrictions of
1688 // a redeclaration within a module.
1689 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1690   if (CheckRedeclarationModuleOwnership(New, Old))
1691     return true;
1692 
1693   if (CheckRedeclarationExported(New, Old))
1694     return true;
1695 
1696   return false;
1697 }
1698 
1699 static bool isUsingDecl(NamedDecl *D) {
1700   return isa<UsingShadowDecl>(D) ||
1701          isa<UnresolvedUsingTypenameDecl>(D) ||
1702          isa<UnresolvedUsingValueDecl>(D);
1703 }
1704 
1705 /// Removes using shadow declarations from the lookup results.
1706 static void RemoveUsingDecls(LookupResult &R) {
1707   LookupResult::Filter F = R.makeFilter();
1708   while (F.hasNext())
1709     if (isUsingDecl(F.next()))
1710       F.erase();
1711 
1712   F.done();
1713 }
1714 
1715 /// Check for this common pattern:
1716 /// @code
1717 /// class S {
1718 ///   S(const S&); // DO NOT IMPLEMENT
1719 ///   void operator=(const S&); // DO NOT IMPLEMENT
1720 /// };
1721 /// @endcode
1722 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1723   // FIXME: Should check for private access too but access is set after we get
1724   // the decl here.
1725   if (D->doesThisDeclarationHaveABody())
1726     return false;
1727 
1728   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1729     return CD->isCopyConstructor();
1730   return D->isCopyAssignmentOperator();
1731 }
1732 
1733 // We need this to handle
1734 //
1735 // typedef struct {
1736 //   void *foo() { return 0; }
1737 // } A;
1738 //
1739 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1740 // for example. If 'A', foo will have external linkage. If we have '*A',
1741 // foo will have no linkage. Since we can't know until we get to the end
1742 // of the typedef, this function finds out if D might have non-external linkage.
1743 // Callers should verify at the end of the TU if it D has external linkage or
1744 // not.
1745 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1746   const DeclContext *DC = D->getDeclContext();
1747   while (!DC->isTranslationUnit()) {
1748     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1749       if (!RD->hasNameForLinkage())
1750         return true;
1751     }
1752     DC = DC->getParent();
1753   }
1754 
1755   return !D->isExternallyVisible();
1756 }
1757 
1758 // FIXME: This needs to be refactored; some other isInMainFile users want
1759 // these semantics.
1760 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1761   if (S.TUKind != TU_Complete)
1762     return false;
1763   return S.SourceMgr.isInMainFile(Loc);
1764 }
1765 
1766 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1767   assert(D);
1768 
1769   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1770     return false;
1771 
1772   // Ignore all entities declared within templates, and out-of-line definitions
1773   // of members of class templates.
1774   if (D->getDeclContext()->isDependentContext() ||
1775       D->getLexicalDeclContext()->isDependentContext())
1776     return false;
1777 
1778   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1779     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1780       return false;
1781     // A non-out-of-line declaration of a member specialization was implicitly
1782     // instantiated; it's the out-of-line declaration that we're interested in.
1783     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1784         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1785       return false;
1786 
1787     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1788       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1789         return false;
1790     } else {
1791       // 'static inline' functions are defined in headers; don't warn.
1792       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1793         return false;
1794     }
1795 
1796     if (FD->doesThisDeclarationHaveABody() &&
1797         Context.DeclMustBeEmitted(FD))
1798       return false;
1799   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     // Constants and utility variables are defined in headers with internal
1801     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1802     // like "inline".)
1803     if (!isMainFileLoc(*this, VD->getLocation()))
1804       return false;
1805 
1806     if (Context.DeclMustBeEmitted(VD))
1807       return false;
1808 
1809     if (VD->isStaticDataMember() &&
1810         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1811       return false;
1812     if (VD->isStaticDataMember() &&
1813         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1814         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1815       return false;
1816 
1817     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1818       return false;
1819   } else {
1820     return false;
1821   }
1822 
1823   // Only warn for unused decls internal to the translation unit.
1824   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1825   // for inline functions defined in the main source file, for instance.
1826   return mightHaveNonExternalLinkage(D);
1827 }
1828 
1829 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1830   if (!D)
1831     return;
1832 
1833   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1834     const FunctionDecl *First = FD->getFirstDecl();
1835     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1836       return; // First should already be in the vector.
1837   }
1838 
1839   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1840     const VarDecl *First = VD->getFirstDecl();
1841     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1842       return; // First should already be in the vector.
1843   }
1844 
1845   if (ShouldWarnIfUnusedFileScopedDecl(D))
1846     UnusedFileScopedDecls.push_back(D);
1847 }
1848 
1849 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1850   if (D->isInvalidDecl())
1851     return false;
1852 
1853   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1854     // For a decomposition declaration, warn if none of the bindings are
1855     // referenced, instead of if the variable itself is referenced (which
1856     // it is, by the bindings' expressions).
1857     for (auto *BD : DD->bindings())
1858       if (BD->isReferenced())
1859         return false;
1860   } else if (!D->getDeclName()) {
1861     return false;
1862   } else if (D->isReferenced() || D->isUsed()) {
1863     return false;
1864   }
1865 
1866   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1867     return false;
1868 
1869   if (isa<LabelDecl>(D))
1870     return true;
1871 
1872   // Except for labels, we only care about unused decls that are local to
1873   // functions.
1874   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1875   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1876     // For dependent types, the diagnostic is deferred.
1877     WithinFunction =
1878         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1879   if (!WithinFunction)
1880     return false;
1881 
1882   if (isa<TypedefNameDecl>(D))
1883     return true;
1884 
1885   // White-list anything that isn't a local variable.
1886   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1887     return false;
1888 
1889   // Types of valid local variables should be complete, so this should succeed.
1890   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1891 
1892     const Expr *Init = VD->getInit();
1893     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1894       Init = Cleanups->getSubExpr();
1895 
1896     const auto *Ty = VD->getType().getTypePtr();
1897 
1898     // Only look at the outermost level of typedef.
1899     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1900       // Allow anything marked with __attribute__((unused)).
1901       if (TT->getDecl()->hasAttr<UnusedAttr>())
1902         return false;
1903     }
1904 
1905     // Warn for reference variables whose initializtion performs lifetime
1906     // extension.
1907     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1908       if (MTE->getExtendingDecl()) {
1909         Ty = VD->getType().getNonReferenceType().getTypePtr();
1910         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1911       }
1912     }
1913 
1914     // If we failed to complete the type for some reason, or if the type is
1915     // dependent, don't diagnose the variable.
1916     if (Ty->isIncompleteType() || Ty->isDependentType())
1917       return false;
1918 
1919     // Look at the element type to ensure that the warning behaviour is
1920     // consistent for both scalars and arrays.
1921     Ty = Ty->getBaseElementTypeUnsafe();
1922 
1923     if (const TagType *TT = Ty->getAs<TagType>()) {
1924       const TagDecl *Tag = TT->getDecl();
1925       if (Tag->hasAttr<UnusedAttr>())
1926         return false;
1927 
1928       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1929         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1930           return false;
1931 
1932         if (Init) {
1933           const CXXConstructExpr *Construct =
1934             dyn_cast<CXXConstructExpr>(Init);
1935           if (Construct && !Construct->isElidable()) {
1936             CXXConstructorDecl *CD = Construct->getConstructor();
1937             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1938                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1939               return false;
1940           }
1941 
1942           // Suppress the warning if we don't know how this is constructed, and
1943           // it could possibly be non-trivial constructor.
1944           if (Init->isTypeDependent()) {
1945             for (const CXXConstructorDecl *Ctor : RD->ctors())
1946               if (!Ctor->isTrivial())
1947                 return false;
1948           }
1949 
1950           // Suppress the warning if the constructor is unresolved because
1951           // its arguments are dependent.
1952           if (isa<CXXUnresolvedConstructExpr>(Init))
1953             return false;
1954         }
1955       }
1956     }
1957 
1958     // TODO: __attribute__((unused)) templates?
1959   }
1960 
1961   return true;
1962 }
1963 
1964 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1965                                      FixItHint &Hint) {
1966   if (isa<LabelDecl>(D)) {
1967     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1968         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1969         true);
1970     if (AfterColon.isInvalid())
1971       return;
1972     Hint = FixItHint::CreateRemoval(
1973         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1974   }
1975 }
1976 
1977 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1978   if (D->getTypeForDecl()->isDependentType())
1979     return;
1980 
1981   for (auto *TmpD : D->decls()) {
1982     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1983       DiagnoseUnusedDecl(T);
1984     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1985       DiagnoseUnusedNestedTypedefs(R);
1986   }
1987 }
1988 
1989 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1990 /// unless they are marked attr(unused).
1991 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1992   if (!ShouldDiagnoseUnusedDecl(D))
1993     return;
1994 
1995   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1996     // typedefs can be referenced later on, so the diagnostics are emitted
1997     // at end-of-translation-unit.
1998     UnusedLocalTypedefNameCandidates.insert(TD);
1999     return;
2000   }
2001 
2002   FixItHint Hint;
2003   GenerateFixForUnusedDecl(D, Context, Hint);
2004 
2005   unsigned DiagID;
2006   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2007     DiagID = diag::warn_unused_exception_param;
2008   else if (isa<LabelDecl>(D))
2009     DiagID = diag::warn_unused_label;
2010   else
2011     DiagID = diag::warn_unused_variable;
2012 
2013   Diag(D->getLocation(), DiagID) << D << Hint;
2014 }
2015 
2016 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2017   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2018   // it's not really unused.
2019   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2020       VD->hasAttr<CleanupAttr>())
2021     return;
2022 
2023   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2024 
2025   if (Ty->isReferenceType() || Ty->isDependentType())
2026     return;
2027 
2028   if (const TagType *TT = Ty->getAs<TagType>()) {
2029     const TagDecl *Tag = TT->getDecl();
2030     if (Tag->hasAttr<UnusedAttr>())
2031       return;
2032     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2033     // mimic gcc's behavior.
2034     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2035       if (!RD->hasAttr<WarnUnusedAttr>())
2036         return;
2037     }
2038   }
2039 
2040   // Don't warn about __block Objective-C pointer variables, as they might
2041   // be assigned in the block but not used elsewhere for the purpose of lifetime
2042   // extension.
2043   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2044     return;
2045 
2046   // Don't warn about Objective-C pointer variables with precise lifetime
2047   // semantics; they can be used to ensure ARC releases the object at a known
2048   // time, which may mean assignment but no other references.
2049   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2050     return;
2051 
2052   auto iter = RefsMinusAssignments.find(VD);
2053   if (iter == RefsMinusAssignments.end())
2054     return;
2055 
2056   assert(iter->getSecond() >= 0 &&
2057          "Found a negative number of references to a VarDecl");
2058   if (iter->getSecond() != 0)
2059     return;
2060   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2061                                          : diag::warn_unused_but_set_variable;
2062   Diag(VD->getLocation(), DiagID) << VD;
2063 }
2064 
2065 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2066   // Verify that we have no forward references left.  If so, there was a goto
2067   // or address of a label taken, but no definition of it.  Label fwd
2068   // definitions are indicated with a null substmt which is also not a resolved
2069   // MS inline assembly label name.
2070   bool Diagnose = false;
2071   if (L->isMSAsmLabel())
2072     Diagnose = !L->isResolvedMSAsmLabel();
2073   else
2074     Diagnose = L->getStmt() == nullptr;
2075   if (Diagnose)
2076     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2077 }
2078 
2079 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2080   S->mergeNRVOIntoParent();
2081 
2082   if (S->decl_empty()) return;
2083   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2084          "Scope shouldn't contain decls!");
2085 
2086   for (auto *TmpD : S->decls()) {
2087     assert(TmpD && "This decl didn't get pushed??");
2088 
2089     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2090     NamedDecl *D = cast<NamedDecl>(TmpD);
2091 
2092     // Diagnose unused variables in this scope.
2093     if (!S->hasUnrecoverableErrorOccurred()) {
2094       DiagnoseUnusedDecl(D);
2095       if (const auto *RD = dyn_cast<RecordDecl>(D))
2096         DiagnoseUnusedNestedTypedefs(RD);
2097       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2098         DiagnoseUnusedButSetDecl(VD);
2099         RefsMinusAssignments.erase(VD);
2100       }
2101     }
2102 
2103     if (!D->getDeclName()) continue;
2104 
2105     // If this was a forward reference to a label, verify it was defined.
2106     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2107       CheckPoppedLabel(LD, *this);
2108 
2109     // Remove this name from our lexical scope, and warn on it if we haven't
2110     // already.
2111     IdResolver.RemoveDecl(D);
2112     auto ShadowI = ShadowingDecls.find(D);
2113     if (ShadowI != ShadowingDecls.end()) {
2114       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2115         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2116             << D << FD << FD->getParent();
2117         Diag(FD->getLocation(), diag::note_previous_declaration);
2118       }
2119       ShadowingDecls.erase(ShadowI);
2120     }
2121   }
2122 }
2123 
2124 /// Look for an Objective-C class in the translation unit.
2125 ///
2126 /// \param Id The name of the Objective-C class we're looking for. If
2127 /// typo-correction fixes this name, the Id will be updated
2128 /// to the fixed name.
2129 ///
2130 /// \param IdLoc The location of the name in the translation unit.
2131 ///
2132 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2133 /// if there is no class with the given name.
2134 ///
2135 /// \returns The declaration of the named Objective-C class, or NULL if the
2136 /// class could not be found.
2137 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2138                                               SourceLocation IdLoc,
2139                                               bool DoTypoCorrection) {
2140   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2141   // creation from this context.
2142   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2143 
2144   if (!IDecl && DoTypoCorrection) {
2145     // Perform typo correction at the given location, but only if we
2146     // find an Objective-C class name.
2147     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2148     if (TypoCorrection C =
2149             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2150                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2151       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2152       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2153       Id = IDecl->getIdentifier();
2154     }
2155   }
2156   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2157   // This routine must always return a class definition, if any.
2158   if (Def && Def->getDefinition())
2159       Def = Def->getDefinition();
2160   return Def;
2161 }
2162 
2163 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2164 /// from S, where a non-field would be declared. This routine copes
2165 /// with the difference between C and C++ scoping rules in structs and
2166 /// unions. For example, the following code is well-formed in C but
2167 /// ill-formed in C++:
2168 /// @code
2169 /// struct S6 {
2170 ///   enum { BAR } e;
2171 /// };
2172 ///
2173 /// void test_S6() {
2174 ///   struct S6 a;
2175 ///   a.e = BAR;
2176 /// }
2177 /// @endcode
2178 /// For the declaration of BAR, this routine will return a different
2179 /// scope. The scope S will be the scope of the unnamed enumeration
2180 /// within S6. In C++, this routine will return the scope associated
2181 /// with S6, because the enumeration's scope is a transparent
2182 /// context but structures can contain non-field names. In C, this
2183 /// routine will return the translation unit scope, since the
2184 /// enumeration's scope is a transparent context and structures cannot
2185 /// contain non-field names.
2186 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2187   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2188          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2189          (S->isClassScope() && !getLangOpts().CPlusPlus))
2190     S = S->getParent();
2191   return S;
2192 }
2193 
2194 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2195                                ASTContext::GetBuiltinTypeError Error) {
2196   switch (Error) {
2197   case ASTContext::GE_None:
2198     return "";
2199   case ASTContext::GE_Missing_type:
2200     return BuiltinInfo.getHeaderName(ID);
2201   case ASTContext::GE_Missing_stdio:
2202     return "stdio.h";
2203   case ASTContext::GE_Missing_setjmp:
2204     return "setjmp.h";
2205   case ASTContext::GE_Missing_ucontext:
2206     return "ucontext.h";
2207   }
2208   llvm_unreachable("unhandled error kind");
2209 }
2210 
2211 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2212                                   unsigned ID, SourceLocation Loc) {
2213   DeclContext *Parent = Context.getTranslationUnitDecl();
2214 
2215   if (getLangOpts().CPlusPlus) {
2216     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2217         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2218     CLinkageDecl->setImplicit();
2219     Parent->addDecl(CLinkageDecl);
2220     Parent = CLinkageDecl;
2221   }
2222 
2223   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2224                                            /*TInfo=*/nullptr, SC_Extern,
2225                                            getCurFPFeatures().isFPConstrained(),
2226                                            false, Type->isFunctionProtoType());
2227   New->setImplicit();
2228   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2229 
2230   // Create Decl objects for each parameter, adding them to the
2231   // FunctionDecl.
2232   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2233     SmallVector<ParmVarDecl *, 16> Params;
2234     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2235       ParmVarDecl *parm = ParmVarDecl::Create(
2236           Context, New, SourceLocation(), SourceLocation(), nullptr,
2237           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2238       parm->setScopeInfo(0, i);
2239       Params.push_back(parm);
2240     }
2241     New->setParams(Params);
2242   }
2243 
2244   AddKnownFunctionAttributes(New);
2245   return New;
2246 }
2247 
2248 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2249 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2250 /// if we're creating this built-in in anticipation of redeclaring the
2251 /// built-in.
2252 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2253                                      Scope *S, bool ForRedeclaration,
2254                                      SourceLocation Loc) {
2255   LookupNecessaryTypesForBuiltin(S, ID);
2256 
2257   ASTContext::GetBuiltinTypeError Error;
2258   QualType R = Context.GetBuiltinType(ID, Error);
2259   if (Error) {
2260     if (!ForRedeclaration)
2261       return nullptr;
2262 
2263     // If we have a builtin without an associated type we should not emit a
2264     // warning when we were not able to find a type for it.
2265     if (Error == ASTContext::GE_Missing_type ||
2266         Context.BuiltinInfo.allowTypeMismatch(ID))
2267       return nullptr;
2268 
2269     // If we could not find a type for setjmp it is because the jmp_buf type was
2270     // not defined prior to the setjmp declaration.
2271     if (Error == ASTContext::GE_Missing_setjmp) {
2272       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2273           << Context.BuiltinInfo.getName(ID);
2274       return nullptr;
2275     }
2276 
2277     // Generally, we emit a warning that the declaration requires the
2278     // appropriate header.
2279     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2280         << getHeaderName(Context.BuiltinInfo, ID, Error)
2281         << Context.BuiltinInfo.getName(ID);
2282     return nullptr;
2283   }
2284 
2285   if (!ForRedeclaration &&
2286       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2287        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2288     Diag(Loc, diag::ext_implicit_lib_function_decl)
2289         << Context.BuiltinInfo.getName(ID) << R;
2290     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2291       Diag(Loc, diag::note_include_header_or_declare)
2292           << Header << Context.BuiltinInfo.getName(ID);
2293   }
2294 
2295   if (R.isNull())
2296     return nullptr;
2297 
2298   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2299   RegisterLocallyScopedExternCDecl(New, S);
2300 
2301   // TUScope is the translation-unit scope to insert this function into.
2302   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2303   // relate Scopes to DeclContexts, and probably eliminate CurContext
2304   // entirely, but we're not there yet.
2305   DeclContext *SavedContext = CurContext;
2306   CurContext = New->getDeclContext();
2307   PushOnScopeChains(New, TUScope);
2308   CurContext = SavedContext;
2309   return New;
2310 }
2311 
2312 /// Typedef declarations don't have linkage, but they still denote the same
2313 /// entity if their types are the same.
2314 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2315 /// isSameEntity.
2316 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2317                                                      TypedefNameDecl *Decl,
2318                                                      LookupResult &Previous) {
2319   // This is only interesting when modules are enabled.
2320   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2321     return;
2322 
2323   // Empty sets are uninteresting.
2324   if (Previous.empty())
2325     return;
2326 
2327   LookupResult::Filter Filter = Previous.makeFilter();
2328   while (Filter.hasNext()) {
2329     NamedDecl *Old = Filter.next();
2330 
2331     // Non-hidden declarations are never ignored.
2332     if (S.isVisible(Old))
2333       continue;
2334 
2335     // Declarations of the same entity are not ignored, even if they have
2336     // different linkages.
2337     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2338       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2339                                 Decl->getUnderlyingType()))
2340         continue;
2341 
2342       // If both declarations give a tag declaration a typedef name for linkage
2343       // purposes, then they declare the same entity.
2344       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2345           Decl->getAnonDeclWithTypedefName())
2346         continue;
2347     }
2348 
2349     Filter.erase();
2350   }
2351 
2352   Filter.done();
2353 }
2354 
2355 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2356   QualType OldType;
2357   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2358     OldType = OldTypedef->getUnderlyingType();
2359   else
2360     OldType = Context.getTypeDeclType(Old);
2361   QualType NewType = New->getUnderlyingType();
2362 
2363   if (NewType->isVariablyModifiedType()) {
2364     // Must not redefine a typedef with a variably-modified type.
2365     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2366     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2367       << Kind << NewType;
2368     if (Old->getLocation().isValid())
2369       notePreviousDefinition(Old, New->getLocation());
2370     New->setInvalidDecl();
2371     return true;
2372   }
2373 
2374   if (OldType != NewType &&
2375       !OldType->isDependentType() &&
2376       !NewType->isDependentType() &&
2377       !Context.hasSameType(OldType, NewType)) {
2378     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2379     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2380       << Kind << NewType << OldType;
2381     if (Old->getLocation().isValid())
2382       notePreviousDefinition(Old, New->getLocation());
2383     New->setInvalidDecl();
2384     return true;
2385   }
2386   return false;
2387 }
2388 
2389 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2390 /// same name and scope as a previous declaration 'Old'.  Figure out
2391 /// how to resolve this situation, merging decls or emitting
2392 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2393 ///
2394 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2395                                 LookupResult &OldDecls) {
2396   // If the new decl is known invalid already, don't bother doing any
2397   // merging checks.
2398   if (New->isInvalidDecl()) return;
2399 
2400   // Allow multiple definitions for ObjC built-in typedefs.
2401   // FIXME: Verify the underlying types are equivalent!
2402   if (getLangOpts().ObjC) {
2403     const IdentifierInfo *TypeID = New->getIdentifier();
2404     switch (TypeID->getLength()) {
2405     default: break;
2406     case 2:
2407       {
2408         if (!TypeID->isStr("id"))
2409           break;
2410         QualType T = New->getUnderlyingType();
2411         if (!T->isPointerType())
2412           break;
2413         if (!T->isVoidPointerType()) {
2414           QualType PT = T->castAs<PointerType>()->getPointeeType();
2415           if (!PT->isStructureType())
2416             break;
2417         }
2418         Context.setObjCIdRedefinitionType(T);
2419         // Install the built-in type for 'id', ignoring the current definition.
2420         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2421         return;
2422       }
2423     case 5:
2424       if (!TypeID->isStr("Class"))
2425         break;
2426       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2427       // Install the built-in type for 'Class', ignoring the current definition.
2428       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2429       return;
2430     case 3:
2431       if (!TypeID->isStr("SEL"))
2432         break;
2433       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2434       // Install the built-in type for 'SEL', ignoring the current definition.
2435       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2436       return;
2437     }
2438     // Fall through - the typedef name was not a builtin type.
2439   }
2440 
2441   // Verify the old decl was also a type.
2442   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2443   if (!Old) {
2444     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2445       << New->getDeclName();
2446 
2447     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2448     if (OldD->getLocation().isValid())
2449       notePreviousDefinition(OldD, New->getLocation());
2450 
2451     return New->setInvalidDecl();
2452   }
2453 
2454   // If the old declaration is invalid, just give up here.
2455   if (Old->isInvalidDecl())
2456     return New->setInvalidDecl();
2457 
2458   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2459     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2460     auto *NewTag = New->getAnonDeclWithTypedefName();
2461     NamedDecl *Hidden = nullptr;
2462     if (OldTag && NewTag &&
2463         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2464         !hasVisibleDefinition(OldTag, &Hidden)) {
2465       // There is a definition of this tag, but it is not visible. Use it
2466       // instead of our tag.
2467       New->setTypeForDecl(OldTD->getTypeForDecl());
2468       if (OldTD->isModed())
2469         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2470                                     OldTD->getUnderlyingType());
2471       else
2472         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2473 
2474       // Make the old tag definition visible.
2475       makeMergedDefinitionVisible(Hidden);
2476 
2477       // If this was an unscoped enumeration, yank all of its enumerators
2478       // out of the scope.
2479       if (isa<EnumDecl>(NewTag)) {
2480         Scope *EnumScope = getNonFieldDeclScope(S);
2481         for (auto *D : NewTag->decls()) {
2482           auto *ED = cast<EnumConstantDecl>(D);
2483           assert(EnumScope->isDeclScope(ED));
2484           EnumScope->RemoveDecl(ED);
2485           IdResolver.RemoveDecl(ED);
2486           ED->getLexicalDeclContext()->removeDecl(ED);
2487         }
2488       }
2489     }
2490   }
2491 
2492   // If the typedef types are not identical, reject them in all languages and
2493   // with any extensions enabled.
2494   if (isIncompatibleTypedef(Old, New))
2495     return;
2496 
2497   // The types match.  Link up the redeclaration chain and merge attributes if
2498   // the old declaration was a typedef.
2499   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2500     New->setPreviousDecl(Typedef);
2501     mergeDeclAttributes(New, Old);
2502   }
2503 
2504   if (getLangOpts().MicrosoftExt)
2505     return;
2506 
2507   if (getLangOpts().CPlusPlus) {
2508     // C++ [dcl.typedef]p2:
2509     //   In a given non-class scope, a typedef specifier can be used to
2510     //   redefine the name of any type declared in that scope to refer
2511     //   to the type to which it already refers.
2512     if (!isa<CXXRecordDecl>(CurContext))
2513       return;
2514 
2515     // C++0x [dcl.typedef]p4:
2516     //   In a given class scope, a typedef specifier can be used to redefine
2517     //   any class-name declared in that scope that is not also a typedef-name
2518     //   to refer to the type to which it already refers.
2519     //
2520     // This wording came in via DR424, which was a correction to the
2521     // wording in DR56, which accidentally banned code like:
2522     //
2523     //   struct S {
2524     //     typedef struct A { } A;
2525     //   };
2526     //
2527     // in the C++03 standard. We implement the C++0x semantics, which
2528     // allow the above but disallow
2529     //
2530     //   struct S {
2531     //     typedef int I;
2532     //     typedef int I;
2533     //   };
2534     //
2535     // since that was the intent of DR56.
2536     if (!isa<TypedefNameDecl>(Old))
2537       return;
2538 
2539     Diag(New->getLocation(), diag::err_redefinition)
2540       << New->getDeclName();
2541     notePreviousDefinition(Old, New->getLocation());
2542     return New->setInvalidDecl();
2543   }
2544 
2545   // Modules always permit redefinition of typedefs, as does C11.
2546   if (getLangOpts().Modules || getLangOpts().C11)
2547     return;
2548 
2549   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2550   // is normally mapped to an error, but can be controlled with
2551   // -Wtypedef-redefinition.  If either the original or the redefinition is
2552   // in a system header, don't emit this for compatibility with GCC.
2553   if (getDiagnostics().getSuppressSystemWarnings() &&
2554       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2555       (Old->isImplicit() ||
2556        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2557        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2558     return;
2559 
2560   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2561     << New->getDeclName();
2562   notePreviousDefinition(Old, New->getLocation());
2563 }
2564 
2565 /// DeclhasAttr - returns true if decl Declaration already has the target
2566 /// attribute.
2567 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2568   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2569   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2570   for (const auto *i : D->attrs())
2571     if (i->getKind() == A->getKind()) {
2572       if (Ann) {
2573         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2574           return true;
2575         continue;
2576       }
2577       // FIXME: Don't hardcode this check
2578       if (OA && isa<OwnershipAttr>(i))
2579         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2580       return true;
2581     }
2582 
2583   return false;
2584 }
2585 
2586 static bool isAttributeTargetADefinition(Decl *D) {
2587   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2588     return VD->isThisDeclarationADefinition();
2589   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2590     return TD->isCompleteDefinition() || TD->isBeingDefined();
2591   return true;
2592 }
2593 
2594 /// Merge alignment attributes from \p Old to \p New, taking into account the
2595 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2596 ///
2597 /// \return \c true if any attributes were added to \p New.
2598 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2599   // Look for alignas attributes on Old, and pick out whichever attribute
2600   // specifies the strictest alignment requirement.
2601   AlignedAttr *OldAlignasAttr = nullptr;
2602   AlignedAttr *OldStrictestAlignAttr = nullptr;
2603   unsigned OldAlign = 0;
2604   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2605     // FIXME: We have no way of representing inherited dependent alignments
2606     // in a case like:
2607     //   template<int A, int B> struct alignas(A) X;
2608     //   template<int A, int B> struct alignas(B) X {};
2609     // For now, we just ignore any alignas attributes which are not on the
2610     // definition in such a case.
2611     if (I->isAlignmentDependent())
2612       return false;
2613 
2614     if (I->isAlignas())
2615       OldAlignasAttr = I;
2616 
2617     unsigned Align = I->getAlignment(S.Context);
2618     if (Align > OldAlign) {
2619       OldAlign = Align;
2620       OldStrictestAlignAttr = I;
2621     }
2622   }
2623 
2624   // Look for alignas attributes on New.
2625   AlignedAttr *NewAlignasAttr = nullptr;
2626   unsigned NewAlign = 0;
2627   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2628     if (I->isAlignmentDependent())
2629       return false;
2630 
2631     if (I->isAlignas())
2632       NewAlignasAttr = I;
2633 
2634     unsigned Align = I->getAlignment(S.Context);
2635     if (Align > NewAlign)
2636       NewAlign = Align;
2637   }
2638 
2639   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2640     // Both declarations have 'alignas' attributes. We require them to match.
2641     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2642     // fall short. (If two declarations both have alignas, they must both match
2643     // every definition, and so must match each other if there is a definition.)
2644 
2645     // If either declaration only contains 'alignas(0)' specifiers, then it
2646     // specifies the natural alignment for the type.
2647     if (OldAlign == 0 || NewAlign == 0) {
2648       QualType Ty;
2649       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2650         Ty = VD->getType();
2651       else
2652         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2653 
2654       if (OldAlign == 0)
2655         OldAlign = S.Context.getTypeAlign(Ty);
2656       if (NewAlign == 0)
2657         NewAlign = S.Context.getTypeAlign(Ty);
2658     }
2659 
2660     if (OldAlign != NewAlign) {
2661       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2662         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2663         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2664       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2665     }
2666   }
2667 
2668   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2669     // C++11 [dcl.align]p6:
2670     //   if any declaration of an entity has an alignment-specifier,
2671     //   every defining declaration of that entity shall specify an
2672     //   equivalent alignment.
2673     // C11 6.7.5/7:
2674     //   If the definition of an object does not have an alignment
2675     //   specifier, any other declaration of that object shall also
2676     //   have no alignment specifier.
2677     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2678       << OldAlignasAttr;
2679     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2680       << OldAlignasAttr;
2681   }
2682 
2683   bool AnyAdded = false;
2684 
2685   // Ensure we have an attribute representing the strictest alignment.
2686   if (OldAlign > NewAlign) {
2687     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2688     Clone->setInherited(true);
2689     New->addAttr(Clone);
2690     AnyAdded = true;
2691   }
2692 
2693   // Ensure we have an alignas attribute if the old declaration had one.
2694   if (OldAlignasAttr && !NewAlignasAttr &&
2695       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2696     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2697     Clone->setInherited(true);
2698     New->addAttr(Clone);
2699     AnyAdded = true;
2700   }
2701 
2702   return AnyAdded;
2703 }
2704 
2705 #define WANT_DECL_MERGE_LOGIC
2706 #include "clang/Sema/AttrParsedAttrImpl.inc"
2707 #undef WANT_DECL_MERGE_LOGIC
2708 
2709 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2710                                const InheritableAttr *Attr,
2711                                Sema::AvailabilityMergeKind AMK) {
2712   // Diagnose any mutual exclusions between the attribute that we want to add
2713   // and attributes that already exist on the declaration.
2714   if (!DiagnoseMutualExclusions(S, D, Attr))
2715     return false;
2716 
2717   // This function copies an attribute Attr from a previous declaration to the
2718   // new declaration D if the new declaration doesn't itself have that attribute
2719   // yet or if that attribute allows duplicates.
2720   // If you're adding a new attribute that requires logic different from
2721   // "use explicit attribute on decl if present, else use attribute from
2722   // previous decl", for example if the attribute needs to be consistent
2723   // between redeclarations, you need to call a custom merge function here.
2724   InheritableAttr *NewAttr = nullptr;
2725   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2726     NewAttr = S.mergeAvailabilityAttr(
2727         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2728         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2729         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2730         AA->getPriority());
2731   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2732     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2733   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2734     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2735   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2736     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2737   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2738     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2739   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2740     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2741   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2742     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2743                                 FA->getFirstArg());
2744   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2745     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2746   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2747     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2748   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2749     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2750                                        IA->getInheritanceModel());
2751   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2752     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2753                                       &S.Context.Idents.get(AA->getSpelling()));
2754   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2755            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2756             isa<CUDAGlobalAttr>(Attr))) {
2757     // CUDA target attributes are part of function signature for
2758     // overloading purposes and must not be merged.
2759     return false;
2760   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2761     NewAttr = S.mergeMinSizeAttr(D, *MA);
2762   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2763     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2764   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2765     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2766   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2767     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2768   else if (isa<AlignedAttr>(Attr))
2769     // AlignedAttrs are handled separately, because we need to handle all
2770     // such attributes on a declaration at the same time.
2771     NewAttr = nullptr;
2772   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2773            (AMK == Sema::AMK_Override ||
2774             AMK == Sema::AMK_ProtocolImplementation ||
2775             AMK == Sema::AMK_OptionalProtocolImplementation))
2776     NewAttr = nullptr;
2777   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2778     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2779   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2780     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2781   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2782     NewAttr = S.mergeImportNameAttr(D, *INA);
2783   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2784     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2785   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2786     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2787   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2788     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2789   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2790     NewAttr =
2791         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2792   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2793     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2794 
2795   if (NewAttr) {
2796     NewAttr->setInherited(true);
2797     D->addAttr(NewAttr);
2798     if (isa<MSInheritanceAttr>(NewAttr))
2799       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2800     return true;
2801   }
2802 
2803   return false;
2804 }
2805 
2806 static const NamedDecl *getDefinition(const Decl *D) {
2807   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2808     return TD->getDefinition();
2809   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2810     const VarDecl *Def = VD->getDefinition();
2811     if (Def)
2812       return Def;
2813     return VD->getActingDefinition();
2814   }
2815   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2816     const FunctionDecl *Def = nullptr;
2817     if (FD->isDefined(Def, true))
2818       return Def;
2819   }
2820   return nullptr;
2821 }
2822 
2823 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2824   for (const auto *Attribute : D->attrs())
2825     if (Attribute->getKind() == Kind)
2826       return true;
2827   return false;
2828 }
2829 
2830 /// checkNewAttributesAfterDef - If we already have a definition, check that
2831 /// there are no new attributes in this declaration.
2832 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2833   if (!New->hasAttrs())
2834     return;
2835 
2836   const NamedDecl *Def = getDefinition(Old);
2837   if (!Def || Def == New)
2838     return;
2839 
2840   AttrVec &NewAttributes = New->getAttrs();
2841   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2842     const Attr *NewAttribute = NewAttributes[I];
2843 
2844     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2845       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2846         Sema::SkipBodyInfo SkipBody;
2847         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2848 
2849         // If we're skipping this definition, drop the "alias" attribute.
2850         if (SkipBody.ShouldSkip) {
2851           NewAttributes.erase(NewAttributes.begin() + I);
2852           --E;
2853           continue;
2854         }
2855       } else {
2856         VarDecl *VD = cast<VarDecl>(New);
2857         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2858                                 VarDecl::TentativeDefinition
2859                             ? diag::err_alias_after_tentative
2860                             : diag::err_redefinition;
2861         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2862         if (Diag == diag::err_redefinition)
2863           S.notePreviousDefinition(Def, VD->getLocation());
2864         else
2865           S.Diag(Def->getLocation(), diag::note_previous_definition);
2866         VD->setInvalidDecl();
2867       }
2868       ++I;
2869       continue;
2870     }
2871 
2872     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2873       // Tentative definitions are only interesting for the alias check above.
2874       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2875         ++I;
2876         continue;
2877       }
2878     }
2879 
2880     if (hasAttribute(Def, NewAttribute->getKind())) {
2881       ++I;
2882       continue; // regular attr merging will take care of validating this.
2883     }
2884 
2885     if (isa<C11NoReturnAttr>(NewAttribute)) {
2886       // C's _Noreturn is allowed to be added to a function after it is defined.
2887       ++I;
2888       continue;
2889     } else if (isa<UuidAttr>(NewAttribute)) {
2890       // msvc will allow a subsequent definition to add an uuid to a class
2891       ++I;
2892       continue;
2893     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2894       if (AA->isAlignas()) {
2895         // C++11 [dcl.align]p6:
2896         //   if any declaration of an entity has an alignment-specifier,
2897         //   every defining declaration of that entity shall specify an
2898         //   equivalent alignment.
2899         // C11 6.7.5/7:
2900         //   If the definition of an object does not have an alignment
2901         //   specifier, any other declaration of that object shall also
2902         //   have no alignment specifier.
2903         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2904           << AA;
2905         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2906           << AA;
2907         NewAttributes.erase(NewAttributes.begin() + I);
2908         --E;
2909         continue;
2910       }
2911     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2912       // If there is a C definition followed by a redeclaration with this
2913       // attribute then there are two different definitions. In C++, prefer the
2914       // standard diagnostics.
2915       if (!S.getLangOpts().CPlusPlus) {
2916         S.Diag(NewAttribute->getLocation(),
2917                diag::err_loader_uninitialized_redeclaration);
2918         S.Diag(Def->getLocation(), diag::note_previous_definition);
2919         NewAttributes.erase(NewAttributes.begin() + I);
2920         --E;
2921         continue;
2922       }
2923     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2924                cast<VarDecl>(New)->isInline() &&
2925                !cast<VarDecl>(New)->isInlineSpecified()) {
2926       // Don't warn about applying selectany to implicitly inline variables.
2927       // Older compilers and language modes would require the use of selectany
2928       // to make such variables inline, and it would have no effect if we
2929       // honored it.
2930       ++I;
2931       continue;
2932     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2933       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2934       // declarations after defintions.
2935       ++I;
2936       continue;
2937     }
2938 
2939     S.Diag(NewAttribute->getLocation(),
2940            diag::warn_attribute_precede_definition);
2941     S.Diag(Def->getLocation(), diag::note_previous_definition);
2942     NewAttributes.erase(NewAttributes.begin() + I);
2943     --E;
2944   }
2945 }
2946 
2947 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2948                                      const ConstInitAttr *CIAttr,
2949                                      bool AttrBeforeInit) {
2950   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2951 
2952   // Figure out a good way to write this specifier on the old declaration.
2953   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2954   // enough of the attribute list spelling information to extract that without
2955   // heroics.
2956   std::string SuitableSpelling;
2957   if (S.getLangOpts().CPlusPlus20)
2958     SuitableSpelling = std::string(
2959         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2960   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2961     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2962         InsertLoc, {tok::l_square, tok::l_square,
2963                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2964                     S.PP.getIdentifierInfo("require_constant_initialization"),
2965                     tok::r_square, tok::r_square}));
2966   if (SuitableSpelling.empty())
2967     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2968         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2969                     S.PP.getIdentifierInfo("require_constant_initialization"),
2970                     tok::r_paren, tok::r_paren}));
2971   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2972     SuitableSpelling = "constinit";
2973   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2974     SuitableSpelling = "[[clang::require_constant_initialization]]";
2975   if (SuitableSpelling.empty())
2976     SuitableSpelling = "__attribute__((require_constant_initialization))";
2977   SuitableSpelling += " ";
2978 
2979   if (AttrBeforeInit) {
2980     // extern constinit int a;
2981     // int a = 0; // error (missing 'constinit'), accepted as extension
2982     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2983     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2984         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2985     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2986   } else {
2987     // int a = 0;
2988     // constinit extern int a; // error (missing 'constinit')
2989     S.Diag(CIAttr->getLocation(),
2990            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2991                                  : diag::warn_require_const_init_added_too_late)
2992         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2993     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2994         << CIAttr->isConstinit()
2995         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2996   }
2997 }
2998 
2999 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3000 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3001                                AvailabilityMergeKind AMK) {
3002   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3003     UsedAttr *NewAttr = OldAttr->clone(Context);
3004     NewAttr->setInherited(true);
3005     New->addAttr(NewAttr);
3006   }
3007   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3008     RetainAttr *NewAttr = OldAttr->clone(Context);
3009     NewAttr->setInherited(true);
3010     New->addAttr(NewAttr);
3011   }
3012 
3013   if (!Old->hasAttrs() && !New->hasAttrs())
3014     return;
3015 
3016   // [dcl.constinit]p1:
3017   //   If the [constinit] specifier is applied to any declaration of a
3018   //   variable, it shall be applied to the initializing declaration.
3019   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3020   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3021   if (bool(OldConstInit) != bool(NewConstInit)) {
3022     const auto *OldVD = cast<VarDecl>(Old);
3023     auto *NewVD = cast<VarDecl>(New);
3024 
3025     // Find the initializing declaration. Note that we might not have linked
3026     // the new declaration into the redeclaration chain yet.
3027     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3028     if (!InitDecl &&
3029         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3030       InitDecl = NewVD;
3031 
3032     if (InitDecl == NewVD) {
3033       // This is the initializing declaration. If it would inherit 'constinit',
3034       // that's ill-formed. (Note that we do not apply this to the attribute
3035       // form).
3036       if (OldConstInit && OldConstInit->isConstinit())
3037         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3038                                  /*AttrBeforeInit=*/true);
3039     } else if (NewConstInit) {
3040       // This is the first time we've been told that this declaration should
3041       // have a constant initializer. If we already saw the initializing
3042       // declaration, this is too late.
3043       if (InitDecl && InitDecl != NewVD) {
3044         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3045                                  /*AttrBeforeInit=*/false);
3046         NewVD->dropAttr<ConstInitAttr>();
3047       }
3048     }
3049   }
3050 
3051   // Attributes declared post-definition are currently ignored.
3052   checkNewAttributesAfterDef(*this, New, Old);
3053 
3054   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3055     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3056       if (!OldA->isEquivalent(NewA)) {
3057         // This redeclaration changes __asm__ label.
3058         Diag(New->getLocation(), diag::err_different_asm_label);
3059         Diag(OldA->getLocation(), diag::note_previous_declaration);
3060       }
3061     } else if (Old->isUsed()) {
3062       // This redeclaration adds an __asm__ label to a declaration that has
3063       // already been ODR-used.
3064       Diag(New->getLocation(), diag::err_late_asm_label_name)
3065         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3066     }
3067   }
3068 
3069   // Re-declaration cannot add abi_tag's.
3070   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3071     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3072       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3073         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3074           Diag(NewAbiTagAttr->getLocation(),
3075                diag::err_new_abi_tag_on_redeclaration)
3076               << NewTag;
3077           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3078         }
3079       }
3080     } else {
3081       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3082       Diag(Old->getLocation(), diag::note_previous_declaration);
3083     }
3084   }
3085 
3086   // This redeclaration adds a section attribute.
3087   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3088     if (auto *VD = dyn_cast<VarDecl>(New)) {
3089       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3090         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3091         Diag(Old->getLocation(), diag::note_previous_declaration);
3092       }
3093     }
3094   }
3095 
3096   // Redeclaration adds code-seg attribute.
3097   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3098   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3099       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3100     Diag(New->getLocation(), diag::warn_mismatched_section)
3101          << 0 /*codeseg*/;
3102     Diag(Old->getLocation(), diag::note_previous_declaration);
3103   }
3104 
3105   if (!Old->hasAttrs())
3106     return;
3107 
3108   bool foundAny = New->hasAttrs();
3109 
3110   // Ensure that any moving of objects within the allocated map is done before
3111   // we process them.
3112   if (!foundAny) New->setAttrs(AttrVec());
3113 
3114   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3115     // Ignore deprecated/unavailable/availability attributes if requested.
3116     AvailabilityMergeKind LocalAMK = AMK_None;
3117     if (isa<DeprecatedAttr>(I) ||
3118         isa<UnavailableAttr>(I) ||
3119         isa<AvailabilityAttr>(I)) {
3120       switch (AMK) {
3121       case AMK_None:
3122         continue;
3123 
3124       case AMK_Redeclaration:
3125       case AMK_Override:
3126       case AMK_ProtocolImplementation:
3127       case AMK_OptionalProtocolImplementation:
3128         LocalAMK = AMK;
3129         break;
3130       }
3131     }
3132 
3133     // Already handled.
3134     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3135       continue;
3136 
3137     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3138       foundAny = true;
3139   }
3140 
3141   if (mergeAlignedAttrs(*this, New, Old))
3142     foundAny = true;
3143 
3144   if (!foundAny) New->dropAttrs();
3145 }
3146 
3147 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3148 /// to the new one.
3149 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3150                                      const ParmVarDecl *oldDecl,
3151                                      Sema &S) {
3152   // C++11 [dcl.attr.depend]p2:
3153   //   The first declaration of a function shall specify the
3154   //   carries_dependency attribute for its declarator-id if any declaration
3155   //   of the function specifies the carries_dependency attribute.
3156   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3157   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3158     S.Diag(CDA->getLocation(),
3159            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3160     // Find the first declaration of the parameter.
3161     // FIXME: Should we build redeclaration chains for function parameters?
3162     const FunctionDecl *FirstFD =
3163       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3164     const ParmVarDecl *FirstVD =
3165       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3166     S.Diag(FirstVD->getLocation(),
3167            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3168   }
3169 
3170   if (!oldDecl->hasAttrs())
3171     return;
3172 
3173   bool foundAny = newDecl->hasAttrs();
3174 
3175   // Ensure that any moving of objects within the allocated map is
3176   // done before we process them.
3177   if (!foundAny) newDecl->setAttrs(AttrVec());
3178 
3179   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3180     if (!DeclHasAttr(newDecl, I)) {
3181       InheritableAttr *newAttr =
3182         cast<InheritableParamAttr>(I->clone(S.Context));
3183       newAttr->setInherited(true);
3184       newDecl->addAttr(newAttr);
3185       foundAny = true;
3186     }
3187   }
3188 
3189   if (!foundAny) newDecl->dropAttrs();
3190 }
3191 
3192 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3193                                 const ParmVarDecl *OldParam,
3194                                 Sema &S) {
3195   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3196     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3197       if (*Oldnullability != *Newnullability) {
3198         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3199           << DiagNullabilityKind(
3200                *Newnullability,
3201                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3202                 != 0))
3203           << DiagNullabilityKind(
3204                *Oldnullability,
3205                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3206                 != 0));
3207         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3208       }
3209     } else {
3210       QualType NewT = NewParam->getType();
3211       NewT = S.Context.getAttributedType(
3212                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3213                          NewT, NewT);
3214       NewParam->setType(NewT);
3215     }
3216   }
3217 }
3218 
3219 namespace {
3220 
3221 /// Used in MergeFunctionDecl to keep track of function parameters in
3222 /// C.
3223 struct GNUCompatibleParamWarning {
3224   ParmVarDecl *OldParm;
3225   ParmVarDecl *NewParm;
3226   QualType PromotedType;
3227 };
3228 
3229 } // end anonymous namespace
3230 
3231 // Determine whether the previous declaration was a definition, implicit
3232 // declaration, or a declaration.
3233 template <typename T>
3234 static std::pair<diag::kind, SourceLocation>
3235 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3236   diag::kind PrevDiag;
3237   SourceLocation OldLocation = Old->getLocation();
3238   if (Old->isThisDeclarationADefinition())
3239     PrevDiag = diag::note_previous_definition;
3240   else if (Old->isImplicit()) {
3241     PrevDiag = diag::note_previous_implicit_declaration;
3242     if (OldLocation.isInvalid())
3243       OldLocation = New->getLocation();
3244   } else
3245     PrevDiag = diag::note_previous_declaration;
3246   return std::make_pair(PrevDiag, OldLocation);
3247 }
3248 
3249 /// canRedefineFunction - checks if a function can be redefined. Currently,
3250 /// only extern inline functions can be redefined, and even then only in
3251 /// GNU89 mode.
3252 static bool canRedefineFunction(const FunctionDecl *FD,
3253                                 const LangOptions& LangOpts) {
3254   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3255           !LangOpts.CPlusPlus &&
3256           FD->isInlineSpecified() &&
3257           FD->getStorageClass() == SC_Extern);
3258 }
3259 
3260 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3261   const AttributedType *AT = T->getAs<AttributedType>();
3262   while (AT && !AT->isCallingConv())
3263     AT = AT->getModifiedType()->getAs<AttributedType>();
3264   return AT;
3265 }
3266 
3267 template <typename T>
3268 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3269   const DeclContext *DC = Old->getDeclContext();
3270   if (DC->isRecord())
3271     return false;
3272 
3273   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3274   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3275     return true;
3276   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3277     return true;
3278   return false;
3279 }
3280 
3281 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3282 static bool isExternC(VarTemplateDecl *) { return false; }
3283 static bool isExternC(FunctionTemplateDecl *) { return false; }
3284 
3285 /// Check whether a redeclaration of an entity introduced by a
3286 /// using-declaration is valid, given that we know it's not an overload
3287 /// (nor a hidden tag declaration).
3288 template<typename ExpectedDecl>
3289 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3290                                    ExpectedDecl *New) {
3291   // C++11 [basic.scope.declarative]p4:
3292   //   Given a set of declarations in a single declarative region, each of
3293   //   which specifies the same unqualified name,
3294   //   -- they shall all refer to the same entity, or all refer to functions
3295   //      and function templates; or
3296   //   -- exactly one declaration shall declare a class name or enumeration
3297   //      name that is not a typedef name and the other declarations shall all
3298   //      refer to the same variable or enumerator, or all refer to functions
3299   //      and function templates; in this case the class name or enumeration
3300   //      name is hidden (3.3.10).
3301 
3302   // C++11 [namespace.udecl]p14:
3303   //   If a function declaration in namespace scope or block scope has the
3304   //   same name and the same parameter-type-list as a function introduced
3305   //   by a using-declaration, and the declarations do not declare the same
3306   //   function, the program is ill-formed.
3307 
3308   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3309   if (Old &&
3310       !Old->getDeclContext()->getRedeclContext()->Equals(
3311           New->getDeclContext()->getRedeclContext()) &&
3312       !(isExternC(Old) && isExternC(New)))
3313     Old = nullptr;
3314 
3315   if (!Old) {
3316     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3317     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3318     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3319     return true;
3320   }
3321   return false;
3322 }
3323 
3324 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3325                                             const FunctionDecl *B) {
3326   assert(A->getNumParams() == B->getNumParams());
3327 
3328   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3329     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3330     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3331     if (AttrA == AttrB)
3332       return true;
3333     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3334            AttrA->isDynamic() == AttrB->isDynamic();
3335   };
3336 
3337   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3338 }
3339 
3340 /// If necessary, adjust the semantic declaration context for a qualified
3341 /// declaration to name the correct inline namespace within the qualifier.
3342 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3343                                                DeclaratorDecl *OldD) {
3344   // The only case where we need to update the DeclContext is when
3345   // redeclaration lookup for a qualified name finds a declaration
3346   // in an inline namespace within the context named by the qualifier:
3347   //
3348   //   inline namespace N { int f(); }
3349   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3350   //
3351   // For unqualified declarations, the semantic context *can* change
3352   // along the redeclaration chain (for local extern declarations,
3353   // extern "C" declarations, and friend declarations in particular).
3354   if (!NewD->getQualifier())
3355     return;
3356 
3357   // NewD is probably already in the right context.
3358   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3359   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3360   if (NamedDC->Equals(SemaDC))
3361     return;
3362 
3363   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3364           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3365          "unexpected context for redeclaration");
3366 
3367   auto *LexDC = NewD->getLexicalDeclContext();
3368   auto FixSemaDC = [=](NamedDecl *D) {
3369     if (!D)
3370       return;
3371     D->setDeclContext(SemaDC);
3372     D->setLexicalDeclContext(LexDC);
3373   };
3374 
3375   FixSemaDC(NewD);
3376   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3377     FixSemaDC(FD->getDescribedFunctionTemplate());
3378   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3379     FixSemaDC(VD->getDescribedVarTemplate());
3380 }
3381 
3382 /// MergeFunctionDecl - We just parsed a function 'New' from
3383 /// declarator D which has the same name and scope as a previous
3384 /// declaration 'Old'.  Figure out how to resolve this situation,
3385 /// merging decls or emitting diagnostics as appropriate.
3386 ///
3387 /// In C++, New and Old must be declarations that are not
3388 /// overloaded. Use IsOverload to determine whether New and Old are
3389 /// overloaded, and to select the Old declaration that New should be
3390 /// merged with.
3391 ///
3392 /// Returns true if there was an error, false otherwise.
3393 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3394                              Scope *S, bool MergeTypeWithOld) {
3395   // Verify the old decl was also a function.
3396   FunctionDecl *Old = OldD->getAsFunction();
3397   if (!Old) {
3398     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3399       if (New->getFriendObjectKind()) {
3400         Diag(New->getLocation(), diag::err_using_decl_friend);
3401         Diag(Shadow->getTargetDecl()->getLocation(),
3402              diag::note_using_decl_target);
3403         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3404             << 0;
3405         return true;
3406       }
3407 
3408       // Check whether the two declarations might declare the same function or
3409       // function template.
3410       if (FunctionTemplateDecl *NewTemplate =
3411               New->getDescribedFunctionTemplate()) {
3412         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3413                                                          NewTemplate))
3414           return true;
3415         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3416                          ->getAsFunction();
3417       } else {
3418         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3419           return true;
3420         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3421       }
3422     } else {
3423       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3424         << New->getDeclName();
3425       notePreviousDefinition(OldD, New->getLocation());
3426       return true;
3427     }
3428   }
3429 
3430   // If the old declaration was found in an inline namespace and the new
3431   // declaration was qualified, update the DeclContext to match.
3432   adjustDeclContextForDeclaratorDecl(New, Old);
3433 
3434   // If the old declaration is invalid, just give up here.
3435   if (Old->isInvalidDecl())
3436     return true;
3437 
3438   // Disallow redeclaration of some builtins.
3439   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3440     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3441     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3442         << Old << Old->getType();
3443     return true;
3444   }
3445 
3446   diag::kind PrevDiag;
3447   SourceLocation OldLocation;
3448   std::tie(PrevDiag, OldLocation) =
3449       getNoteDiagForInvalidRedeclaration(Old, New);
3450 
3451   // Don't complain about this if we're in GNU89 mode and the old function
3452   // is an extern inline function.
3453   // Don't complain about specializations. They are not supposed to have
3454   // storage classes.
3455   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3456       New->getStorageClass() == SC_Static &&
3457       Old->hasExternalFormalLinkage() &&
3458       !New->getTemplateSpecializationInfo() &&
3459       !canRedefineFunction(Old, getLangOpts())) {
3460     if (getLangOpts().MicrosoftExt) {
3461       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3462       Diag(OldLocation, PrevDiag);
3463     } else {
3464       Diag(New->getLocation(), diag::err_static_non_static) << New;
3465       Diag(OldLocation, PrevDiag);
3466       return true;
3467     }
3468   }
3469 
3470   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3471     if (!Old->hasAttr<InternalLinkageAttr>()) {
3472       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3473           << ILA;
3474       Diag(Old->getLocation(), diag::note_previous_declaration);
3475       New->dropAttr<InternalLinkageAttr>();
3476     }
3477 
3478   if (auto *EA = New->getAttr<ErrorAttr>()) {
3479     if (!Old->hasAttr<ErrorAttr>()) {
3480       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3481       Diag(Old->getLocation(), diag::note_previous_declaration);
3482       New->dropAttr<ErrorAttr>();
3483     }
3484   }
3485 
3486   if (CheckRedeclarationInModule(New, Old))
3487     return true;
3488 
3489   if (!getLangOpts().CPlusPlus) {
3490     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3491     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3492       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3493         << New << OldOvl;
3494 
3495       // Try our best to find a decl that actually has the overloadable
3496       // attribute for the note. In most cases (e.g. programs with only one
3497       // broken declaration/definition), this won't matter.
3498       //
3499       // FIXME: We could do this if we juggled some extra state in
3500       // OverloadableAttr, rather than just removing it.
3501       const Decl *DiagOld = Old;
3502       if (OldOvl) {
3503         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3504           const auto *A = D->getAttr<OverloadableAttr>();
3505           return A && !A->isImplicit();
3506         });
3507         // If we've implicitly added *all* of the overloadable attrs to this
3508         // chain, emitting a "previous redecl" note is pointless.
3509         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3510       }
3511 
3512       if (DiagOld)
3513         Diag(DiagOld->getLocation(),
3514              diag::note_attribute_overloadable_prev_overload)
3515           << OldOvl;
3516 
3517       if (OldOvl)
3518         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3519       else
3520         New->dropAttr<OverloadableAttr>();
3521     }
3522   }
3523 
3524   // If a function is first declared with a calling convention, but is later
3525   // declared or defined without one, all following decls assume the calling
3526   // convention of the first.
3527   //
3528   // It's OK if a function is first declared without a calling convention,
3529   // but is later declared or defined with the default calling convention.
3530   //
3531   // To test if either decl has an explicit calling convention, we look for
3532   // AttributedType sugar nodes on the type as written.  If they are missing or
3533   // were canonicalized away, we assume the calling convention was implicit.
3534   //
3535   // Note also that we DO NOT return at this point, because we still have
3536   // other tests to run.
3537   QualType OldQType = Context.getCanonicalType(Old->getType());
3538   QualType NewQType = Context.getCanonicalType(New->getType());
3539   const FunctionType *OldType = cast<FunctionType>(OldQType);
3540   const FunctionType *NewType = cast<FunctionType>(NewQType);
3541   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3542   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3543   bool RequiresAdjustment = false;
3544 
3545   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3546     FunctionDecl *First = Old->getFirstDecl();
3547     const FunctionType *FT =
3548         First->getType().getCanonicalType()->castAs<FunctionType>();
3549     FunctionType::ExtInfo FI = FT->getExtInfo();
3550     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3551     if (!NewCCExplicit) {
3552       // Inherit the CC from the previous declaration if it was specified
3553       // there but not here.
3554       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3555       RequiresAdjustment = true;
3556     } else if (Old->getBuiltinID()) {
3557       // Builtin attribute isn't propagated to the new one yet at this point,
3558       // so we check if the old one is a builtin.
3559 
3560       // Calling Conventions on a Builtin aren't really useful and setting a
3561       // default calling convention and cdecl'ing some builtin redeclarations is
3562       // common, so warn and ignore the calling convention on the redeclaration.
3563       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3564           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3565           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3566       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3567       RequiresAdjustment = true;
3568     } else {
3569       // Calling conventions aren't compatible, so complain.
3570       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3571       Diag(New->getLocation(), diag::err_cconv_change)
3572         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3573         << !FirstCCExplicit
3574         << (!FirstCCExplicit ? "" :
3575             FunctionType::getNameForCallConv(FI.getCC()));
3576 
3577       // Put the note on the first decl, since it is the one that matters.
3578       Diag(First->getLocation(), diag::note_previous_declaration);
3579       return true;
3580     }
3581   }
3582 
3583   // FIXME: diagnose the other way around?
3584   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3585     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3586     RequiresAdjustment = true;
3587   }
3588 
3589   // Merge regparm attribute.
3590   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3591       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3592     if (NewTypeInfo.getHasRegParm()) {
3593       Diag(New->getLocation(), diag::err_regparm_mismatch)
3594         << NewType->getRegParmType()
3595         << OldType->getRegParmType();
3596       Diag(OldLocation, diag::note_previous_declaration);
3597       return true;
3598     }
3599 
3600     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3601     RequiresAdjustment = true;
3602   }
3603 
3604   // Merge ns_returns_retained attribute.
3605   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3606     if (NewTypeInfo.getProducesResult()) {
3607       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3608           << "'ns_returns_retained'";
3609       Diag(OldLocation, diag::note_previous_declaration);
3610       return true;
3611     }
3612 
3613     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3614     RequiresAdjustment = true;
3615   }
3616 
3617   if (OldTypeInfo.getNoCallerSavedRegs() !=
3618       NewTypeInfo.getNoCallerSavedRegs()) {
3619     if (NewTypeInfo.getNoCallerSavedRegs()) {
3620       AnyX86NoCallerSavedRegistersAttr *Attr =
3621         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3622       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3623       Diag(OldLocation, diag::note_previous_declaration);
3624       return true;
3625     }
3626 
3627     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3628     RequiresAdjustment = true;
3629   }
3630 
3631   if (RequiresAdjustment) {
3632     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3633     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3634     New->setType(QualType(AdjustedType, 0));
3635     NewQType = Context.getCanonicalType(New->getType());
3636   }
3637 
3638   // If this redeclaration makes the function inline, we may need to add it to
3639   // UndefinedButUsed.
3640   if (!Old->isInlined() && New->isInlined() &&
3641       !New->hasAttr<GNUInlineAttr>() &&
3642       !getLangOpts().GNUInline &&
3643       Old->isUsed(false) &&
3644       !Old->isDefined() && !New->isThisDeclarationADefinition())
3645     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3646                                            SourceLocation()));
3647 
3648   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3649   // about it.
3650   if (New->hasAttr<GNUInlineAttr>() &&
3651       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3652     UndefinedButUsed.erase(Old->getCanonicalDecl());
3653   }
3654 
3655   // If pass_object_size params don't match up perfectly, this isn't a valid
3656   // redeclaration.
3657   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3658       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3659     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3660         << New->getDeclName();
3661     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3662     return true;
3663   }
3664 
3665   if (getLangOpts().CPlusPlus) {
3666     // C++1z [over.load]p2
3667     //   Certain function declarations cannot be overloaded:
3668     //     -- Function declarations that differ only in the return type,
3669     //        the exception specification, or both cannot be overloaded.
3670 
3671     // Check the exception specifications match. This may recompute the type of
3672     // both Old and New if it resolved exception specifications, so grab the
3673     // types again after this. Because this updates the type, we do this before
3674     // any of the other checks below, which may update the "de facto" NewQType
3675     // but do not necessarily update the type of New.
3676     if (CheckEquivalentExceptionSpec(Old, New))
3677       return true;
3678     OldQType = Context.getCanonicalType(Old->getType());
3679     NewQType = Context.getCanonicalType(New->getType());
3680 
3681     // Go back to the type source info to compare the declared return types,
3682     // per C++1y [dcl.type.auto]p13:
3683     //   Redeclarations or specializations of a function or function template
3684     //   with a declared return type that uses a placeholder type shall also
3685     //   use that placeholder, not a deduced type.
3686     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3687     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3688     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3689         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3690                                        OldDeclaredReturnType)) {
3691       QualType ResQT;
3692       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3693           OldDeclaredReturnType->isObjCObjectPointerType())
3694         // FIXME: This does the wrong thing for a deduced return type.
3695         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3696       if (ResQT.isNull()) {
3697         if (New->isCXXClassMember() && New->isOutOfLine())
3698           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3699               << New << New->getReturnTypeSourceRange();
3700         else
3701           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3702               << New->getReturnTypeSourceRange();
3703         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3704                                     << Old->getReturnTypeSourceRange();
3705         return true;
3706       }
3707       else
3708         NewQType = ResQT;
3709     }
3710 
3711     QualType OldReturnType = OldType->getReturnType();
3712     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3713     if (OldReturnType != NewReturnType) {
3714       // If this function has a deduced return type and has already been
3715       // defined, copy the deduced value from the old declaration.
3716       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3717       if (OldAT && OldAT->isDeduced()) {
3718         QualType DT = OldAT->getDeducedType();
3719         if (DT.isNull()) {
3720           New->setType(SubstAutoTypeDependent(New->getType()));
3721           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3722         } else {
3723           New->setType(SubstAutoType(New->getType(), DT));
3724           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3725         }
3726       }
3727     }
3728 
3729     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3730     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3731     if (OldMethod && NewMethod) {
3732       // Preserve triviality.
3733       NewMethod->setTrivial(OldMethod->isTrivial());
3734 
3735       // MSVC allows explicit template specialization at class scope:
3736       // 2 CXXMethodDecls referring to the same function will be injected.
3737       // We don't want a redeclaration error.
3738       bool IsClassScopeExplicitSpecialization =
3739                               OldMethod->isFunctionTemplateSpecialization() &&
3740                               NewMethod->isFunctionTemplateSpecialization();
3741       bool isFriend = NewMethod->getFriendObjectKind();
3742 
3743       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3744           !IsClassScopeExplicitSpecialization) {
3745         //    -- Member function declarations with the same name and the
3746         //       same parameter types cannot be overloaded if any of them
3747         //       is a static member function declaration.
3748         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3749           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3750           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3751           return true;
3752         }
3753 
3754         // C++ [class.mem]p1:
3755         //   [...] A member shall not be declared twice in the
3756         //   member-specification, except that a nested class or member
3757         //   class template can be declared and then later defined.
3758         if (!inTemplateInstantiation()) {
3759           unsigned NewDiag;
3760           if (isa<CXXConstructorDecl>(OldMethod))
3761             NewDiag = diag::err_constructor_redeclared;
3762           else if (isa<CXXDestructorDecl>(NewMethod))
3763             NewDiag = diag::err_destructor_redeclared;
3764           else if (isa<CXXConversionDecl>(NewMethod))
3765             NewDiag = diag::err_conv_function_redeclared;
3766           else
3767             NewDiag = diag::err_member_redeclared;
3768 
3769           Diag(New->getLocation(), NewDiag);
3770         } else {
3771           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3772             << New << New->getType();
3773         }
3774         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3775         return true;
3776 
3777       // Complain if this is an explicit declaration of a special
3778       // member that was initially declared implicitly.
3779       //
3780       // As an exception, it's okay to befriend such methods in order
3781       // to permit the implicit constructor/destructor/operator calls.
3782       } else if (OldMethod->isImplicit()) {
3783         if (isFriend) {
3784           NewMethod->setImplicit();
3785         } else {
3786           Diag(NewMethod->getLocation(),
3787                diag::err_definition_of_implicitly_declared_member)
3788             << New << getSpecialMember(OldMethod);
3789           return true;
3790         }
3791       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3792         Diag(NewMethod->getLocation(),
3793              diag::err_definition_of_explicitly_defaulted_member)
3794           << getSpecialMember(OldMethod);
3795         return true;
3796       }
3797     }
3798 
3799     // C++11 [dcl.attr.noreturn]p1:
3800     //   The first declaration of a function shall specify the noreturn
3801     //   attribute if any declaration of that function specifies the noreturn
3802     //   attribute.
3803     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3804       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3805         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3806             << NRA;
3807         Diag(Old->getLocation(), diag::note_previous_declaration);
3808       }
3809 
3810     // C++11 [dcl.attr.depend]p2:
3811     //   The first declaration of a function shall specify the
3812     //   carries_dependency attribute for its declarator-id if any declaration
3813     //   of the function specifies the carries_dependency attribute.
3814     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3815     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3816       Diag(CDA->getLocation(),
3817            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3818       Diag(Old->getFirstDecl()->getLocation(),
3819            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3820     }
3821 
3822     // (C++98 8.3.5p3):
3823     //   All declarations for a function shall agree exactly in both the
3824     //   return type and the parameter-type-list.
3825     // We also want to respect all the extended bits except noreturn.
3826 
3827     // noreturn should now match unless the old type info didn't have it.
3828     QualType OldQTypeForComparison = OldQType;
3829     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3830       auto *OldType = OldQType->castAs<FunctionProtoType>();
3831       const FunctionType *OldTypeForComparison
3832         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3833       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3834       assert(OldQTypeForComparison.isCanonical());
3835     }
3836 
3837     if (haveIncompatibleLanguageLinkages(Old, New)) {
3838       // As a special case, retain the language linkage from previous
3839       // declarations of a friend function as an extension.
3840       //
3841       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3842       // and is useful because there's otherwise no way to specify language
3843       // linkage within class scope.
3844       //
3845       // Check cautiously as the friend object kind isn't yet complete.
3846       if (New->getFriendObjectKind() != Decl::FOK_None) {
3847         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3848         Diag(OldLocation, PrevDiag);
3849       } else {
3850         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3851         Diag(OldLocation, PrevDiag);
3852         return true;
3853       }
3854     }
3855 
3856     // If the function types are compatible, merge the declarations. Ignore the
3857     // exception specifier because it was already checked above in
3858     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3859     // about incompatible types under -fms-compatibility.
3860     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3861                                                          NewQType))
3862       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3863 
3864     // If the types are imprecise (due to dependent constructs in friends or
3865     // local extern declarations), it's OK if they differ. We'll check again
3866     // during instantiation.
3867     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3868       return false;
3869 
3870     // Fall through for conflicting redeclarations and redefinitions.
3871   }
3872 
3873   // C: Function types need to be compatible, not identical. This handles
3874   // duplicate function decls like "void f(int); void f(enum X);" properly.
3875   if (!getLangOpts().CPlusPlus &&
3876       Context.typesAreCompatible(OldQType, NewQType)) {
3877     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3878     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3879     const FunctionProtoType *OldProto = nullptr;
3880     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3881         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3882       // The old declaration provided a function prototype, but the
3883       // new declaration does not. Merge in the prototype.
3884       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3885       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3886       NewQType =
3887           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3888                                   OldProto->getExtProtoInfo());
3889       New->setType(NewQType);
3890       New->setHasInheritedPrototype();
3891 
3892       // Synthesize parameters with the same types.
3893       SmallVector<ParmVarDecl*, 16> Params;
3894       for (const auto &ParamType : OldProto->param_types()) {
3895         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3896                                                  SourceLocation(), nullptr,
3897                                                  ParamType, /*TInfo=*/nullptr,
3898                                                  SC_None, nullptr);
3899         Param->setScopeInfo(0, Params.size());
3900         Param->setImplicit();
3901         Params.push_back(Param);
3902       }
3903 
3904       New->setParams(Params);
3905     }
3906 
3907     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3908   }
3909 
3910   // Check if the function types are compatible when pointer size address
3911   // spaces are ignored.
3912   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3913     return false;
3914 
3915   // GNU C permits a K&R definition to follow a prototype declaration
3916   // if the declared types of the parameters in the K&R definition
3917   // match the types in the prototype declaration, even when the
3918   // promoted types of the parameters from the K&R definition differ
3919   // from the types in the prototype. GCC then keeps the types from
3920   // the prototype.
3921   //
3922   // If a variadic prototype is followed by a non-variadic K&R definition,
3923   // the K&R definition becomes variadic.  This is sort of an edge case, but
3924   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3925   // C99 6.9.1p8.
3926   if (!getLangOpts().CPlusPlus &&
3927       Old->hasPrototype() && !New->hasPrototype() &&
3928       New->getType()->getAs<FunctionProtoType>() &&
3929       Old->getNumParams() == New->getNumParams()) {
3930     SmallVector<QualType, 16> ArgTypes;
3931     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3932     const FunctionProtoType *OldProto
3933       = Old->getType()->getAs<FunctionProtoType>();
3934     const FunctionProtoType *NewProto
3935       = New->getType()->getAs<FunctionProtoType>();
3936 
3937     // Determine whether this is the GNU C extension.
3938     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3939                                                NewProto->getReturnType());
3940     bool LooseCompatible = !MergedReturn.isNull();
3941     for (unsigned Idx = 0, End = Old->getNumParams();
3942          LooseCompatible && Idx != End; ++Idx) {
3943       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3944       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3945       if (Context.typesAreCompatible(OldParm->getType(),
3946                                      NewProto->getParamType(Idx))) {
3947         ArgTypes.push_back(NewParm->getType());
3948       } else if (Context.typesAreCompatible(OldParm->getType(),
3949                                             NewParm->getType(),
3950                                             /*CompareUnqualified=*/true)) {
3951         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3952                                            NewProto->getParamType(Idx) };
3953         Warnings.push_back(Warn);
3954         ArgTypes.push_back(NewParm->getType());
3955       } else
3956         LooseCompatible = false;
3957     }
3958 
3959     if (LooseCompatible) {
3960       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3961         Diag(Warnings[Warn].NewParm->getLocation(),
3962              diag::ext_param_promoted_not_compatible_with_prototype)
3963           << Warnings[Warn].PromotedType
3964           << Warnings[Warn].OldParm->getType();
3965         if (Warnings[Warn].OldParm->getLocation().isValid())
3966           Diag(Warnings[Warn].OldParm->getLocation(),
3967                diag::note_previous_declaration);
3968       }
3969 
3970       if (MergeTypeWithOld)
3971         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3972                                              OldProto->getExtProtoInfo()));
3973       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3974     }
3975 
3976     // Fall through to diagnose conflicting types.
3977   }
3978 
3979   // A function that has already been declared has been redeclared or
3980   // defined with a different type; show an appropriate diagnostic.
3981 
3982   // If the previous declaration was an implicitly-generated builtin
3983   // declaration, then at the very least we should use a specialized note.
3984   unsigned BuiltinID;
3985   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3986     // If it's actually a library-defined builtin function like 'malloc'
3987     // or 'printf', just warn about the incompatible redeclaration.
3988     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3989       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3990       Diag(OldLocation, diag::note_previous_builtin_declaration)
3991         << Old << Old->getType();
3992       return false;
3993     }
3994 
3995     PrevDiag = diag::note_previous_builtin_declaration;
3996   }
3997 
3998   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3999   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4000   return true;
4001 }
4002 
4003 /// Completes the merge of two function declarations that are
4004 /// known to be compatible.
4005 ///
4006 /// This routine handles the merging of attributes and other
4007 /// properties of function declarations from the old declaration to
4008 /// the new declaration, once we know that New is in fact a
4009 /// redeclaration of Old.
4010 ///
4011 /// \returns false
4012 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4013                                         Scope *S, bool MergeTypeWithOld) {
4014   // Merge the attributes
4015   mergeDeclAttributes(New, Old);
4016 
4017   // Merge "pure" flag.
4018   if (Old->isPure())
4019     New->setPure();
4020 
4021   // Merge "used" flag.
4022   if (Old->getMostRecentDecl()->isUsed(false))
4023     New->setIsUsed();
4024 
4025   // Merge attributes from the parameters.  These can mismatch with K&R
4026   // declarations.
4027   if (New->getNumParams() == Old->getNumParams())
4028       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4029         ParmVarDecl *NewParam = New->getParamDecl(i);
4030         ParmVarDecl *OldParam = Old->getParamDecl(i);
4031         mergeParamDeclAttributes(NewParam, OldParam, *this);
4032         mergeParamDeclTypes(NewParam, OldParam, *this);
4033       }
4034 
4035   if (getLangOpts().CPlusPlus)
4036     return MergeCXXFunctionDecl(New, Old, S);
4037 
4038   // Merge the function types so the we get the composite types for the return
4039   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4040   // was visible.
4041   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4042   if (!Merged.isNull() && MergeTypeWithOld)
4043     New->setType(Merged);
4044 
4045   return false;
4046 }
4047 
4048 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4049                                 ObjCMethodDecl *oldMethod) {
4050   // Merge the attributes, including deprecated/unavailable
4051   AvailabilityMergeKind MergeKind =
4052       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4053           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4054                                      : AMK_ProtocolImplementation)
4055           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4056                                                            : AMK_Override;
4057 
4058   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4059 
4060   // Merge attributes from the parameters.
4061   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4062                                        oe = oldMethod->param_end();
4063   for (ObjCMethodDecl::param_iterator
4064          ni = newMethod->param_begin(), ne = newMethod->param_end();
4065        ni != ne && oi != oe; ++ni, ++oi)
4066     mergeParamDeclAttributes(*ni, *oi, *this);
4067 
4068   CheckObjCMethodOverride(newMethod, oldMethod);
4069 }
4070 
4071 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4072   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4073 
4074   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4075          ? diag::err_redefinition_different_type
4076          : diag::err_redeclaration_different_type)
4077     << New->getDeclName() << New->getType() << Old->getType();
4078 
4079   diag::kind PrevDiag;
4080   SourceLocation OldLocation;
4081   std::tie(PrevDiag, OldLocation)
4082     = getNoteDiagForInvalidRedeclaration(Old, New);
4083   S.Diag(OldLocation, PrevDiag);
4084   New->setInvalidDecl();
4085 }
4086 
4087 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4088 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4089 /// emitting diagnostics as appropriate.
4090 ///
4091 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4092 /// to here in AddInitializerToDecl. We can't check them before the initializer
4093 /// is attached.
4094 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4095                              bool MergeTypeWithOld) {
4096   if (New->isInvalidDecl() || Old->isInvalidDecl())
4097     return;
4098 
4099   QualType MergedT;
4100   if (getLangOpts().CPlusPlus) {
4101     if (New->getType()->isUndeducedType()) {
4102       // We don't know what the new type is until the initializer is attached.
4103       return;
4104     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4105       // These could still be something that needs exception specs checked.
4106       return MergeVarDeclExceptionSpecs(New, Old);
4107     }
4108     // C++ [basic.link]p10:
4109     //   [...] the types specified by all declarations referring to a given
4110     //   object or function shall be identical, except that declarations for an
4111     //   array object can specify array types that differ by the presence or
4112     //   absence of a major array bound (8.3.4).
4113     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4114       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4115       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4116 
4117       // We are merging a variable declaration New into Old. If it has an array
4118       // bound, and that bound differs from Old's bound, we should diagnose the
4119       // mismatch.
4120       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4121         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4122              PrevVD = PrevVD->getPreviousDecl()) {
4123           QualType PrevVDTy = PrevVD->getType();
4124           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4125             continue;
4126 
4127           if (!Context.hasSameType(New->getType(), PrevVDTy))
4128             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4129         }
4130       }
4131 
4132       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4133         if (Context.hasSameType(OldArray->getElementType(),
4134                                 NewArray->getElementType()))
4135           MergedT = New->getType();
4136       }
4137       // FIXME: Check visibility. New is hidden but has a complete type. If New
4138       // has no array bound, it should not inherit one from Old, if Old is not
4139       // visible.
4140       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4141         if (Context.hasSameType(OldArray->getElementType(),
4142                                 NewArray->getElementType()))
4143           MergedT = Old->getType();
4144       }
4145     }
4146     else if (New->getType()->isObjCObjectPointerType() &&
4147                Old->getType()->isObjCObjectPointerType()) {
4148       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4149                                               Old->getType());
4150     }
4151   } else {
4152     // C 6.2.7p2:
4153     //   All declarations that refer to the same object or function shall have
4154     //   compatible type.
4155     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4156   }
4157   if (MergedT.isNull()) {
4158     // It's OK if we couldn't merge types if either type is dependent, for a
4159     // block-scope variable. In other cases (static data members of class
4160     // templates, variable templates, ...), we require the types to be
4161     // equivalent.
4162     // FIXME: The C++ standard doesn't say anything about this.
4163     if ((New->getType()->isDependentType() ||
4164          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4165       // If the old type was dependent, we can't merge with it, so the new type
4166       // becomes dependent for now. We'll reproduce the original type when we
4167       // instantiate the TypeSourceInfo for the variable.
4168       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4169         New->setType(Context.DependentTy);
4170       return;
4171     }
4172     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4173   }
4174 
4175   // Don't actually update the type on the new declaration if the old
4176   // declaration was an extern declaration in a different scope.
4177   if (MergeTypeWithOld)
4178     New->setType(MergedT);
4179 }
4180 
4181 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4182                                   LookupResult &Previous) {
4183   // C11 6.2.7p4:
4184   //   For an identifier with internal or external linkage declared
4185   //   in a scope in which a prior declaration of that identifier is
4186   //   visible, if the prior declaration specifies internal or
4187   //   external linkage, the type of the identifier at the later
4188   //   declaration becomes the composite type.
4189   //
4190   // If the variable isn't visible, we do not merge with its type.
4191   if (Previous.isShadowed())
4192     return false;
4193 
4194   if (S.getLangOpts().CPlusPlus) {
4195     // C++11 [dcl.array]p3:
4196     //   If there is a preceding declaration of the entity in the same
4197     //   scope in which the bound was specified, an omitted array bound
4198     //   is taken to be the same as in that earlier declaration.
4199     return NewVD->isPreviousDeclInSameBlockScope() ||
4200            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4201             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4202   } else {
4203     // If the old declaration was function-local, don't merge with its
4204     // type unless we're in the same function.
4205     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4206            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4207   }
4208 }
4209 
4210 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4211 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4212 /// situation, merging decls or emitting diagnostics as appropriate.
4213 ///
4214 /// Tentative definition rules (C99 6.9.2p2) are checked by
4215 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4216 /// definitions here, since the initializer hasn't been attached.
4217 ///
4218 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4219   // If the new decl is already invalid, don't do any other checking.
4220   if (New->isInvalidDecl())
4221     return;
4222 
4223   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4224     return;
4225 
4226   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4227 
4228   // Verify the old decl was also a variable or variable template.
4229   VarDecl *Old = nullptr;
4230   VarTemplateDecl *OldTemplate = nullptr;
4231   if (Previous.isSingleResult()) {
4232     if (NewTemplate) {
4233       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4234       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4235 
4236       if (auto *Shadow =
4237               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4238         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4239           return New->setInvalidDecl();
4240     } else {
4241       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4242 
4243       if (auto *Shadow =
4244               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4245         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4246           return New->setInvalidDecl();
4247     }
4248   }
4249   if (!Old) {
4250     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4251         << New->getDeclName();
4252     notePreviousDefinition(Previous.getRepresentativeDecl(),
4253                            New->getLocation());
4254     return New->setInvalidDecl();
4255   }
4256 
4257   // If the old declaration was found in an inline namespace and the new
4258   // declaration was qualified, update the DeclContext to match.
4259   adjustDeclContextForDeclaratorDecl(New, Old);
4260 
4261   // Ensure the template parameters are compatible.
4262   if (NewTemplate &&
4263       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4264                                       OldTemplate->getTemplateParameters(),
4265                                       /*Complain=*/true, TPL_TemplateMatch))
4266     return New->setInvalidDecl();
4267 
4268   // C++ [class.mem]p1:
4269   //   A member shall not be declared twice in the member-specification [...]
4270   //
4271   // Here, we need only consider static data members.
4272   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4273     Diag(New->getLocation(), diag::err_duplicate_member)
4274       << New->getIdentifier();
4275     Diag(Old->getLocation(), diag::note_previous_declaration);
4276     New->setInvalidDecl();
4277   }
4278 
4279   mergeDeclAttributes(New, Old);
4280   // Warn if an already-declared variable is made a weak_import in a subsequent
4281   // declaration
4282   if (New->hasAttr<WeakImportAttr>() &&
4283       Old->getStorageClass() == SC_None &&
4284       !Old->hasAttr<WeakImportAttr>()) {
4285     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4286     Diag(Old->getLocation(), diag::note_previous_declaration);
4287     // Remove weak_import attribute on new declaration.
4288     New->dropAttr<WeakImportAttr>();
4289   }
4290 
4291   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4292     if (!Old->hasAttr<InternalLinkageAttr>()) {
4293       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4294           << ILA;
4295       Diag(Old->getLocation(), diag::note_previous_declaration);
4296       New->dropAttr<InternalLinkageAttr>();
4297     }
4298 
4299   // Merge the types.
4300   VarDecl *MostRecent = Old->getMostRecentDecl();
4301   if (MostRecent != Old) {
4302     MergeVarDeclTypes(New, MostRecent,
4303                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4304     if (New->isInvalidDecl())
4305       return;
4306   }
4307 
4308   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4309   if (New->isInvalidDecl())
4310     return;
4311 
4312   diag::kind PrevDiag;
4313   SourceLocation OldLocation;
4314   std::tie(PrevDiag, OldLocation) =
4315       getNoteDiagForInvalidRedeclaration(Old, New);
4316 
4317   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4318   if (New->getStorageClass() == SC_Static &&
4319       !New->isStaticDataMember() &&
4320       Old->hasExternalFormalLinkage()) {
4321     if (getLangOpts().MicrosoftExt) {
4322       Diag(New->getLocation(), diag::ext_static_non_static)
4323           << New->getDeclName();
4324       Diag(OldLocation, PrevDiag);
4325     } else {
4326       Diag(New->getLocation(), diag::err_static_non_static)
4327           << New->getDeclName();
4328       Diag(OldLocation, PrevDiag);
4329       return New->setInvalidDecl();
4330     }
4331   }
4332   // C99 6.2.2p4:
4333   //   For an identifier declared with the storage-class specifier
4334   //   extern in a scope in which a prior declaration of that
4335   //   identifier is visible,23) if the prior declaration specifies
4336   //   internal or external linkage, the linkage of the identifier at
4337   //   the later declaration is the same as the linkage specified at
4338   //   the prior declaration. If no prior declaration is visible, or
4339   //   if the prior declaration specifies no linkage, then the
4340   //   identifier has external linkage.
4341   if (New->hasExternalStorage() && Old->hasLinkage())
4342     /* Okay */;
4343   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4344            !New->isStaticDataMember() &&
4345            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4346     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4347     Diag(OldLocation, PrevDiag);
4348     return New->setInvalidDecl();
4349   }
4350 
4351   // Check if extern is followed by non-extern and vice-versa.
4352   if (New->hasExternalStorage() &&
4353       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4354     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4355     Diag(OldLocation, PrevDiag);
4356     return New->setInvalidDecl();
4357   }
4358   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4359       !New->hasExternalStorage()) {
4360     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4361     Diag(OldLocation, PrevDiag);
4362     return New->setInvalidDecl();
4363   }
4364 
4365   if (CheckRedeclarationInModule(New, Old))
4366     return;
4367 
4368   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4369 
4370   // FIXME: The test for external storage here seems wrong? We still
4371   // need to check for mismatches.
4372   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4373       // Don't complain about out-of-line definitions of static members.
4374       !(Old->getLexicalDeclContext()->isRecord() &&
4375         !New->getLexicalDeclContext()->isRecord())) {
4376     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4377     Diag(OldLocation, PrevDiag);
4378     return New->setInvalidDecl();
4379   }
4380 
4381   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4382     if (VarDecl *Def = Old->getDefinition()) {
4383       // C++1z [dcl.fcn.spec]p4:
4384       //   If the definition of a variable appears in a translation unit before
4385       //   its first declaration as inline, the program is ill-formed.
4386       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4387       Diag(Def->getLocation(), diag::note_previous_definition);
4388     }
4389   }
4390 
4391   // If this redeclaration makes the variable inline, we may need to add it to
4392   // UndefinedButUsed.
4393   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4394       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4395     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4396                                            SourceLocation()));
4397 
4398   if (New->getTLSKind() != Old->getTLSKind()) {
4399     if (!Old->getTLSKind()) {
4400       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4401       Diag(OldLocation, PrevDiag);
4402     } else if (!New->getTLSKind()) {
4403       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4404       Diag(OldLocation, PrevDiag);
4405     } else {
4406       // Do not allow redeclaration to change the variable between requiring
4407       // static and dynamic initialization.
4408       // FIXME: GCC allows this, but uses the TLS keyword on the first
4409       // declaration to determine the kind. Do we need to be compatible here?
4410       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4411         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4412       Diag(OldLocation, PrevDiag);
4413     }
4414   }
4415 
4416   // C++ doesn't have tentative definitions, so go right ahead and check here.
4417   if (getLangOpts().CPlusPlus &&
4418       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4419     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4420         Old->getCanonicalDecl()->isConstexpr()) {
4421       // This definition won't be a definition any more once it's been merged.
4422       Diag(New->getLocation(),
4423            diag::warn_deprecated_redundant_constexpr_static_def);
4424     } else if (VarDecl *Def = Old->getDefinition()) {
4425       if (checkVarDeclRedefinition(Def, New))
4426         return;
4427     }
4428   }
4429 
4430   if (haveIncompatibleLanguageLinkages(Old, New)) {
4431     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4432     Diag(OldLocation, PrevDiag);
4433     New->setInvalidDecl();
4434     return;
4435   }
4436 
4437   // Merge "used" flag.
4438   if (Old->getMostRecentDecl()->isUsed(false))
4439     New->setIsUsed();
4440 
4441   // Keep a chain of previous declarations.
4442   New->setPreviousDecl(Old);
4443   if (NewTemplate)
4444     NewTemplate->setPreviousDecl(OldTemplate);
4445 
4446   // Inherit access appropriately.
4447   New->setAccess(Old->getAccess());
4448   if (NewTemplate)
4449     NewTemplate->setAccess(New->getAccess());
4450 
4451   if (Old->isInline())
4452     New->setImplicitlyInline();
4453 }
4454 
4455 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4456   SourceManager &SrcMgr = getSourceManager();
4457   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4458   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4459   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4460   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4461   auto &HSI = PP.getHeaderSearchInfo();
4462   StringRef HdrFilename =
4463       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4464 
4465   auto noteFromModuleOrInclude = [&](Module *Mod,
4466                                      SourceLocation IncLoc) -> bool {
4467     // Redefinition errors with modules are common with non modular mapped
4468     // headers, example: a non-modular header H in module A that also gets
4469     // included directly in a TU. Pointing twice to the same header/definition
4470     // is confusing, try to get better diagnostics when modules is on.
4471     if (IncLoc.isValid()) {
4472       if (Mod) {
4473         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4474             << HdrFilename.str() << Mod->getFullModuleName();
4475         if (!Mod->DefinitionLoc.isInvalid())
4476           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4477               << Mod->getFullModuleName();
4478       } else {
4479         Diag(IncLoc, diag::note_redefinition_include_same_file)
4480             << HdrFilename.str();
4481       }
4482       return true;
4483     }
4484 
4485     return false;
4486   };
4487 
4488   // Is it the same file and same offset? Provide more information on why
4489   // this leads to a redefinition error.
4490   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4491     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4492     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4493     bool EmittedDiag =
4494         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4495     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4496 
4497     // If the header has no guards, emit a note suggesting one.
4498     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4499       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4500 
4501     if (EmittedDiag)
4502       return;
4503   }
4504 
4505   // Redefinition coming from different files or couldn't do better above.
4506   if (Old->getLocation().isValid())
4507     Diag(Old->getLocation(), diag::note_previous_definition);
4508 }
4509 
4510 /// We've just determined that \p Old and \p New both appear to be definitions
4511 /// of the same variable. Either diagnose or fix the problem.
4512 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4513   if (!hasVisibleDefinition(Old) &&
4514       (New->getFormalLinkage() == InternalLinkage ||
4515        New->isInline() ||
4516        New->getDescribedVarTemplate() ||
4517        New->getNumTemplateParameterLists() ||
4518        New->getDeclContext()->isDependentContext())) {
4519     // The previous definition is hidden, and multiple definitions are
4520     // permitted (in separate TUs). Demote this to a declaration.
4521     New->demoteThisDefinitionToDeclaration();
4522 
4523     // Make the canonical definition visible.
4524     if (auto *OldTD = Old->getDescribedVarTemplate())
4525       makeMergedDefinitionVisible(OldTD);
4526     makeMergedDefinitionVisible(Old);
4527     return false;
4528   } else {
4529     Diag(New->getLocation(), diag::err_redefinition) << New;
4530     notePreviousDefinition(Old, New->getLocation());
4531     New->setInvalidDecl();
4532     return true;
4533   }
4534 }
4535 
4536 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4537 /// no declarator (e.g. "struct foo;") is parsed.
4538 Decl *
4539 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4540                                  RecordDecl *&AnonRecord) {
4541   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4542                                     AnonRecord);
4543 }
4544 
4545 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4546 // disambiguate entities defined in different scopes.
4547 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4548 // compatibility.
4549 // We will pick our mangling number depending on which version of MSVC is being
4550 // targeted.
4551 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4552   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4553              ? S->getMSCurManglingNumber()
4554              : S->getMSLastManglingNumber();
4555 }
4556 
4557 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4558   if (!Context.getLangOpts().CPlusPlus)
4559     return;
4560 
4561   if (isa<CXXRecordDecl>(Tag->getParent())) {
4562     // If this tag is the direct child of a class, number it if
4563     // it is anonymous.
4564     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4565       return;
4566     MangleNumberingContext &MCtx =
4567         Context.getManglingNumberContext(Tag->getParent());
4568     Context.setManglingNumber(
4569         Tag, MCtx.getManglingNumber(
4570                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4571     return;
4572   }
4573 
4574   // If this tag isn't a direct child of a class, number it if it is local.
4575   MangleNumberingContext *MCtx;
4576   Decl *ManglingContextDecl;
4577   std::tie(MCtx, ManglingContextDecl) =
4578       getCurrentMangleNumberContext(Tag->getDeclContext());
4579   if (MCtx) {
4580     Context.setManglingNumber(
4581         Tag, MCtx->getManglingNumber(
4582                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4583   }
4584 }
4585 
4586 namespace {
4587 struct NonCLikeKind {
4588   enum {
4589     None,
4590     BaseClass,
4591     DefaultMemberInit,
4592     Lambda,
4593     Friend,
4594     OtherMember,
4595     Invalid,
4596   } Kind = None;
4597   SourceRange Range;
4598 
4599   explicit operator bool() { return Kind != None; }
4600 };
4601 }
4602 
4603 /// Determine whether a class is C-like, according to the rules of C++
4604 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4605 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4606   if (RD->isInvalidDecl())
4607     return {NonCLikeKind::Invalid, {}};
4608 
4609   // C++ [dcl.typedef]p9: [P1766R1]
4610   //   An unnamed class with a typedef name for linkage purposes shall not
4611   //
4612   //    -- have any base classes
4613   if (RD->getNumBases())
4614     return {NonCLikeKind::BaseClass,
4615             SourceRange(RD->bases_begin()->getBeginLoc(),
4616                         RD->bases_end()[-1].getEndLoc())};
4617   bool Invalid = false;
4618   for (Decl *D : RD->decls()) {
4619     // Don't complain about things we already diagnosed.
4620     if (D->isInvalidDecl()) {
4621       Invalid = true;
4622       continue;
4623     }
4624 
4625     //  -- have any [...] default member initializers
4626     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4627       if (FD->hasInClassInitializer()) {
4628         auto *Init = FD->getInClassInitializer();
4629         return {NonCLikeKind::DefaultMemberInit,
4630                 Init ? Init->getSourceRange() : D->getSourceRange()};
4631       }
4632       continue;
4633     }
4634 
4635     // FIXME: We don't allow friend declarations. This violates the wording of
4636     // P1766, but not the intent.
4637     if (isa<FriendDecl>(D))
4638       return {NonCLikeKind::Friend, D->getSourceRange()};
4639 
4640     //  -- declare any members other than non-static data members, member
4641     //     enumerations, or member classes,
4642     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4643         isa<EnumDecl>(D))
4644       continue;
4645     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4646     if (!MemberRD) {
4647       if (D->isImplicit())
4648         continue;
4649       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4650     }
4651 
4652     //  -- contain a lambda-expression,
4653     if (MemberRD->isLambda())
4654       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4655 
4656     //  and all member classes shall also satisfy these requirements
4657     //  (recursively).
4658     if (MemberRD->isThisDeclarationADefinition()) {
4659       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4660         return Kind;
4661     }
4662   }
4663 
4664   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4665 }
4666 
4667 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4668                                         TypedefNameDecl *NewTD) {
4669   if (TagFromDeclSpec->isInvalidDecl())
4670     return;
4671 
4672   // Do nothing if the tag already has a name for linkage purposes.
4673   if (TagFromDeclSpec->hasNameForLinkage())
4674     return;
4675 
4676   // A well-formed anonymous tag must always be a TUK_Definition.
4677   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4678 
4679   // The type must match the tag exactly;  no qualifiers allowed.
4680   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4681                            Context.getTagDeclType(TagFromDeclSpec))) {
4682     if (getLangOpts().CPlusPlus)
4683       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4684     return;
4685   }
4686 
4687   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4688   //   An unnamed class with a typedef name for linkage purposes shall [be
4689   //   C-like].
4690   //
4691   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4692   // shouldn't happen, but there are constructs that the language rule doesn't
4693   // disallow for which we can't reasonably avoid computing linkage early.
4694   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4695   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4696                              : NonCLikeKind();
4697   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4698   if (NonCLike || ChangesLinkage) {
4699     if (NonCLike.Kind == NonCLikeKind::Invalid)
4700       return;
4701 
4702     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4703     if (ChangesLinkage) {
4704       // If the linkage changes, we can't accept this as an extension.
4705       if (NonCLike.Kind == NonCLikeKind::None)
4706         DiagID = diag::err_typedef_changes_linkage;
4707       else
4708         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4709     }
4710 
4711     SourceLocation FixitLoc =
4712         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4713     llvm::SmallString<40> TextToInsert;
4714     TextToInsert += ' ';
4715     TextToInsert += NewTD->getIdentifier()->getName();
4716 
4717     Diag(FixitLoc, DiagID)
4718       << isa<TypeAliasDecl>(NewTD)
4719       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4720     if (NonCLike.Kind != NonCLikeKind::None) {
4721       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4722         << NonCLike.Kind - 1 << NonCLike.Range;
4723     }
4724     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4725       << NewTD << isa<TypeAliasDecl>(NewTD);
4726 
4727     if (ChangesLinkage)
4728       return;
4729   }
4730 
4731   // Otherwise, set this as the anon-decl typedef for the tag.
4732   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4733 }
4734 
4735 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4736   switch (T) {
4737   case DeclSpec::TST_class:
4738     return 0;
4739   case DeclSpec::TST_struct:
4740     return 1;
4741   case DeclSpec::TST_interface:
4742     return 2;
4743   case DeclSpec::TST_union:
4744     return 3;
4745   case DeclSpec::TST_enum:
4746     return 4;
4747   default:
4748     llvm_unreachable("unexpected type specifier");
4749   }
4750 }
4751 
4752 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4753 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4754 /// parameters to cope with template friend declarations.
4755 Decl *
4756 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4757                                  MultiTemplateParamsArg TemplateParams,
4758                                  bool IsExplicitInstantiation,
4759                                  RecordDecl *&AnonRecord) {
4760   Decl *TagD = nullptr;
4761   TagDecl *Tag = nullptr;
4762   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4763       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4764       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4765       DS.getTypeSpecType() == DeclSpec::TST_union ||
4766       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4767     TagD = DS.getRepAsDecl();
4768 
4769     if (!TagD) // We probably had an error
4770       return nullptr;
4771 
4772     // Note that the above type specs guarantee that the
4773     // type rep is a Decl, whereas in many of the others
4774     // it's a Type.
4775     if (isa<TagDecl>(TagD))
4776       Tag = cast<TagDecl>(TagD);
4777     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4778       Tag = CTD->getTemplatedDecl();
4779   }
4780 
4781   if (Tag) {
4782     handleTagNumbering(Tag, S);
4783     Tag->setFreeStanding();
4784     if (Tag->isInvalidDecl())
4785       return Tag;
4786   }
4787 
4788   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4789     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4790     // or incomplete types shall not be restrict-qualified."
4791     if (TypeQuals & DeclSpec::TQ_restrict)
4792       Diag(DS.getRestrictSpecLoc(),
4793            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4794            << DS.getSourceRange();
4795   }
4796 
4797   if (DS.isInlineSpecified())
4798     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4799         << getLangOpts().CPlusPlus17;
4800 
4801   if (DS.hasConstexprSpecifier()) {
4802     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4803     // and definitions of functions and variables.
4804     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4805     // the declaration of a function or function template
4806     if (Tag)
4807       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4808           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4809           << static_cast<int>(DS.getConstexprSpecifier());
4810     else
4811       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4812           << static_cast<int>(DS.getConstexprSpecifier());
4813     // Don't emit warnings after this error.
4814     return TagD;
4815   }
4816 
4817   DiagnoseFunctionSpecifiers(DS);
4818 
4819   if (DS.isFriendSpecified()) {
4820     // If we're dealing with a decl but not a TagDecl, assume that
4821     // whatever routines created it handled the friendship aspect.
4822     if (TagD && !Tag)
4823       return nullptr;
4824     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4825   }
4826 
4827   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4828   bool IsExplicitSpecialization =
4829     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4830   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4831       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4832       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4833     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4834     // nested-name-specifier unless it is an explicit instantiation
4835     // or an explicit specialization.
4836     //
4837     // FIXME: We allow class template partial specializations here too, per the
4838     // obvious intent of DR1819.
4839     //
4840     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4841     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4842         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4843     return nullptr;
4844   }
4845 
4846   // Track whether this decl-specifier declares anything.
4847   bool DeclaresAnything = true;
4848 
4849   // Handle anonymous struct definitions.
4850   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4851     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4852         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4853       if (getLangOpts().CPlusPlus ||
4854           Record->getDeclContext()->isRecord()) {
4855         // If CurContext is a DeclContext that can contain statements,
4856         // RecursiveASTVisitor won't visit the decls that
4857         // BuildAnonymousStructOrUnion() will put into CurContext.
4858         // Also store them here so that they can be part of the
4859         // DeclStmt that gets created in this case.
4860         // FIXME: Also return the IndirectFieldDecls created by
4861         // BuildAnonymousStructOr union, for the same reason?
4862         if (CurContext->isFunctionOrMethod())
4863           AnonRecord = Record;
4864         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4865                                            Context.getPrintingPolicy());
4866       }
4867 
4868       DeclaresAnything = false;
4869     }
4870   }
4871 
4872   // C11 6.7.2.1p2:
4873   //   A struct-declaration that does not declare an anonymous structure or
4874   //   anonymous union shall contain a struct-declarator-list.
4875   //
4876   // This rule also existed in C89 and C99; the grammar for struct-declaration
4877   // did not permit a struct-declaration without a struct-declarator-list.
4878   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4879       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4880     // Check for Microsoft C extension: anonymous struct/union member.
4881     // Handle 2 kinds of anonymous struct/union:
4882     //   struct STRUCT;
4883     //   union UNION;
4884     // and
4885     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4886     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4887     if ((Tag && Tag->getDeclName()) ||
4888         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4889       RecordDecl *Record = nullptr;
4890       if (Tag)
4891         Record = dyn_cast<RecordDecl>(Tag);
4892       else if (const RecordType *RT =
4893                    DS.getRepAsType().get()->getAsStructureType())
4894         Record = RT->getDecl();
4895       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4896         Record = UT->getDecl();
4897 
4898       if (Record && getLangOpts().MicrosoftExt) {
4899         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4900             << Record->isUnion() << DS.getSourceRange();
4901         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4902       }
4903 
4904       DeclaresAnything = false;
4905     }
4906   }
4907 
4908   // Skip all the checks below if we have a type error.
4909   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4910       (TagD && TagD->isInvalidDecl()))
4911     return TagD;
4912 
4913   if (getLangOpts().CPlusPlus &&
4914       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4915     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4916       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4917           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4918         DeclaresAnything = false;
4919 
4920   if (!DS.isMissingDeclaratorOk()) {
4921     // Customize diagnostic for a typedef missing a name.
4922     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4923       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4924           << DS.getSourceRange();
4925     else
4926       DeclaresAnything = false;
4927   }
4928 
4929   if (DS.isModulePrivateSpecified() &&
4930       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4931     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4932       << Tag->getTagKind()
4933       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4934 
4935   ActOnDocumentableDecl(TagD);
4936 
4937   // C 6.7/2:
4938   //   A declaration [...] shall declare at least a declarator [...], a tag,
4939   //   or the members of an enumeration.
4940   // C++ [dcl.dcl]p3:
4941   //   [If there are no declarators], and except for the declaration of an
4942   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4943   //   names into the program, or shall redeclare a name introduced by a
4944   //   previous declaration.
4945   if (!DeclaresAnything) {
4946     // In C, we allow this as a (popular) extension / bug. Don't bother
4947     // producing further diagnostics for redundant qualifiers after this.
4948     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4949                                ? diag::err_no_declarators
4950                                : diag::ext_no_declarators)
4951         << DS.getSourceRange();
4952     return TagD;
4953   }
4954 
4955   // C++ [dcl.stc]p1:
4956   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4957   //   init-declarator-list of the declaration shall not be empty.
4958   // C++ [dcl.fct.spec]p1:
4959   //   If a cv-qualifier appears in a decl-specifier-seq, the
4960   //   init-declarator-list of the declaration shall not be empty.
4961   //
4962   // Spurious qualifiers here appear to be valid in C.
4963   unsigned DiagID = diag::warn_standalone_specifier;
4964   if (getLangOpts().CPlusPlus)
4965     DiagID = diag::ext_standalone_specifier;
4966 
4967   // Note that a linkage-specification sets a storage class, but
4968   // 'extern "C" struct foo;' is actually valid and not theoretically
4969   // useless.
4970   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4971     if (SCS == DeclSpec::SCS_mutable)
4972       // Since mutable is not a viable storage class specifier in C, there is
4973       // no reason to treat it as an extension. Instead, diagnose as an error.
4974       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4975     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4976       Diag(DS.getStorageClassSpecLoc(), DiagID)
4977         << DeclSpec::getSpecifierName(SCS);
4978   }
4979 
4980   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4981     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4982       << DeclSpec::getSpecifierName(TSCS);
4983   if (DS.getTypeQualifiers()) {
4984     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4985       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4986     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4987       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4988     // Restrict is covered above.
4989     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4990       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4991     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4992       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4993   }
4994 
4995   // Warn about ignored type attributes, for example:
4996   // __attribute__((aligned)) struct A;
4997   // Attributes should be placed after tag to apply to type declaration.
4998   if (!DS.getAttributes().empty()) {
4999     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5000     if (TypeSpecType == DeclSpec::TST_class ||
5001         TypeSpecType == DeclSpec::TST_struct ||
5002         TypeSpecType == DeclSpec::TST_interface ||
5003         TypeSpecType == DeclSpec::TST_union ||
5004         TypeSpecType == DeclSpec::TST_enum) {
5005       for (const ParsedAttr &AL : DS.getAttributes())
5006         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5007             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5008     }
5009   }
5010 
5011   return TagD;
5012 }
5013 
5014 /// We are trying to inject an anonymous member into the given scope;
5015 /// check if there's an existing declaration that can't be overloaded.
5016 ///
5017 /// \return true if this is a forbidden redeclaration
5018 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5019                                          Scope *S,
5020                                          DeclContext *Owner,
5021                                          DeclarationName Name,
5022                                          SourceLocation NameLoc,
5023                                          bool IsUnion) {
5024   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5025                  Sema::ForVisibleRedeclaration);
5026   if (!SemaRef.LookupName(R, S)) return false;
5027 
5028   // Pick a representative declaration.
5029   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5030   assert(PrevDecl && "Expected a non-null Decl");
5031 
5032   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5033     return false;
5034 
5035   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5036     << IsUnion << Name;
5037   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5038 
5039   return true;
5040 }
5041 
5042 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5043 /// anonymous struct or union AnonRecord into the owning context Owner
5044 /// and scope S. This routine will be invoked just after we realize
5045 /// that an unnamed union or struct is actually an anonymous union or
5046 /// struct, e.g.,
5047 ///
5048 /// @code
5049 /// union {
5050 ///   int i;
5051 ///   float f;
5052 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5053 ///    // f into the surrounding scope.x
5054 /// @endcode
5055 ///
5056 /// This routine is recursive, injecting the names of nested anonymous
5057 /// structs/unions into the owning context and scope as well.
5058 static bool
5059 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5060                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5061                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5062   bool Invalid = false;
5063 
5064   // Look every FieldDecl and IndirectFieldDecl with a name.
5065   for (auto *D : AnonRecord->decls()) {
5066     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5067         cast<NamedDecl>(D)->getDeclName()) {
5068       ValueDecl *VD = cast<ValueDecl>(D);
5069       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5070                                        VD->getLocation(),
5071                                        AnonRecord->isUnion())) {
5072         // C++ [class.union]p2:
5073         //   The names of the members of an anonymous union shall be
5074         //   distinct from the names of any other entity in the
5075         //   scope in which the anonymous union is declared.
5076         Invalid = true;
5077       } else {
5078         // C++ [class.union]p2:
5079         //   For the purpose of name lookup, after the anonymous union
5080         //   definition, the members of the anonymous union are
5081         //   considered to have been defined in the scope in which the
5082         //   anonymous union is declared.
5083         unsigned OldChainingSize = Chaining.size();
5084         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5085           Chaining.append(IF->chain_begin(), IF->chain_end());
5086         else
5087           Chaining.push_back(VD);
5088 
5089         assert(Chaining.size() >= 2);
5090         NamedDecl **NamedChain =
5091           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5092         for (unsigned i = 0; i < Chaining.size(); i++)
5093           NamedChain[i] = Chaining[i];
5094 
5095         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5096             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5097             VD->getType(), {NamedChain, Chaining.size()});
5098 
5099         for (const auto *Attr : VD->attrs())
5100           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5101 
5102         IndirectField->setAccess(AS);
5103         IndirectField->setImplicit();
5104         SemaRef.PushOnScopeChains(IndirectField, S);
5105 
5106         // That includes picking up the appropriate access specifier.
5107         if (AS != AS_none) IndirectField->setAccess(AS);
5108 
5109         Chaining.resize(OldChainingSize);
5110       }
5111     }
5112   }
5113 
5114   return Invalid;
5115 }
5116 
5117 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5118 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5119 /// illegal input values are mapped to SC_None.
5120 static StorageClass
5121 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5122   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5123   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5124          "Parser allowed 'typedef' as storage class VarDecl.");
5125   switch (StorageClassSpec) {
5126   case DeclSpec::SCS_unspecified:    return SC_None;
5127   case DeclSpec::SCS_extern:
5128     if (DS.isExternInLinkageSpec())
5129       return SC_None;
5130     return SC_Extern;
5131   case DeclSpec::SCS_static:         return SC_Static;
5132   case DeclSpec::SCS_auto:           return SC_Auto;
5133   case DeclSpec::SCS_register:       return SC_Register;
5134   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5135     // Illegal SCSs map to None: error reporting is up to the caller.
5136   case DeclSpec::SCS_mutable:        // Fall through.
5137   case DeclSpec::SCS_typedef:        return SC_None;
5138   }
5139   llvm_unreachable("unknown storage class specifier");
5140 }
5141 
5142 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5143   assert(Record->hasInClassInitializer());
5144 
5145   for (const auto *I : Record->decls()) {
5146     const auto *FD = dyn_cast<FieldDecl>(I);
5147     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5148       FD = IFD->getAnonField();
5149     if (FD && FD->hasInClassInitializer())
5150       return FD->getLocation();
5151   }
5152 
5153   llvm_unreachable("couldn't find in-class initializer");
5154 }
5155 
5156 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5157                                       SourceLocation DefaultInitLoc) {
5158   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5159     return;
5160 
5161   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5162   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5163 }
5164 
5165 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5166                                       CXXRecordDecl *AnonUnion) {
5167   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5168     return;
5169 
5170   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5171 }
5172 
5173 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5174 /// anonymous structure or union. Anonymous unions are a C++ feature
5175 /// (C++ [class.union]) and a C11 feature; anonymous structures
5176 /// are a C11 feature and GNU C++ extension.
5177 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5178                                         AccessSpecifier AS,
5179                                         RecordDecl *Record,
5180                                         const PrintingPolicy &Policy) {
5181   DeclContext *Owner = Record->getDeclContext();
5182 
5183   // Diagnose whether this anonymous struct/union is an extension.
5184   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5185     Diag(Record->getLocation(), diag::ext_anonymous_union);
5186   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5187     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5188   else if (!Record->isUnion() && !getLangOpts().C11)
5189     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5190 
5191   // C and C++ require different kinds of checks for anonymous
5192   // structs/unions.
5193   bool Invalid = false;
5194   if (getLangOpts().CPlusPlus) {
5195     const char *PrevSpec = nullptr;
5196     if (Record->isUnion()) {
5197       // C++ [class.union]p6:
5198       // C++17 [class.union.anon]p2:
5199       //   Anonymous unions declared in a named namespace or in the
5200       //   global namespace shall be declared static.
5201       unsigned DiagID;
5202       DeclContext *OwnerScope = Owner->getRedeclContext();
5203       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5204           (OwnerScope->isTranslationUnit() ||
5205            (OwnerScope->isNamespace() &&
5206             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5207         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5208           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5209 
5210         // Recover by adding 'static'.
5211         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5212                                PrevSpec, DiagID, Policy);
5213       }
5214       // C++ [class.union]p6:
5215       //   A storage class is not allowed in a declaration of an
5216       //   anonymous union in a class scope.
5217       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5218                isa<RecordDecl>(Owner)) {
5219         Diag(DS.getStorageClassSpecLoc(),
5220              diag::err_anonymous_union_with_storage_spec)
5221           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5222 
5223         // Recover by removing the storage specifier.
5224         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5225                                SourceLocation(),
5226                                PrevSpec, DiagID, Context.getPrintingPolicy());
5227       }
5228     }
5229 
5230     // Ignore const/volatile/restrict qualifiers.
5231     if (DS.getTypeQualifiers()) {
5232       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5233         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5234           << Record->isUnion() << "const"
5235           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5236       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5237         Diag(DS.getVolatileSpecLoc(),
5238              diag::ext_anonymous_struct_union_qualified)
5239           << Record->isUnion() << "volatile"
5240           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5241       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5242         Diag(DS.getRestrictSpecLoc(),
5243              diag::ext_anonymous_struct_union_qualified)
5244           << Record->isUnion() << "restrict"
5245           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5246       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5247         Diag(DS.getAtomicSpecLoc(),
5248              diag::ext_anonymous_struct_union_qualified)
5249           << Record->isUnion() << "_Atomic"
5250           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5251       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5252         Diag(DS.getUnalignedSpecLoc(),
5253              diag::ext_anonymous_struct_union_qualified)
5254           << Record->isUnion() << "__unaligned"
5255           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5256 
5257       DS.ClearTypeQualifiers();
5258     }
5259 
5260     // C++ [class.union]p2:
5261     //   The member-specification of an anonymous union shall only
5262     //   define non-static data members. [Note: nested types and
5263     //   functions cannot be declared within an anonymous union. ]
5264     for (auto *Mem : Record->decls()) {
5265       // Ignore invalid declarations; we already diagnosed them.
5266       if (Mem->isInvalidDecl())
5267         continue;
5268 
5269       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5270         // C++ [class.union]p3:
5271         //   An anonymous union shall not have private or protected
5272         //   members (clause 11).
5273         assert(FD->getAccess() != AS_none);
5274         if (FD->getAccess() != AS_public) {
5275           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5276             << Record->isUnion() << (FD->getAccess() == AS_protected);
5277           Invalid = true;
5278         }
5279 
5280         // C++ [class.union]p1
5281         //   An object of a class with a non-trivial constructor, a non-trivial
5282         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5283         //   assignment operator cannot be a member of a union, nor can an
5284         //   array of such objects.
5285         if (CheckNontrivialField(FD))
5286           Invalid = true;
5287       } else if (Mem->isImplicit()) {
5288         // Any implicit members are fine.
5289       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5290         // This is a type that showed up in an
5291         // elaborated-type-specifier inside the anonymous struct or
5292         // union, but which actually declares a type outside of the
5293         // anonymous struct or union. It's okay.
5294       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5295         if (!MemRecord->isAnonymousStructOrUnion() &&
5296             MemRecord->getDeclName()) {
5297           // Visual C++ allows type definition in anonymous struct or union.
5298           if (getLangOpts().MicrosoftExt)
5299             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5300               << Record->isUnion();
5301           else {
5302             // This is a nested type declaration.
5303             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5304               << Record->isUnion();
5305             Invalid = true;
5306           }
5307         } else {
5308           // This is an anonymous type definition within another anonymous type.
5309           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5310           // not part of standard C++.
5311           Diag(MemRecord->getLocation(),
5312                diag::ext_anonymous_record_with_anonymous_type)
5313             << Record->isUnion();
5314         }
5315       } else if (isa<AccessSpecDecl>(Mem)) {
5316         // Any access specifier is fine.
5317       } else if (isa<StaticAssertDecl>(Mem)) {
5318         // In C++1z, static_assert declarations are also fine.
5319       } else {
5320         // We have something that isn't a non-static data
5321         // member. Complain about it.
5322         unsigned DK = diag::err_anonymous_record_bad_member;
5323         if (isa<TypeDecl>(Mem))
5324           DK = diag::err_anonymous_record_with_type;
5325         else if (isa<FunctionDecl>(Mem))
5326           DK = diag::err_anonymous_record_with_function;
5327         else if (isa<VarDecl>(Mem))
5328           DK = diag::err_anonymous_record_with_static;
5329 
5330         // Visual C++ allows type definition in anonymous struct or union.
5331         if (getLangOpts().MicrosoftExt &&
5332             DK == diag::err_anonymous_record_with_type)
5333           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5334             << Record->isUnion();
5335         else {
5336           Diag(Mem->getLocation(), DK) << Record->isUnion();
5337           Invalid = true;
5338         }
5339       }
5340     }
5341 
5342     // C++11 [class.union]p8 (DR1460):
5343     //   At most one variant member of a union may have a
5344     //   brace-or-equal-initializer.
5345     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5346         Owner->isRecord())
5347       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5348                                 cast<CXXRecordDecl>(Record));
5349   }
5350 
5351   if (!Record->isUnion() && !Owner->isRecord()) {
5352     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5353       << getLangOpts().CPlusPlus;
5354     Invalid = true;
5355   }
5356 
5357   // C++ [dcl.dcl]p3:
5358   //   [If there are no declarators], and except for the declaration of an
5359   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5360   //   names into the program
5361   // C++ [class.mem]p2:
5362   //   each such member-declaration shall either declare at least one member
5363   //   name of the class or declare at least one unnamed bit-field
5364   //
5365   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5366   if (getLangOpts().CPlusPlus && Record->field_empty())
5367     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5368 
5369   // Mock up a declarator.
5370   Declarator Dc(DS, DeclaratorContext::Member);
5371   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5372   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5373 
5374   // Create a declaration for this anonymous struct/union.
5375   NamedDecl *Anon = nullptr;
5376   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5377     Anon = FieldDecl::Create(
5378         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5379         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5380         /*BitWidth=*/nullptr, /*Mutable=*/false,
5381         /*InitStyle=*/ICIS_NoInit);
5382     Anon->setAccess(AS);
5383     ProcessDeclAttributes(S, Anon, Dc);
5384 
5385     if (getLangOpts().CPlusPlus)
5386       FieldCollector->Add(cast<FieldDecl>(Anon));
5387   } else {
5388     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5389     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5390     if (SCSpec == DeclSpec::SCS_mutable) {
5391       // mutable can only appear on non-static class members, so it's always
5392       // an error here
5393       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5394       Invalid = true;
5395       SC = SC_None;
5396     }
5397 
5398     assert(DS.getAttributes().empty() && "No attribute expected");
5399     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5400                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5401                            Context.getTypeDeclType(Record), TInfo, SC);
5402 
5403     // Default-initialize the implicit variable. This initialization will be
5404     // trivial in almost all cases, except if a union member has an in-class
5405     // initializer:
5406     //   union { int n = 0; };
5407     ActOnUninitializedDecl(Anon);
5408   }
5409   Anon->setImplicit();
5410 
5411   // Mark this as an anonymous struct/union type.
5412   Record->setAnonymousStructOrUnion(true);
5413 
5414   // Add the anonymous struct/union object to the current
5415   // context. We'll be referencing this object when we refer to one of
5416   // its members.
5417   Owner->addDecl(Anon);
5418 
5419   // Inject the members of the anonymous struct/union into the owning
5420   // context and into the identifier resolver chain for name lookup
5421   // purposes.
5422   SmallVector<NamedDecl*, 2> Chain;
5423   Chain.push_back(Anon);
5424 
5425   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5426     Invalid = true;
5427 
5428   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5429     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5430       MangleNumberingContext *MCtx;
5431       Decl *ManglingContextDecl;
5432       std::tie(MCtx, ManglingContextDecl) =
5433           getCurrentMangleNumberContext(NewVD->getDeclContext());
5434       if (MCtx) {
5435         Context.setManglingNumber(
5436             NewVD, MCtx->getManglingNumber(
5437                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5438         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5439       }
5440     }
5441   }
5442 
5443   if (Invalid)
5444     Anon->setInvalidDecl();
5445 
5446   return Anon;
5447 }
5448 
5449 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5450 /// Microsoft C anonymous structure.
5451 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5452 /// Example:
5453 ///
5454 /// struct A { int a; };
5455 /// struct B { struct A; int b; };
5456 ///
5457 /// void foo() {
5458 ///   B var;
5459 ///   var.a = 3;
5460 /// }
5461 ///
5462 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5463                                            RecordDecl *Record) {
5464   assert(Record && "expected a record!");
5465 
5466   // Mock up a declarator.
5467   Declarator Dc(DS, DeclaratorContext::TypeName);
5468   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5469   assert(TInfo && "couldn't build declarator info for anonymous struct");
5470 
5471   auto *ParentDecl = cast<RecordDecl>(CurContext);
5472   QualType RecTy = Context.getTypeDeclType(Record);
5473 
5474   // Create a declaration for this anonymous struct.
5475   NamedDecl *Anon =
5476       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5477                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5478                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5479                         /*InitStyle=*/ICIS_NoInit);
5480   Anon->setImplicit();
5481 
5482   // Add the anonymous struct object to the current context.
5483   CurContext->addDecl(Anon);
5484 
5485   // Inject the members of the anonymous struct into the current
5486   // context and into the identifier resolver chain for name lookup
5487   // purposes.
5488   SmallVector<NamedDecl*, 2> Chain;
5489   Chain.push_back(Anon);
5490 
5491   RecordDecl *RecordDef = Record->getDefinition();
5492   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5493                                diag::err_field_incomplete_or_sizeless) ||
5494       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5495                                           AS_none, Chain)) {
5496     Anon->setInvalidDecl();
5497     ParentDecl->setInvalidDecl();
5498   }
5499 
5500   return Anon;
5501 }
5502 
5503 /// GetNameForDeclarator - Determine the full declaration name for the
5504 /// given Declarator.
5505 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5506   return GetNameFromUnqualifiedId(D.getName());
5507 }
5508 
5509 /// Retrieves the declaration name from a parsed unqualified-id.
5510 DeclarationNameInfo
5511 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5512   DeclarationNameInfo NameInfo;
5513   NameInfo.setLoc(Name.StartLocation);
5514 
5515   switch (Name.getKind()) {
5516 
5517   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5518   case UnqualifiedIdKind::IK_Identifier:
5519     NameInfo.setName(Name.Identifier);
5520     return NameInfo;
5521 
5522   case UnqualifiedIdKind::IK_DeductionGuideName: {
5523     // C++ [temp.deduct.guide]p3:
5524     //   The simple-template-id shall name a class template specialization.
5525     //   The template-name shall be the same identifier as the template-name
5526     //   of the simple-template-id.
5527     // These together intend to imply that the template-name shall name a
5528     // class template.
5529     // FIXME: template<typename T> struct X {};
5530     //        template<typename T> using Y = X<T>;
5531     //        Y(int) -> Y<int>;
5532     //   satisfies these rules but does not name a class template.
5533     TemplateName TN = Name.TemplateName.get().get();
5534     auto *Template = TN.getAsTemplateDecl();
5535     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5536       Diag(Name.StartLocation,
5537            diag::err_deduction_guide_name_not_class_template)
5538         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5539       if (Template)
5540         Diag(Template->getLocation(), diag::note_template_decl_here);
5541       return DeclarationNameInfo();
5542     }
5543 
5544     NameInfo.setName(
5545         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5546     return NameInfo;
5547   }
5548 
5549   case UnqualifiedIdKind::IK_OperatorFunctionId:
5550     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5551                                            Name.OperatorFunctionId.Operator));
5552     NameInfo.setCXXOperatorNameRange(SourceRange(
5553         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5554     return NameInfo;
5555 
5556   case UnqualifiedIdKind::IK_LiteralOperatorId:
5557     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5558                                                            Name.Identifier));
5559     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5560     return NameInfo;
5561 
5562   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5563     TypeSourceInfo *TInfo;
5564     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5565     if (Ty.isNull())
5566       return DeclarationNameInfo();
5567     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5568                                                Context.getCanonicalType(Ty)));
5569     NameInfo.setNamedTypeInfo(TInfo);
5570     return NameInfo;
5571   }
5572 
5573   case UnqualifiedIdKind::IK_ConstructorName: {
5574     TypeSourceInfo *TInfo;
5575     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5576     if (Ty.isNull())
5577       return DeclarationNameInfo();
5578     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5579                                               Context.getCanonicalType(Ty)));
5580     NameInfo.setNamedTypeInfo(TInfo);
5581     return NameInfo;
5582   }
5583 
5584   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5585     // In well-formed code, we can only have a constructor
5586     // template-id that refers to the current context, so go there
5587     // to find the actual type being constructed.
5588     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5589     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5590       return DeclarationNameInfo();
5591 
5592     // Determine the type of the class being constructed.
5593     QualType CurClassType = Context.getTypeDeclType(CurClass);
5594 
5595     // FIXME: Check two things: that the template-id names the same type as
5596     // CurClassType, and that the template-id does not occur when the name
5597     // was qualified.
5598 
5599     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5600                                     Context.getCanonicalType(CurClassType)));
5601     // FIXME: should we retrieve TypeSourceInfo?
5602     NameInfo.setNamedTypeInfo(nullptr);
5603     return NameInfo;
5604   }
5605 
5606   case UnqualifiedIdKind::IK_DestructorName: {
5607     TypeSourceInfo *TInfo;
5608     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5609     if (Ty.isNull())
5610       return DeclarationNameInfo();
5611     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5612                                               Context.getCanonicalType(Ty)));
5613     NameInfo.setNamedTypeInfo(TInfo);
5614     return NameInfo;
5615   }
5616 
5617   case UnqualifiedIdKind::IK_TemplateId: {
5618     TemplateName TName = Name.TemplateId->Template.get();
5619     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5620     return Context.getNameForTemplate(TName, TNameLoc);
5621   }
5622 
5623   } // switch (Name.getKind())
5624 
5625   llvm_unreachable("Unknown name kind");
5626 }
5627 
5628 static QualType getCoreType(QualType Ty) {
5629   do {
5630     if (Ty->isPointerType() || Ty->isReferenceType())
5631       Ty = Ty->getPointeeType();
5632     else if (Ty->isArrayType())
5633       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5634     else
5635       return Ty.withoutLocalFastQualifiers();
5636   } while (true);
5637 }
5638 
5639 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5640 /// and Definition have "nearly" matching parameters. This heuristic is
5641 /// used to improve diagnostics in the case where an out-of-line function
5642 /// definition doesn't match any declaration within the class or namespace.
5643 /// Also sets Params to the list of indices to the parameters that differ
5644 /// between the declaration and the definition. If hasSimilarParameters
5645 /// returns true and Params is empty, then all of the parameters match.
5646 static bool hasSimilarParameters(ASTContext &Context,
5647                                      FunctionDecl *Declaration,
5648                                      FunctionDecl *Definition,
5649                                      SmallVectorImpl<unsigned> &Params) {
5650   Params.clear();
5651   if (Declaration->param_size() != Definition->param_size())
5652     return false;
5653   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5654     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5655     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5656 
5657     // The parameter types are identical
5658     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5659       continue;
5660 
5661     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5662     QualType DefParamBaseTy = getCoreType(DefParamTy);
5663     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5664     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5665 
5666     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5667         (DeclTyName && DeclTyName == DefTyName))
5668       Params.push_back(Idx);
5669     else  // The two parameters aren't even close
5670       return false;
5671   }
5672 
5673   return true;
5674 }
5675 
5676 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5677 /// declarator needs to be rebuilt in the current instantiation.
5678 /// Any bits of declarator which appear before the name are valid for
5679 /// consideration here.  That's specifically the type in the decl spec
5680 /// and the base type in any member-pointer chunks.
5681 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5682                                                     DeclarationName Name) {
5683   // The types we specifically need to rebuild are:
5684   //   - typenames, typeofs, and decltypes
5685   //   - types which will become injected class names
5686   // Of course, we also need to rebuild any type referencing such a
5687   // type.  It's safest to just say "dependent", but we call out a
5688   // few cases here.
5689 
5690   DeclSpec &DS = D.getMutableDeclSpec();
5691   switch (DS.getTypeSpecType()) {
5692   case DeclSpec::TST_typename:
5693   case DeclSpec::TST_typeofType:
5694   case DeclSpec::TST_underlyingType:
5695   case DeclSpec::TST_atomic: {
5696     // Grab the type from the parser.
5697     TypeSourceInfo *TSI = nullptr;
5698     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5699     if (T.isNull() || !T->isInstantiationDependentType()) break;
5700 
5701     // Make sure there's a type source info.  This isn't really much
5702     // of a waste; most dependent types should have type source info
5703     // attached already.
5704     if (!TSI)
5705       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5706 
5707     // Rebuild the type in the current instantiation.
5708     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5709     if (!TSI) return true;
5710 
5711     // Store the new type back in the decl spec.
5712     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5713     DS.UpdateTypeRep(LocType);
5714     break;
5715   }
5716 
5717   case DeclSpec::TST_decltype:
5718   case DeclSpec::TST_typeofExpr: {
5719     Expr *E = DS.getRepAsExpr();
5720     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5721     if (Result.isInvalid()) return true;
5722     DS.UpdateExprRep(Result.get());
5723     break;
5724   }
5725 
5726   default:
5727     // Nothing to do for these decl specs.
5728     break;
5729   }
5730 
5731   // It doesn't matter what order we do this in.
5732   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5733     DeclaratorChunk &Chunk = D.getTypeObject(I);
5734 
5735     // The only type information in the declarator which can come
5736     // before the declaration name is the base type of a member
5737     // pointer.
5738     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5739       continue;
5740 
5741     // Rebuild the scope specifier in-place.
5742     CXXScopeSpec &SS = Chunk.Mem.Scope();
5743     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5744       return true;
5745   }
5746 
5747   return false;
5748 }
5749 
5750 /// Returns true if the declaration is declared in a system header or from a
5751 /// system macro.
5752 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5753   return SM.isInSystemHeader(D->getLocation()) ||
5754          SM.isInSystemMacro(D->getLocation());
5755 }
5756 
5757 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5758   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5759   // of system decl.
5760   if (D->getPreviousDecl() || D->isImplicit())
5761     return;
5762   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5763   if (Status != ReservedIdentifierStatus::NotReserved &&
5764       !isFromSystemHeader(Context.getSourceManager(), D)) {
5765     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5766         << D << static_cast<int>(Status);
5767   }
5768 }
5769 
5770 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5771   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5772   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5773 
5774   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5775       Dcl && Dcl->getDeclContext()->isFileContext())
5776     Dcl->setTopLevelDeclInObjCContainer();
5777 
5778   return Dcl;
5779 }
5780 
5781 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5782 ///   If T is the name of a class, then each of the following shall have a
5783 ///   name different from T:
5784 ///     - every static data member of class T;
5785 ///     - every member function of class T
5786 ///     - every member of class T that is itself a type;
5787 /// \returns true if the declaration name violates these rules.
5788 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5789                                    DeclarationNameInfo NameInfo) {
5790   DeclarationName Name = NameInfo.getName();
5791 
5792   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5793   while (Record && Record->isAnonymousStructOrUnion())
5794     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5795   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5796     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5797     return true;
5798   }
5799 
5800   return false;
5801 }
5802 
5803 /// Diagnose a declaration whose declarator-id has the given
5804 /// nested-name-specifier.
5805 ///
5806 /// \param SS The nested-name-specifier of the declarator-id.
5807 ///
5808 /// \param DC The declaration context to which the nested-name-specifier
5809 /// resolves.
5810 ///
5811 /// \param Name The name of the entity being declared.
5812 ///
5813 /// \param Loc The location of the name of the entity being declared.
5814 ///
5815 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5816 /// we're declaring an explicit / partial specialization / instantiation.
5817 ///
5818 /// \returns true if we cannot safely recover from this error, false otherwise.
5819 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5820                                         DeclarationName Name,
5821                                         SourceLocation Loc, bool IsTemplateId) {
5822   DeclContext *Cur = CurContext;
5823   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5824     Cur = Cur->getParent();
5825 
5826   // If the user provided a superfluous scope specifier that refers back to the
5827   // class in which the entity is already declared, diagnose and ignore it.
5828   //
5829   // class X {
5830   //   void X::f();
5831   // };
5832   //
5833   // Note, it was once ill-formed to give redundant qualification in all
5834   // contexts, but that rule was removed by DR482.
5835   if (Cur->Equals(DC)) {
5836     if (Cur->isRecord()) {
5837       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5838                                       : diag::err_member_extra_qualification)
5839         << Name << FixItHint::CreateRemoval(SS.getRange());
5840       SS.clear();
5841     } else {
5842       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5843     }
5844     return false;
5845   }
5846 
5847   // Check whether the qualifying scope encloses the scope of the original
5848   // declaration. For a template-id, we perform the checks in
5849   // CheckTemplateSpecializationScope.
5850   if (!Cur->Encloses(DC) && !IsTemplateId) {
5851     if (Cur->isRecord())
5852       Diag(Loc, diag::err_member_qualification)
5853         << Name << SS.getRange();
5854     else if (isa<TranslationUnitDecl>(DC))
5855       Diag(Loc, diag::err_invalid_declarator_global_scope)
5856         << Name << SS.getRange();
5857     else if (isa<FunctionDecl>(Cur))
5858       Diag(Loc, diag::err_invalid_declarator_in_function)
5859         << Name << SS.getRange();
5860     else if (isa<BlockDecl>(Cur))
5861       Diag(Loc, diag::err_invalid_declarator_in_block)
5862         << Name << SS.getRange();
5863     else if (isa<ExportDecl>(Cur)) {
5864       if (!isa<NamespaceDecl>(DC))
5865         Diag(Loc, diag::err_export_non_namespace_scope_name)
5866             << Name << SS.getRange();
5867       else
5868         // The cases that DC is not NamespaceDecl should be handled in
5869         // CheckRedeclarationExported.
5870         return false;
5871     } else
5872       Diag(Loc, diag::err_invalid_declarator_scope)
5873       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5874 
5875     return true;
5876   }
5877 
5878   if (Cur->isRecord()) {
5879     // Cannot qualify members within a class.
5880     Diag(Loc, diag::err_member_qualification)
5881       << Name << SS.getRange();
5882     SS.clear();
5883 
5884     // C++ constructors and destructors with incorrect scopes can break
5885     // our AST invariants by having the wrong underlying types. If
5886     // that's the case, then drop this declaration entirely.
5887     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5888          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5889         !Context.hasSameType(Name.getCXXNameType(),
5890                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5891       return true;
5892 
5893     return false;
5894   }
5895 
5896   // C++11 [dcl.meaning]p1:
5897   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5898   //   not begin with a decltype-specifer"
5899   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5900   while (SpecLoc.getPrefix())
5901     SpecLoc = SpecLoc.getPrefix();
5902   if (isa_and_nonnull<DecltypeType>(
5903           SpecLoc.getNestedNameSpecifier()->getAsType()))
5904     Diag(Loc, diag::err_decltype_in_declarator)
5905       << SpecLoc.getTypeLoc().getSourceRange();
5906 
5907   return false;
5908 }
5909 
5910 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5911                                   MultiTemplateParamsArg TemplateParamLists) {
5912   // TODO: consider using NameInfo for diagnostic.
5913   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5914   DeclarationName Name = NameInfo.getName();
5915 
5916   // All of these full declarators require an identifier.  If it doesn't have
5917   // one, the ParsedFreeStandingDeclSpec action should be used.
5918   if (D.isDecompositionDeclarator()) {
5919     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5920   } else if (!Name) {
5921     if (!D.isInvalidType())  // Reject this if we think it is valid.
5922       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5923           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5924     return nullptr;
5925   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5926     return nullptr;
5927 
5928   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5929   // we find one that is.
5930   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5931          (S->getFlags() & Scope::TemplateParamScope) != 0)
5932     S = S->getParent();
5933 
5934   DeclContext *DC = CurContext;
5935   if (D.getCXXScopeSpec().isInvalid())
5936     D.setInvalidType();
5937   else if (D.getCXXScopeSpec().isSet()) {
5938     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5939                                         UPPC_DeclarationQualifier))
5940       return nullptr;
5941 
5942     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5943     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5944     if (!DC || isa<EnumDecl>(DC)) {
5945       // If we could not compute the declaration context, it's because the
5946       // declaration context is dependent but does not refer to a class,
5947       // class template, or class template partial specialization. Complain
5948       // and return early, to avoid the coming semantic disaster.
5949       Diag(D.getIdentifierLoc(),
5950            diag::err_template_qualified_declarator_no_match)
5951         << D.getCXXScopeSpec().getScopeRep()
5952         << D.getCXXScopeSpec().getRange();
5953       return nullptr;
5954     }
5955     bool IsDependentContext = DC->isDependentContext();
5956 
5957     if (!IsDependentContext &&
5958         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5959       return nullptr;
5960 
5961     // If a class is incomplete, do not parse entities inside it.
5962     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5963       Diag(D.getIdentifierLoc(),
5964            diag::err_member_def_undefined_record)
5965         << Name << DC << D.getCXXScopeSpec().getRange();
5966       return nullptr;
5967     }
5968     if (!D.getDeclSpec().isFriendSpecified()) {
5969       if (diagnoseQualifiedDeclaration(
5970               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5971               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5972         if (DC->isRecord())
5973           return nullptr;
5974 
5975         D.setInvalidType();
5976       }
5977     }
5978 
5979     // Check whether we need to rebuild the type of the given
5980     // declaration in the current instantiation.
5981     if (EnteringContext && IsDependentContext &&
5982         TemplateParamLists.size() != 0) {
5983       ContextRAII SavedContext(*this, DC);
5984       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5985         D.setInvalidType();
5986     }
5987   }
5988 
5989   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5990   QualType R = TInfo->getType();
5991 
5992   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5993                                       UPPC_DeclarationType))
5994     D.setInvalidType();
5995 
5996   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5997                         forRedeclarationInCurContext());
5998 
5999   // See if this is a redefinition of a variable in the same scope.
6000   if (!D.getCXXScopeSpec().isSet()) {
6001     bool IsLinkageLookup = false;
6002     bool CreateBuiltins = false;
6003 
6004     // If the declaration we're planning to build will be a function
6005     // or object with linkage, then look for another declaration with
6006     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6007     //
6008     // If the declaration we're planning to build will be declared with
6009     // external linkage in the translation unit, create any builtin with
6010     // the same name.
6011     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6012       /* Do nothing*/;
6013     else if (CurContext->isFunctionOrMethod() &&
6014              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6015               R->isFunctionType())) {
6016       IsLinkageLookup = true;
6017       CreateBuiltins =
6018           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6019     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6020                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6021       CreateBuiltins = true;
6022 
6023     if (IsLinkageLookup) {
6024       Previous.clear(LookupRedeclarationWithLinkage);
6025       Previous.setRedeclarationKind(ForExternalRedeclaration);
6026     }
6027 
6028     LookupName(Previous, S, CreateBuiltins);
6029   } else { // Something like "int foo::x;"
6030     LookupQualifiedName(Previous, DC);
6031 
6032     // C++ [dcl.meaning]p1:
6033     //   When the declarator-id is qualified, the declaration shall refer to a
6034     //  previously declared member of the class or namespace to which the
6035     //  qualifier refers (or, in the case of a namespace, of an element of the
6036     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6037     //  thereof; [...]
6038     //
6039     // Note that we already checked the context above, and that we do not have
6040     // enough information to make sure that Previous contains the declaration
6041     // we want to match. For example, given:
6042     //
6043     //   class X {
6044     //     void f();
6045     //     void f(float);
6046     //   };
6047     //
6048     //   void X::f(int) { } // ill-formed
6049     //
6050     // In this case, Previous will point to the overload set
6051     // containing the two f's declared in X, but neither of them
6052     // matches.
6053 
6054     // C++ [dcl.meaning]p1:
6055     //   [...] the member shall not merely have been introduced by a
6056     //   using-declaration in the scope of the class or namespace nominated by
6057     //   the nested-name-specifier of the declarator-id.
6058     RemoveUsingDecls(Previous);
6059   }
6060 
6061   if (Previous.isSingleResult() &&
6062       Previous.getFoundDecl()->isTemplateParameter()) {
6063     // Maybe we will complain about the shadowed template parameter.
6064     if (!D.isInvalidType())
6065       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6066                                       Previous.getFoundDecl());
6067 
6068     // Just pretend that we didn't see the previous declaration.
6069     Previous.clear();
6070   }
6071 
6072   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6073     // Forget that the previous declaration is the injected-class-name.
6074     Previous.clear();
6075 
6076   // In C++, the previous declaration we find might be a tag type
6077   // (class or enum). In this case, the new declaration will hide the
6078   // tag type. Note that this applies to functions, function templates, and
6079   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6080   if (Previous.isSingleTagDecl() &&
6081       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6082       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6083     Previous.clear();
6084 
6085   // Check that there are no default arguments other than in the parameters
6086   // of a function declaration (C++ only).
6087   if (getLangOpts().CPlusPlus)
6088     CheckExtraCXXDefaultArguments(D);
6089 
6090   NamedDecl *New;
6091 
6092   bool AddToScope = true;
6093   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6094     if (TemplateParamLists.size()) {
6095       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6096       return nullptr;
6097     }
6098 
6099     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6100   } else if (R->isFunctionType()) {
6101     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6102                                   TemplateParamLists,
6103                                   AddToScope);
6104   } else {
6105     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6106                                   AddToScope);
6107   }
6108 
6109   if (!New)
6110     return nullptr;
6111 
6112   // If this has an identifier and is not a function template specialization,
6113   // add it to the scope stack.
6114   if (New->getDeclName() && AddToScope)
6115     PushOnScopeChains(New, S);
6116 
6117   if (isInOpenMPDeclareTargetContext())
6118     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6119 
6120   return New;
6121 }
6122 
6123 /// Helper method to turn variable array types into constant array
6124 /// types in certain situations which would otherwise be errors (for
6125 /// GCC compatibility).
6126 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6127                                                     ASTContext &Context,
6128                                                     bool &SizeIsNegative,
6129                                                     llvm::APSInt &Oversized) {
6130   // This method tries to turn a variable array into a constant
6131   // array even when the size isn't an ICE.  This is necessary
6132   // for compatibility with code that depends on gcc's buggy
6133   // constant expression folding, like struct {char x[(int)(char*)2];}
6134   SizeIsNegative = false;
6135   Oversized = 0;
6136 
6137   if (T->isDependentType())
6138     return QualType();
6139 
6140   QualifierCollector Qs;
6141   const Type *Ty = Qs.strip(T);
6142 
6143   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6144     QualType Pointee = PTy->getPointeeType();
6145     QualType FixedType =
6146         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6147                                             Oversized);
6148     if (FixedType.isNull()) return FixedType;
6149     FixedType = Context.getPointerType(FixedType);
6150     return Qs.apply(Context, FixedType);
6151   }
6152   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6153     QualType Inner = PTy->getInnerType();
6154     QualType FixedType =
6155         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6156                                             Oversized);
6157     if (FixedType.isNull()) return FixedType;
6158     FixedType = Context.getParenType(FixedType);
6159     return Qs.apply(Context, FixedType);
6160   }
6161 
6162   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6163   if (!VLATy)
6164     return QualType();
6165 
6166   QualType ElemTy = VLATy->getElementType();
6167   if (ElemTy->isVariablyModifiedType()) {
6168     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6169                                                  SizeIsNegative, Oversized);
6170     if (ElemTy.isNull())
6171       return QualType();
6172   }
6173 
6174   Expr::EvalResult Result;
6175   if (!VLATy->getSizeExpr() ||
6176       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6177     return QualType();
6178 
6179   llvm::APSInt Res = Result.Val.getInt();
6180 
6181   // Check whether the array size is negative.
6182   if (Res.isSigned() && Res.isNegative()) {
6183     SizeIsNegative = true;
6184     return QualType();
6185   }
6186 
6187   // Check whether the array is too large to be addressed.
6188   unsigned ActiveSizeBits =
6189       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6190        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6191           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6192           : Res.getActiveBits();
6193   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6194     Oversized = Res;
6195     return QualType();
6196   }
6197 
6198   QualType FoldedArrayType = Context.getConstantArrayType(
6199       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6200   return Qs.apply(Context, FoldedArrayType);
6201 }
6202 
6203 static void
6204 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6205   SrcTL = SrcTL.getUnqualifiedLoc();
6206   DstTL = DstTL.getUnqualifiedLoc();
6207   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6208     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6209     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6210                                       DstPTL.getPointeeLoc());
6211     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6212     return;
6213   }
6214   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6215     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6216     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6217                                       DstPTL.getInnerLoc());
6218     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6219     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6220     return;
6221   }
6222   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6223   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6224   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6225   TypeLoc DstElemTL = DstATL.getElementLoc();
6226   if (VariableArrayTypeLoc SrcElemATL =
6227           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6228     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6229     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6230   } else {
6231     DstElemTL.initializeFullCopy(SrcElemTL);
6232   }
6233   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6234   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6235   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6236 }
6237 
6238 /// Helper method to turn variable array types into constant array
6239 /// types in certain situations which would otherwise be errors (for
6240 /// GCC compatibility).
6241 static TypeSourceInfo*
6242 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6243                                               ASTContext &Context,
6244                                               bool &SizeIsNegative,
6245                                               llvm::APSInt &Oversized) {
6246   QualType FixedTy
6247     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6248                                           SizeIsNegative, Oversized);
6249   if (FixedTy.isNull())
6250     return nullptr;
6251   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6252   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6253                                     FixedTInfo->getTypeLoc());
6254   return FixedTInfo;
6255 }
6256 
6257 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6258 /// true if we were successful.
6259 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6260                                            QualType &T, SourceLocation Loc,
6261                                            unsigned FailedFoldDiagID) {
6262   bool SizeIsNegative;
6263   llvm::APSInt Oversized;
6264   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6265       TInfo, Context, SizeIsNegative, Oversized);
6266   if (FixedTInfo) {
6267     Diag(Loc, diag::ext_vla_folded_to_constant);
6268     TInfo = FixedTInfo;
6269     T = FixedTInfo->getType();
6270     return true;
6271   }
6272 
6273   if (SizeIsNegative)
6274     Diag(Loc, diag::err_typecheck_negative_array_size);
6275   else if (Oversized.getBoolValue())
6276     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6277   else if (FailedFoldDiagID)
6278     Diag(Loc, FailedFoldDiagID);
6279   return false;
6280 }
6281 
6282 /// Register the given locally-scoped extern "C" declaration so
6283 /// that it can be found later for redeclarations. We include any extern "C"
6284 /// declaration that is not visible in the translation unit here, not just
6285 /// function-scope declarations.
6286 void
6287 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6288   if (!getLangOpts().CPlusPlus &&
6289       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6290     // Don't need to track declarations in the TU in C.
6291     return;
6292 
6293   // Note that we have a locally-scoped external with this name.
6294   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6295 }
6296 
6297 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6298   // FIXME: We can have multiple results via __attribute__((overloadable)).
6299   auto Result = Context.getExternCContextDecl()->lookup(Name);
6300   return Result.empty() ? nullptr : *Result.begin();
6301 }
6302 
6303 /// Diagnose function specifiers on a declaration of an identifier that
6304 /// does not identify a function.
6305 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6306   // FIXME: We should probably indicate the identifier in question to avoid
6307   // confusion for constructs like "virtual int a(), b;"
6308   if (DS.isVirtualSpecified())
6309     Diag(DS.getVirtualSpecLoc(),
6310          diag::err_virtual_non_function);
6311 
6312   if (DS.hasExplicitSpecifier())
6313     Diag(DS.getExplicitSpecLoc(),
6314          diag::err_explicit_non_function);
6315 
6316   if (DS.isNoreturnSpecified())
6317     Diag(DS.getNoreturnSpecLoc(),
6318          diag::err_noreturn_non_function);
6319 }
6320 
6321 NamedDecl*
6322 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6323                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6324   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6325   if (D.getCXXScopeSpec().isSet()) {
6326     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6327       << D.getCXXScopeSpec().getRange();
6328     D.setInvalidType();
6329     // Pretend we didn't see the scope specifier.
6330     DC = CurContext;
6331     Previous.clear();
6332   }
6333 
6334   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6335 
6336   if (D.getDeclSpec().isInlineSpecified())
6337     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6338         << getLangOpts().CPlusPlus17;
6339   if (D.getDeclSpec().hasConstexprSpecifier())
6340     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6341         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6342 
6343   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6344     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6345       Diag(D.getName().StartLocation,
6346            diag::err_deduction_guide_invalid_specifier)
6347           << "typedef";
6348     else
6349       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6350           << D.getName().getSourceRange();
6351     return nullptr;
6352   }
6353 
6354   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6355   if (!NewTD) return nullptr;
6356 
6357   // Handle attributes prior to checking for duplicates in MergeVarDecl
6358   ProcessDeclAttributes(S, NewTD, D);
6359 
6360   CheckTypedefForVariablyModifiedType(S, NewTD);
6361 
6362   bool Redeclaration = D.isRedeclaration();
6363   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6364   D.setRedeclaration(Redeclaration);
6365   return ND;
6366 }
6367 
6368 void
6369 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6370   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6371   // then it shall have block scope.
6372   // Note that variably modified types must be fixed before merging the decl so
6373   // that redeclarations will match.
6374   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6375   QualType T = TInfo->getType();
6376   if (T->isVariablyModifiedType()) {
6377     setFunctionHasBranchProtectedScope();
6378 
6379     if (S->getFnParent() == nullptr) {
6380       bool SizeIsNegative;
6381       llvm::APSInt Oversized;
6382       TypeSourceInfo *FixedTInfo =
6383         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6384                                                       SizeIsNegative,
6385                                                       Oversized);
6386       if (FixedTInfo) {
6387         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6388         NewTD->setTypeSourceInfo(FixedTInfo);
6389       } else {
6390         if (SizeIsNegative)
6391           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6392         else if (T->isVariableArrayType())
6393           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6394         else if (Oversized.getBoolValue())
6395           Diag(NewTD->getLocation(), diag::err_array_too_large)
6396             << toString(Oversized, 10);
6397         else
6398           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6399         NewTD->setInvalidDecl();
6400       }
6401     }
6402   }
6403 }
6404 
6405 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6406 /// declares a typedef-name, either using the 'typedef' type specifier or via
6407 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6408 NamedDecl*
6409 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6410                            LookupResult &Previous, bool &Redeclaration) {
6411 
6412   // Find the shadowed declaration before filtering for scope.
6413   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6414 
6415   // Merge the decl with the existing one if appropriate. If the decl is
6416   // in an outer scope, it isn't the same thing.
6417   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6418                        /*AllowInlineNamespace*/false);
6419   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6420   if (!Previous.empty()) {
6421     Redeclaration = true;
6422     MergeTypedefNameDecl(S, NewTD, Previous);
6423   } else {
6424     inferGslPointerAttribute(NewTD);
6425   }
6426 
6427   if (ShadowedDecl && !Redeclaration)
6428     CheckShadow(NewTD, ShadowedDecl, Previous);
6429 
6430   // If this is the C FILE type, notify the AST context.
6431   if (IdentifierInfo *II = NewTD->getIdentifier())
6432     if (!NewTD->isInvalidDecl() &&
6433         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6434       if (II->isStr("FILE"))
6435         Context.setFILEDecl(NewTD);
6436       else if (II->isStr("jmp_buf"))
6437         Context.setjmp_bufDecl(NewTD);
6438       else if (II->isStr("sigjmp_buf"))
6439         Context.setsigjmp_bufDecl(NewTD);
6440       else if (II->isStr("ucontext_t"))
6441         Context.setucontext_tDecl(NewTD);
6442     }
6443 
6444   return NewTD;
6445 }
6446 
6447 /// Determines whether the given declaration is an out-of-scope
6448 /// previous declaration.
6449 ///
6450 /// This routine should be invoked when name lookup has found a
6451 /// previous declaration (PrevDecl) that is not in the scope where a
6452 /// new declaration by the same name is being introduced. If the new
6453 /// declaration occurs in a local scope, previous declarations with
6454 /// linkage may still be considered previous declarations (C99
6455 /// 6.2.2p4-5, C++ [basic.link]p6).
6456 ///
6457 /// \param PrevDecl the previous declaration found by name
6458 /// lookup
6459 ///
6460 /// \param DC the context in which the new declaration is being
6461 /// declared.
6462 ///
6463 /// \returns true if PrevDecl is an out-of-scope previous declaration
6464 /// for a new delcaration with the same name.
6465 static bool
6466 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6467                                 ASTContext &Context) {
6468   if (!PrevDecl)
6469     return false;
6470 
6471   if (!PrevDecl->hasLinkage())
6472     return false;
6473 
6474   if (Context.getLangOpts().CPlusPlus) {
6475     // C++ [basic.link]p6:
6476     //   If there is a visible declaration of an entity with linkage
6477     //   having the same name and type, ignoring entities declared
6478     //   outside the innermost enclosing namespace scope, the block
6479     //   scope declaration declares that same entity and receives the
6480     //   linkage of the previous declaration.
6481     DeclContext *OuterContext = DC->getRedeclContext();
6482     if (!OuterContext->isFunctionOrMethod())
6483       // This rule only applies to block-scope declarations.
6484       return false;
6485 
6486     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6487     if (PrevOuterContext->isRecord())
6488       // We found a member function: ignore it.
6489       return false;
6490 
6491     // Find the innermost enclosing namespace for the new and
6492     // previous declarations.
6493     OuterContext = OuterContext->getEnclosingNamespaceContext();
6494     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6495 
6496     // The previous declaration is in a different namespace, so it
6497     // isn't the same function.
6498     if (!OuterContext->Equals(PrevOuterContext))
6499       return false;
6500   }
6501 
6502   return true;
6503 }
6504 
6505 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6506   CXXScopeSpec &SS = D.getCXXScopeSpec();
6507   if (!SS.isSet()) return;
6508   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6509 }
6510 
6511 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6512   QualType type = decl->getType();
6513   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6514   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6515     // Various kinds of declaration aren't allowed to be __autoreleasing.
6516     unsigned kind = -1U;
6517     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6518       if (var->hasAttr<BlocksAttr>())
6519         kind = 0; // __block
6520       else if (!var->hasLocalStorage())
6521         kind = 1; // global
6522     } else if (isa<ObjCIvarDecl>(decl)) {
6523       kind = 3; // ivar
6524     } else if (isa<FieldDecl>(decl)) {
6525       kind = 2; // field
6526     }
6527 
6528     if (kind != -1U) {
6529       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6530         << kind;
6531     }
6532   } else if (lifetime == Qualifiers::OCL_None) {
6533     // Try to infer lifetime.
6534     if (!type->isObjCLifetimeType())
6535       return false;
6536 
6537     lifetime = type->getObjCARCImplicitLifetime();
6538     type = Context.getLifetimeQualifiedType(type, lifetime);
6539     decl->setType(type);
6540   }
6541 
6542   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6543     // Thread-local variables cannot have lifetime.
6544     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6545         var->getTLSKind()) {
6546       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6547         << var->getType();
6548       return true;
6549     }
6550   }
6551 
6552   return false;
6553 }
6554 
6555 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6556   if (Decl->getType().hasAddressSpace())
6557     return;
6558   if (Decl->getType()->isDependentType())
6559     return;
6560   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6561     QualType Type = Var->getType();
6562     if (Type->isSamplerT() || Type->isVoidType())
6563       return;
6564     LangAS ImplAS = LangAS::opencl_private;
6565     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6566     // __opencl_c_program_scope_global_variables feature, the address space
6567     // for a variable at program scope or a static or extern variable inside
6568     // a function are inferred to be __global.
6569     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6570         Var->hasGlobalStorage())
6571       ImplAS = LangAS::opencl_global;
6572     // If the original type from a decayed type is an array type and that array
6573     // type has no address space yet, deduce it now.
6574     if (auto DT = dyn_cast<DecayedType>(Type)) {
6575       auto OrigTy = DT->getOriginalType();
6576       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6577         // Add the address space to the original array type and then propagate
6578         // that to the element type through `getAsArrayType`.
6579         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6580         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6581         // Re-generate the decayed type.
6582         Type = Context.getDecayedType(OrigTy);
6583       }
6584     }
6585     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6586     // Apply any qualifiers (including address space) from the array type to
6587     // the element type. This implements C99 6.7.3p8: "If the specification of
6588     // an array type includes any type qualifiers, the element type is so
6589     // qualified, not the array type."
6590     if (Type->isArrayType())
6591       Type = QualType(Context.getAsArrayType(Type), 0);
6592     Decl->setType(Type);
6593   }
6594 }
6595 
6596 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6597   // Ensure that an auto decl is deduced otherwise the checks below might cache
6598   // the wrong linkage.
6599   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6600 
6601   // 'weak' only applies to declarations with external linkage.
6602   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6603     if (!ND.isExternallyVisible()) {
6604       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6605       ND.dropAttr<WeakAttr>();
6606     }
6607   }
6608   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6609     if (ND.isExternallyVisible()) {
6610       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6611       ND.dropAttr<WeakRefAttr>();
6612       ND.dropAttr<AliasAttr>();
6613     }
6614   }
6615 
6616   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6617     if (VD->hasInit()) {
6618       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6619         assert(VD->isThisDeclarationADefinition() &&
6620                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6621         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6622         VD->dropAttr<AliasAttr>();
6623       }
6624     }
6625   }
6626 
6627   // 'selectany' only applies to externally visible variable declarations.
6628   // It does not apply to functions.
6629   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6630     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6631       S.Diag(Attr->getLocation(),
6632              diag::err_attribute_selectany_non_extern_data);
6633       ND.dropAttr<SelectAnyAttr>();
6634     }
6635   }
6636 
6637   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6638     auto *VD = dyn_cast<VarDecl>(&ND);
6639     bool IsAnonymousNS = false;
6640     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6641     if (VD) {
6642       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6643       while (NS && !IsAnonymousNS) {
6644         IsAnonymousNS = NS->isAnonymousNamespace();
6645         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6646       }
6647     }
6648     // dll attributes require external linkage. Static locals may have external
6649     // linkage but still cannot be explicitly imported or exported.
6650     // In Microsoft mode, a variable defined in anonymous namespace must have
6651     // external linkage in order to be exported.
6652     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6653     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6654         (!AnonNSInMicrosoftMode &&
6655          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6656       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6657         << &ND << Attr;
6658       ND.setInvalidDecl();
6659     }
6660   }
6661 
6662   // Check the attributes on the function type, if any.
6663   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6664     // Don't declare this variable in the second operand of the for-statement;
6665     // GCC miscompiles that by ending its lifetime before evaluating the
6666     // third operand. See gcc.gnu.org/PR86769.
6667     AttributedTypeLoc ATL;
6668     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6669          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6670          TL = ATL.getModifiedLoc()) {
6671       // The [[lifetimebound]] attribute can be applied to the implicit object
6672       // parameter of a non-static member function (other than a ctor or dtor)
6673       // by applying it to the function type.
6674       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6675         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6676         if (!MD || MD->isStatic()) {
6677           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6678               << !MD << A->getRange();
6679         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6680           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6681               << isa<CXXDestructorDecl>(MD) << A->getRange();
6682         }
6683       }
6684     }
6685   }
6686 }
6687 
6688 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6689                                            NamedDecl *NewDecl,
6690                                            bool IsSpecialization,
6691                                            bool IsDefinition) {
6692   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6693     return;
6694 
6695   bool IsTemplate = false;
6696   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6697     OldDecl = OldTD->getTemplatedDecl();
6698     IsTemplate = true;
6699     if (!IsSpecialization)
6700       IsDefinition = false;
6701   }
6702   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6703     NewDecl = NewTD->getTemplatedDecl();
6704     IsTemplate = true;
6705   }
6706 
6707   if (!OldDecl || !NewDecl)
6708     return;
6709 
6710   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6711   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6712   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6713   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6714 
6715   // dllimport and dllexport are inheritable attributes so we have to exclude
6716   // inherited attribute instances.
6717   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6718                     (NewExportAttr && !NewExportAttr->isInherited());
6719 
6720   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6721   // the only exception being explicit specializations.
6722   // Implicitly generated declarations are also excluded for now because there
6723   // is no other way to switch these to use dllimport or dllexport.
6724   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6725 
6726   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6727     // Allow with a warning for free functions and global variables.
6728     bool JustWarn = false;
6729     if (!OldDecl->isCXXClassMember()) {
6730       auto *VD = dyn_cast<VarDecl>(OldDecl);
6731       if (VD && !VD->getDescribedVarTemplate())
6732         JustWarn = true;
6733       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6734       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6735         JustWarn = true;
6736     }
6737 
6738     // We cannot change a declaration that's been used because IR has already
6739     // been emitted. Dllimported functions will still work though (modulo
6740     // address equality) as they can use the thunk.
6741     if (OldDecl->isUsed())
6742       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6743         JustWarn = false;
6744 
6745     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6746                                : diag::err_attribute_dll_redeclaration;
6747     S.Diag(NewDecl->getLocation(), DiagID)
6748         << NewDecl
6749         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6750     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6751     if (!JustWarn) {
6752       NewDecl->setInvalidDecl();
6753       return;
6754     }
6755   }
6756 
6757   // A redeclaration is not allowed to drop a dllimport attribute, the only
6758   // exceptions being inline function definitions (except for function
6759   // templates), local extern declarations, qualified friend declarations or
6760   // special MSVC extension: in the last case, the declaration is treated as if
6761   // it were marked dllexport.
6762   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6763   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6764   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6765     // Ignore static data because out-of-line definitions are diagnosed
6766     // separately.
6767     IsStaticDataMember = VD->isStaticDataMember();
6768     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6769                    VarDecl::DeclarationOnly;
6770   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6771     IsInline = FD->isInlined();
6772     IsQualifiedFriend = FD->getQualifier() &&
6773                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6774   }
6775 
6776   if (OldImportAttr && !HasNewAttr &&
6777       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6778       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6779     if (IsMicrosoftABI && IsDefinition) {
6780       S.Diag(NewDecl->getLocation(),
6781              diag::warn_redeclaration_without_import_attribute)
6782           << NewDecl;
6783       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6784       NewDecl->dropAttr<DLLImportAttr>();
6785       NewDecl->addAttr(
6786           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6787     } else {
6788       S.Diag(NewDecl->getLocation(),
6789              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6790           << NewDecl << OldImportAttr;
6791       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6792       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6793       OldDecl->dropAttr<DLLImportAttr>();
6794       NewDecl->dropAttr<DLLImportAttr>();
6795     }
6796   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6797     // In MinGW, seeing a function declared inline drops the dllimport
6798     // attribute.
6799     OldDecl->dropAttr<DLLImportAttr>();
6800     NewDecl->dropAttr<DLLImportAttr>();
6801     S.Diag(NewDecl->getLocation(),
6802            diag::warn_dllimport_dropped_from_inline_function)
6803         << NewDecl << OldImportAttr;
6804   }
6805 
6806   // A specialization of a class template member function is processed here
6807   // since it's a redeclaration. If the parent class is dllexport, the
6808   // specialization inherits that attribute. This doesn't happen automatically
6809   // since the parent class isn't instantiated until later.
6810   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6811     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6812         !NewImportAttr && !NewExportAttr) {
6813       if (const DLLExportAttr *ParentExportAttr =
6814               MD->getParent()->getAttr<DLLExportAttr>()) {
6815         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6816         NewAttr->setInherited(true);
6817         NewDecl->addAttr(NewAttr);
6818       }
6819     }
6820   }
6821 }
6822 
6823 /// Given that we are within the definition of the given function,
6824 /// will that definition behave like C99's 'inline', where the
6825 /// definition is discarded except for optimization purposes?
6826 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6827   // Try to avoid calling GetGVALinkageForFunction.
6828 
6829   // All cases of this require the 'inline' keyword.
6830   if (!FD->isInlined()) return false;
6831 
6832   // This is only possible in C++ with the gnu_inline attribute.
6833   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6834     return false;
6835 
6836   // Okay, go ahead and call the relatively-more-expensive function.
6837   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6838 }
6839 
6840 /// Determine whether a variable is extern "C" prior to attaching
6841 /// an initializer. We can't just call isExternC() here, because that
6842 /// will also compute and cache whether the declaration is externally
6843 /// visible, which might change when we attach the initializer.
6844 ///
6845 /// This can only be used if the declaration is known to not be a
6846 /// redeclaration of an internal linkage declaration.
6847 ///
6848 /// For instance:
6849 ///
6850 ///   auto x = []{};
6851 ///
6852 /// Attaching the initializer here makes this declaration not externally
6853 /// visible, because its type has internal linkage.
6854 ///
6855 /// FIXME: This is a hack.
6856 template<typename T>
6857 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6858   if (S.getLangOpts().CPlusPlus) {
6859     // In C++, the overloadable attribute negates the effects of extern "C".
6860     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6861       return false;
6862 
6863     // So do CUDA's host/device attributes.
6864     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6865                                  D->template hasAttr<CUDAHostAttr>()))
6866       return false;
6867   }
6868   return D->isExternC();
6869 }
6870 
6871 static bool shouldConsiderLinkage(const VarDecl *VD) {
6872   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6873   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6874       isa<OMPDeclareMapperDecl>(DC))
6875     return VD->hasExternalStorage();
6876   if (DC->isFileContext())
6877     return true;
6878   if (DC->isRecord())
6879     return false;
6880   if (isa<RequiresExprBodyDecl>(DC))
6881     return false;
6882   llvm_unreachable("Unexpected context");
6883 }
6884 
6885 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6886   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6887   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6888       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6889     return true;
6890   if (DC->isRecord())
6891     return false;
6892   llvm_unreachable("Unexpected context");
6893 }
6894 
6895 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6896                           ParsedAttr::Kind Kind) {
6897   // Check decl attributes on the DeclSpec.
6898   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6899     return true;
6900 
6901   // Walk the declarator structure, checking decl attributes that were in a type
6902   // position to the decl itself.
6903   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6904     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6905       return true;
6906   }
6907 
6908   // Finally, check attributes on the decl itself.
6909   return PD.getAttributes().hasAttribute(Kind);
6910 }
6911 
6912 /// Adjust the \c DeclContext for a function or variable that might be a
6913 /// function-local external declaration.
6914 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6915   if (!DC->isFunctionOrMethod())
6916     return false;
6917 
6918   // If this is a local extern function or variable declared within a function
6919   // template, don't add it into the enclosing namespace scope until it is
6920   // instantiated; it might have a dependent type right now.
6921   if (DC->isDependentContext())
6922     return true;
6923 
6924   // C++11 [basic.link]p7:
6925   //   When a block scope declaration of an entity with linkage is not found to
6926   //   refer to some other declaration, then that entity is a member of the
6927   //   innermost enclosing namespace.
6928   //
6929   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6930   // semantically-enclosing namespace, not a lexically-enclosing one.
6931   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6932     DC = DC->getParent();
6933   return true;
6934 }
6935 
6936 /// Returns true if given declaration has external C language linkage.
6937 static bool isDeclExternC(const Decl *D) {
6938   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6939     return FD->isExternC();
6940   if (const auto *VD = dyn_cast<VarDecl>(D))
6941     return VD->isExternC();
6942 
6943   llvm_unreachable("Unknown type of decl!");
6944 }
6945 
6946 /// Returns true if there hasn't been any invalid type diagnosed.
6947 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6948   DeclContext *DC = NewVD->getDeclContext();
6949   QualType R = NewVD->getType();
6950 
6951   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6952   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6953   // argument.
6954   if (R->isImageType() || R->isPipeType()) {
6955     Se.Diag(NewVD->getLocation(),
6956             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6957         << R;
6958     NewVD->setInvalidDecl();
6959     return false;
6960   }
6961 
6962   // OpenCL v1.2 s6.9.r:
6963   // The event type cannot be used to declare a program scope variable.
6964   // OpenCL v2.0 s6.9.q:
6965   // The clk_event_t and reserve_id_t types cannot be declared in program
6966   // scope.
6967   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6968     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6969       Se.Diag(NewVD->getLocation(),
6970               diag::err_invalid_type_for_program_scope_var)
6971           << R;
6972       NewVD->setInvalidDecl();
6973       return false;
6974     }
6975   }
6976 
6977   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6978   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6979                                                Se.getLangOpts())) {
6980     QualType NR = R.getCanonicalType();
6981     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6982            NR->isReferenceType()) {
6983       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6984           NR->isFunctionReferenceType()) {
6985         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6986             << NR->isReferenceType();
6987         NewVD->setInvalidDecl();
6988         return false;
6989       }
6990       NR = NR->getPointeeType();
6991     }
6992   }
6993 
6994   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6995                                                Se.getLangOpts())) {
6996     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6997     // half array type (unless the cl_khr_fp16 extension is enabled).
6998     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6999       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7000       NewVD->setInvalidDecl();
7001       return false;
7002     }
7003   }
7004 
7005   // OpenCL v1.2 s6.9.r:
7006   // The event type cannot be used with the __local, __constant and __global
7007   // address space qualifiers.
7008   if (R->isEventT()) {
7009     if (R.getAddressSpace() != LangAS::opencl_private) {
7010       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7011       NewVD->setInvalidDecl();
7012       return false;
7013     }
7014   }
7015 
7016   if (R->isSamplerT()) {
7017     // OpenCL v1.2 s6.9.b p4:
7018     // The sampler type cannot be used with the __local and __global address
7019     // space qualifiers.
7020     if (R.getAddressSpace() == LangAS::opencl_local ||
7021         R.getAddressSpace() == LangAS::opencl_global) {
7022       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7023       NewVD->setInvalidDecl();
7024     }
7025 
7026     // OpenCL v1.2 s6.12.14.1:
7027     // A global sampler must be declared with either the constant address
7028     // space qualifier or with the const qualifier.
7029     if (DC->isTranslationUnit() &&
7030         !(R.getAddressSpace() == LangAS::opencl_constant ||
7031           R.isConstQualified())) {
7032       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7033       NewVD->setInvalidDecl();
7034     }
7035     if (NewVD->isInvalidDecl())
7036       return false;
7037   }
7038 
7039   return true;
7040 }
7041 
7042 template <typename AttrTy>
7043 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7044   const TypedefNameDecl *TND = TT->getDecl();
7045   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7046     AttrTy *Clone = Attribute->clone(S.Context);
7047     Clone->setInherited(true);
7048     D->addAttr(Clone);
7049   }
7050 }
7051 
7052 NamedDecl *Sema::ActOnVariableDeclarator(
7053     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7054     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7055     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7056   QualType R = TInfo->getType();
7057   DeclarationName Name = GetNameForDeclarator(D).getName();
7058 
7059   IdentifierInfo *II = Name.getAsIdentifierInfo();
7060 
7061   if (D.isDecompositionDeclarator()) {
7062     // Take the name of the first declarator as our name for diagnostic
7063     // purposes.
7064     auto &Decomp = D.getDecompositionDeclarator();
7065     if (!Decomp.bindings().empty()) {
7066       II = Decomp.bindings()[0].Name;
7067       Name = II;
7068     }
7069   } else if (!II) {
7070     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7071     return nullptr;
7072   }
7073 
7074 
7075   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7076   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7077 
7078   // dllimport globals without explicit storage class are treated as extern. We
7079   // have to change the storage class this early to get the right DeclContext.
7080   if (SC == SC_None && !DC->isRecord() &&
7081       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7082       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7083     SC = SC_Extern;
7084 
7085   DeclContext *OriginalDC = DC;
7086   bool IsLocalExternDecl = SC == SC_Extern &&
7087                            adjustContextForLocalExternDecl(DC);
7088 
7089   if (SCSpec == DeclSpec::SCS_mutable) {
7090     // mutable can only appear on non-static class members, so it's always
7091     // an error here
7092     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7093     D.setInvalidType();
7094     SC = SC_None;
7095   }
7096 
7097   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7098       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7099                               D.getDeclSpec().getStorageClassSpecLoc())) {
7100     // In C++11, the 'register' storage class specifier is deprecated.
7101     // Suppress the warning in system macros, it's used in macros in some
7102     // popular C system headers, such as in glibc's htonl() macro.
7103     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7104          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7105                                    : diag::warn_deprecated_register)
7106       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7107   }
7108 
7109   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7110 
7111   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7112     // C99 6.9p2: The storage-class specifiers auto and register shall not
7113     // appear in the declaration specifiers in an external declaration.
7114     // Global Register+Asm is a GNU extension we support.
7115     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7116       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7117       D.setInvalidType();
7118     }
7119   }
7120 
7121   // If this variable has a VLA type and an initializer, try to
7122   // fold to a constant-sized type. This is otherwise invalid.
7123   if (D.hasInitializer() && R->isVariableArrayType())
7124     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7125                                     /*DiagID=*/0);
7126 
7127   bool IsMemberSpecialization = false;
7128   bool IsVariableTemplateSpecialization = false;
7129   bool IsPartialSpecialization = false;
7130   bool IsVariableTemplate = false;
7131   VarDecl *NewVD = nullptr;
7132   VarTemplateDecl *NewTemplate = nullptr;
7133   TemplateParameterList *TemplateParams = nullptr;
7134   if (!getLangOpts().CPlusPlus) {
7135     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7136                             II, R, TInfo, SC);
7137 
7138     if (R->getContainedDeducedType())
7139       ParsingInitForAutoVars.insert(NewVD);
7140 
7141     if (D.isInvalidType())
7142       NewVD->setInvalidDecl();
7143 
7144     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7145         NewVD->hasLocalStorage())
7146       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7147                             NTCUC_AutoVar, NTCUK_Destruct);
7148   } else {
7149     bool Invalid = false;
7150 
7151     if (DC->isRecord() && !CurContext->isRecord()) {
7152       // This is an out-of-line definition of a static data member.
7153       switch (SC) {
7154       case SC_None:
7155         break;
7156       case SC_Static:
7157         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7158              diag::err_static_out_of_line)
7159           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7160         break;
7161       case SC_Auto:
7162       case SC_Register:
7163       case SC_Extern:
7164         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7165         // to names of variables declared in a block or to function parameters.
7166         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7167         // of class members
7168 
7169         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7170              diag::err_storage_class_for_static_member)
7171           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7172         break;
7173       case SC_PrivateExtern:
7174         llvm_unreachable("C storage class in c++!");
7175       }
7176     }
7177 
7178     if (SC == SC_Static && CurContext->isRecord()) {
7179       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7180         // Walk up the enclosing DeclContexts to check for any that are
7181         // incompatible with static data members.
7182         const DeclContext *FunctionOrMethod = nullptr;
7183         const CXXRecordDecl *AnonStruct = nullptr;
7184         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7185           if (Ctxt->isFunctionOrMethod()) {
7186             FunctionOrMethod = Ctxt;
7187             break;
7188           }
7189           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7190           if (ParentDecl && !ParentDecl->getDeclName()) {
7191             AnonStruct = ParentDecl;
7192             break;
7193           }
7194         }
7195         if (FunctionOrMethod) {
7196           // C++ [class.static.data]p5: A local class shall not have static data
7197           // members.
7198           Diag(D.getIdentifierLoc(),
7199                diag::err_static_data_member_not_allowed_in_local_class)
7200             << Name << RD->getDeclName() << RD->getTagKind();
7201         } else if (AnonStruct) {
7202           // C++ [class.static.data]p4: Unnamed classes and classes contained
7203           // directly or indirectly within unnamed classes shall not contain
7204           // static data members.
7205           Diag(D.getIdentifierLoc(),
7206                diag::err_static_data_member_not_allowed_in_anon_struct)
7207             << Name << AnonStruct->getTagKind();
7208           Invalid = true;
7209         } else if (RD->isUnion()) {
7210           // C++98 [class.union]p1: If a union contains a static data member,
7211           // the program is ill-formed. C++11 drops this restriction.
7212           Diag(D.getIdentifierLoc(),
7213                getLangOpts().CPlusPlus11
7214                  ? diag::warn_cxx98_compat_static_data_member_in_union
7215                  : diag::ext_static_data_member_in_union) << Name;
7216         }
7217       }
7218     }
7219 
7220     // Match up the template parameter lists with the scope specifier, then
7221     // determine whether we have a template or a template specialization.
7222     bool InvalidScope = false;
7223     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7224         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7225         D.getCXXScopeSpec(),
7226         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7227             ? D.getName().TemplateId
7228             : nullptr,
7229         TemplateParamLists,
7230         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7231     Invalid |= InvalidScope;
7232 
7233     if (TemplateParams) {
7234       if (!TemplateParams->size() &&
7235           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7236         // There is an extraneous 'template<>' for this variable. Complain
7237         // about it, but allow the declaration of the variable.
7238         Diag(TemplateParams->getTemplateLoc(),
7239              diag::err_template_variable_noparams)
7240           << II
7241           << SourceRange(TemplateParams->getTemplateLoc(),
7242                          TemplateParams->getRAngleLoc());
7243         TemplateParams = nullptr;
7244       } else {
7245         // Check that we can declare a template here.
7246         if (CheckTemplateDeclScope(S, TemplateParams))
7247           return nullptr;
7248 
7249         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7250           // This is an explicit specialization or a partial specialization.
7251           IsVariableTemplateSpecialization = true;
7252           IsPartialSpecialization = TemplateParams->size() > 0;
7253         } else { // if (TemplateParams->size() > 0)
7254           // This is a template declaration.
7255           IsVariableTemplate = true;
7256 
7257           // Only C++1y supports variable templates (N3651).
7258           Diag(D.getIdentifierLoc(),
7259                getLangOpts().CPlusPlus14
7260                    ? diag::warn_cxx11_compat_variable_template
7261                    : diag::ext_variable_template);
7262         }
7263       }
7264     } else {
7265       // Check that we can declare a member specialization here.
7266       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7267           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7268         return nullptr;
7269       assert((Invalid ||
7270               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7271              "should have a 'template<>' for this decl");
7272     }
7273 
7274     if (IsVariableTemplateSpecialization) {
7275       SourceLocation TemplateKWLoc =
7276           TemplateParamLists.size() > 0
7277               ? TemplateParamLists[0]->getTemplateLoc()
7278               : SourceLocation();
7279       DeclResult Res = ActOnVarTemplateSpecialization(
7280           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7281           IsPartialSpecialization);
7282       if (Res.isInvalid())
7283         return nullptr;
7284       NewVD = cast<VarDecl>(Res.get());
7285       AddToScope = false;
7286     } else if (D.isDecompositionDeclarator()) {
7287       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7288                                         D.getIdentifierLoc(), R, TInfo, SC,
7289                                         Bindings);
7290     } else
7291       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7292                               D.getIdentifierLoc(), II, R, TInfo, SC);
7293 
7294     // If this is supposed to be a variable template, create it as such.
7295     if (IsVariableTemplate) {
7296       NewTemplate =
7297           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7298                                   TemplateParams, NewVD);
7299       NewVD->setDescribedVarTemplate(NewTemplate);
7300     }
7301 
7302     // If this decl has an auto type in need of deduction, make a note of the
7303     // Decl so we can diagnose uses of it in its own initializer.
7304     if (R->getContainedDeducedType())
7305       ParsingInitForAutoVars.insert(NewVD);
7306 
7307     if (D.isInvalidType() || Invalid) {
7308       NewVD->setInvalidDecl();
7309       if (NewTemplate)
7310         NewTemplate->setInvalidDecl();
7311     }
7312 
7313     SetNestedNameSpecifier(*this, NewVD, D);
7314 
7315     // If we have any template parameter lists that don't directly belong to
7316     // the variable (matching the scope specifier), store them.
7317     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7318     if (TemplateParamLists.size() > VDTemplateParamLists)
7319       NewVD->setTemplateParameterListsInfo(
7320           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7321   }
7322 
7323   if (D.getDeclSpec().isInlineSpecified()) {
7324     if (!getLangOpts().CPlusPlus) {
7325       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7326           << 0;
7327     } else if (CurContext->isFunctionOrMethod()) {
7328       // 'inline' is not allowed on block scope variable declaration.
7329       Diag(D.getDeclSpec().getInlineSpecLoc(),
7330            diag::err_inline_declaration_block_scope) << Name
7331         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7332     } else {
7333       Diag(D.getDeclSpec().getInlineSpecLoc(),
7334            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7335                                      : diag::ext_inline_variable);
7336       NewVD->setInlineSpecified();
7337     }
7338   }
7339 
7340   // Set the lexical context. If the declarator has a C++ scope specifier, the
7341   // lexical context will be different from the semantic context.
7342   NewVD->setLexicalDeclContext(CurContext);
7343   if (NewTemplate)
7344     NewTemplate->setLexicalDeclContext(CurContext);
7345 
7346   if (IsLocalExternDecl) {
7347     if (D.isDecompositionDeclarator())
7348       for (auto *B : Bindings)
7349         B->setLocalExternDecl();
7350     else
7351       NewVD->setLocalExternDecl();
7352   }
7353 
7354   bool EmitTLSUnsupportedError = false;
7355   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7356     // C++11 [dcl.stc]p4:
7357     //   When thread_local is applied to a variable of block scope the
7358     //   storage-class-specifier static is implied if it does not appear
7359     //   explicitly.
7360     // Core issue: 'static' is not implied if the variable is declared
7361     //   'extern'.
7362     if (NewVD->hasLocalStorage() &&
7363         (SCSpec != DeclSpec::SCS_unspecified ||
7364          TSCS != DeclSpec::TSCS_thread_local ||
7365          !DC->isFunctionOrMethod()))
7366       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7367            diag::err_thread_non_global)
7368         << DeclSpec::getSpecifierName(TSCS);
7369     else if (!Context.getTargetInfo().isTLSSupported()) {
7370       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7371           getLangOpts().SYCLIsDevice) {
7372         // Postpone error emission until we've collected attributes required to
7373         // figure out whether it's a host or device variable and whether the
7374         // error should be ignored.
7375         EmitTLSUnsupportedError = true;
7376         // We still need to mark the variable as TLS so it shows up in AST with
7377         // proper storage class for other tools to use even if we're not going
7378         // to emit any code for it.
7379         NewVD->setTSCSpec(TSCS);
7380       } else
7381         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7382              diag::err_thread_unsupported);
7383     } else
7384       NewVD->setTSCSpec(TSCS);
7385   }
7386 
7387   switch (D.getDeclSpec().getConstexprSpecifier()) {
7388   case ConstexprSpecKind::Unspecified:
7389     break;
7390 
7391   case ConstexprSpecKind::Consteval:
7392     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7393          diag::err_constexpr_wrong_decl_kind)
7394         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7395     LLVM_FALLTHROUGH;
7396 
7397   case ConstexprSpecKind::Constexpr:
7398     NewVD->setConstexpr(true);
7399     // C++1z [dcl.spec.constexpr]p1:
7400     //   A static data member declared with the constexpr specifier is
7401     //   implicitly an inline variable.
7402     if (NewVD->isStaticDataMember() &&
7403         (getLangOpts().CPlusPlus17 ||
7404          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7405       NewVD->setImplicitlyInline();
7406     break;
7407 
7408   case ConstexprSpecKind::Constinit:
7409     if (!NewVD->hasGlobalStorage())
7410       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7411            diag::err_constinit_local_variable);
7412     else
7413       NewVD->addAttr(ConstInitAttr::Create(
7414           Context, D.getDeclSpec().getConstexprSpecLoc(),
7415           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7416     break;
7417   }
7418 
7419   // C99 6.7.4p3
7420   //   An inline definition of a function with external linkage shall
7421   //   not contain a definition of a modifiable object with static or
7422   //   thread storage duration...
7423   // We only apply this when the function is required to be defined
7424   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7425   // that a local variable with thread storage duration still has to
7426   // be marked 'static'.  Also note that it's possible to get these
7427   // semantics in C++ using __attribute__((gnu_inline)).
7428   if (SC == SC_Static && S->getFnParent() != nullptr &&
7429       !NewVD->getType().isConstQualified()) {
7430     FunctionDecl *CurFD = getCurFunctionDecl();
7431     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7432       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7433            diag::warn_static_local_in_extern_inline);
7434       MaybeSuggestAddingStaticToDecl(CurFD);
7435     }
7436   }
7437 
7438   if (D.getDeclSpec().isModulePrivateSpecified()) {
7439     if (IsVariableTemplateSpecialization)
7440       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7441           << (IsPartialSpecialization ? 1 : 0)
7442           << FixItHint::CreateRemoval(
7443                  D.getDeclSpec().getModulePrivateSpecLoc());
7444     else if (IsMemberSpecialization)
7445       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7446         << 2
7447         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7448     else if (NewVD->hasLocalStorage())
7449       Diag(NewVD->getLocation(), diag::err_module_private_local)
7450           << 0 << NewVD
7451           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7452           << FixItHint::CreateRemoval(
7453                  D.getDeclSpec().getModulePrivateSpecLoc());
7454     else {
7455       NewVD->setModulePrivate();
7456       if (NewTemplate)
7457         NewTemplate->setModulePrivate();
7458       for (auto *B : Bindings)
7459         B->setModulePrivate();
7460     }
7461   }
7462 
7463   if (getLangOpts().OpenCL) {
7464     deduceOpenCLAddressSpace(NewVD);
7465 
7466     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7467     if (TSC != TSCS_unspecified) {
7468       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7469            diag::err_opencl_unknown_type_specifier)
7470           << getLangOpts().getOpenCLVersionString()
7471           << DeclSpec::getSpecifierName(TSC) << 1;
7472       NewVD->setInvalidDecl();
7473     }
7474   }
7475 
7476   // Handle attributes prior to checking for duplicates in MergeVarDecl
7477   ProcessDeclAttributes(S, NewVD, D);
7478 
7479   // FIXME: This is probably the wrong location to be doing this and we should
7480   // probably be doing this for more attributes (especially for function
7481   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7482   // the code to copy attributes would be generated by TableGen.
7483   if (R->isFunctionPointerType())
7484     if (const auto *TT = R->getAs<TypedefType>())
7485       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7486 
7487   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7488       getLangOpts().SYCLIsDevice) {
7489     if (EmitTLSUnsupportedError &&
7490         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7491          (getLangOpts().OpenMPIsDevice &&
7492           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7493       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7494            diag::err_thread_unsupported);
7495 
7496     if (EmitTLSUnsupportedError &&
7497         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7498       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7499     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7500     // storage [duration]."
7501     if (SC == SC_None && S->getFnParent() != nullptr &&
7502         (NewVD->hasAttr<CUDASharedAttr>() ||
7503          NewVD->hasAttr<CUDAConstantAttr>())) {
7504       NewVD->setStorageClass(SC_Static);
7505     }
7506   }
7507 
7508   // Ensure that dllimport globals without explicit storage class are treated as
7509   // extern. The storage class is set above using parsed attributes. Now we can
7510   // check the VarDecl itself.
7511   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7512          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7513          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7514 
7515   // In auto-retain/release, infer strong retension for variables of
7516   // retainable type.
7517   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7518     NewVD->setInvalidDecl();
7519 
7520   // Handle GNU asm-label extension (encoded as an attribute).
7521   if (Expr *E = (Expr*)D.getAsmLabel()) {
7522     // The parser guarantees this is a string.
7523     StringLiteral *SE = cast<StringLiteral>(E);
7524     StringRef Label = SE->getString();
7525     if (S->getFnParent() != nullptr) {
7526       switch (SC) {
7527       case SC_None:
7528       case SC_Auto:
7529         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7530         break;
7531       case SC_Register:
7532         // Local Named register
7533         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7534             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7535           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7536         break;
7537       case SC_Static:
7538       case SC_Extern:
7539       case SC_PrivateExtern:
7540         break;
7541       }
7542     } else if (SC == SC_Register) {
7543       // Global Named register
7544       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7545         const auto &TI = Context.getTargetInfo();
7546         bool HasSizeMismatch;
7547 
7548         if (!TI.isValidGCCRegisterName(Label))
7549           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7550         else if (!TI.validateGlobalRegisterVariable(Label,
7551                                                     Context.getTypeSize(R),
7552                                                     HasSizeMismatch))
7553           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7554         else if (HasSizeMismatch)
7555           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7556       }
7557 
7558       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7559         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7560         NewVD->setInvalidDecl(true);
7561       }
7562     }
7563 
7564     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7565                                         /*IsLiteralLabel=*/true,
7566                                         SE->getStrTokenLoc(0)));
7567   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7568     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7569       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7570     if (I != ExtnameUndeclaredIdentifiers.end()) {
7571       if (isDeclExternC(NewVD)) {
7572         NewVD->addAttr(I->second);
7573         ExtnameUndeclaredIdentifiers.erase(I);
7574       } else
7575         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7576             << /*Variable*/1 << NewVD;
7577     }
7578   }
7579 
7580   // Find the shadowed declaration before filtering for scope.
7581   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7582                                 ? getShadowedDeclaration(NewVD, Previous)
7583                                 : nullptr;
7584 
7585   // Don't consider existing declarations that are in a different
7586   // scope and are out-of-semantic-context declarations (if the new
7587   // declaration has linkage).
7588   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7589                        D.getCXXScopeSpec().isNotEmpty() ||
7590                        IsMemberSpecialization ||
7591                        IsVariableTemplateSpecialization);
7592 
7593   // Check whether the previous declaration is in the same block scope. This
7594   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7595   if (getLangOpts().CPlusPlus &&
7596       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7597     NewVD->setPreviousDeclInSameBlockScope(
7598         Previous.isSingleResult() && !Previous.isShadowed() &&
7599         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7600 
7601   if (!getLangOpts().CPlusPlus) {
7602     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7603   } else {
7604     // If this is an explicit specialization of a static data member, check it.
7605     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7606         CheckMemberSpecialization(NewVD, Previous))
7607       NewVD->setInvalidDecl();
7608 
7609     // Merge the decl with the existing one if appropriate.
7610     if (!Previous.empty()) {
7611       if (Previous.isSingleResult() &&
7612           isa<FieldDecl>(Previous.getFoundDecl()) &&
7613           D.getCXXScopeSpec().isSet()) {
7614         // The user tried to define a non-static data member
7615         // out-of-line (C++ [dcl.meaning]p1).
7616         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7617           << D.getCXXScopeSpec().getRange();
7618         Previous.clear();
7619         NewVD->setInvalidDecl();
7620       }
7621     } else if (D.getCXXScopeSpec().isSet()) {
7622       // No previous declaration in the qualifying scope.
7623       Diag(D.getIdentifierLoc(), diag::err_no_member)
7624         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7625         << D.getCXXScopeSpec().getRange();
7626       NewVD->setInvalidDecl();
7627     }
7628 
7629     if (!IsVariableTemplateSpecialization)
7630       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7631 
7632     if (NewTemplate) {
7633       VarTemplateDecl *PrevVarTemplate =
7634           NewVD->getPreviousDecl()
7635               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7636               : nullptr;
7637 
7638       // Check the template parameter list of this declaration, possibly
7639       // merging in the template parameter list from the previous variable
7640       // template declaration.
7641       if (CheckTemplateParameterList(
7642               TemplateParams,
7643               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7644                               : nullptr,
7645               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7646                DC->isDependentContext())
7647                   ? TPC_ClassTemplateMember
7648                   : TPC_VarTemplate))
7649         NewVD->setInvalidDecl();
7650 
7651       // If we are providing an explicit specialization of a static variable
7652       // template, make a note of that.
7653       if (PrevVarTemplate &&
7654           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7655         PrevVarTemplate->setMemberSpecialization();
7656     }
7657   }
7658 
7659   // Diagnose shadowed variables iff this isn't a redeclaration.
7660   if (ShadowedDecl && !D.isRedeclaration())
7661     CheckShadow(NewVD, ShadowedDecl, Previous);
7662 
7663   ProcessPragmaWeak(S, NewVD);
7664 
7665   // If this is the first declaration of an extern C variable, update
7666   // the map of such variables.
7667   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7668       isIncompleteDeclExternC(*this, NewVD))
7669     RegisterLocallyScopedExternCDecl(NewVD, S);
7670 
7671   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7672     MangleNumberingContext *MCtx;
7673     Decl *ManglingContextDecl;
7674     std::tie(MCtx, ManglingContextDecl) =
7675         getCurrentMangleNumberContext(NewVD->getDeclContext());
7676     if (MCtx) {
7677       Context.setManglingNumber(
7678           NewVD, MCtx->getManglingNumber(
7679                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7680       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7681     }
7682   }
7683 
7684   // Special handling of variable named 'main'.
7685   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7686       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7687       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7688 
7689     // C++ [basic.start.main]p3
7690     // A program that declares a variable main at global scope is ill-formed.
7691     if (getLangOpts().CPlusPlus)
7692       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7693 
7694     // In C, and external-linkage variable named main results in undefined
7695     // behavior.
7696     else if (NewVD->hasExternalFormalLinkage())
7697       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7698   }
7699 
7700   if (D.isRedeclaration() && !Previous.empty()) {
7701     NamedDecl *Prev = Previous.getRepresentativeDecl();
7702     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7703                                    D.isFunctionDefinition());
7704   }
7705 
7706   if (NewTemplate) {
7707     if (NewVD->isInvalidDecl())
7708       NewTemplate->setInvalidDecl();
7709     ActOnDocumentableDecl(NewTemplate);
7710     return NewTemplate;
7711   }
7712 
7713   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7714     CompleteMemberSpecialization(NewVD, Previous);
7715 
7716   return NewVD;
7717 }
7718 
7719 /// Enum describing the %select options in diag::warn_decl_shadow.
7720 enum ShadowedDeclKind {
7721   SDK_Local,
7722   SDK_Global,
7723   SDK_StaticMember,
7724   SDK_Field,
7725   SDK_Typedef,
7726   SDK_Using,
7727   SDK_StructuredBinding
7728 };
7729 
7730 /// Determine what kind of declaration we're shadowing.
7731 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7732                                                 const DeclContext *OldDC) {
7733   if (isa<TypeAliasDecl>(ShadowedDecl))
7734     return SDK_Using;
7735   else if (isa<TypedefDecl>(ShadowedDecl))
7736     return SDK_Typedef;
7737   else if (isa<BindingDecl>(ShadowedDecl))
7738     return SDK_StructuredBinding;
7739   else if (isa<RecordDecl>(OldDC))
7740     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7741 
7742   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7743 }
7744 
7745 /// Return the location of the capture if the given lambda captures the given
7746 /// variable \p VD, or an invalid source location otherwise.
7747 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7748                                          const VarDecl *VD) {
7749   for (const Capture &Capture : LSI->Captures) {
7750     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7751       return Capture.getLocation();
7752   }
7753   return SourceLocation();
7754 }
7755 
7756 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7757                                      const LookupResult &R) {
7758   // Only diagnose if we're shadowing an unambiguous field or variable.
7759   if (R.getResultKind() != LookupResult::Found)
7760     return false;
7761 
7762   // Return false if warning is ignored.
7763   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7764 }
7765 
7766 /// Return the declaration shadowed by the given variable \p D, or null
7767 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7768 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7769                                         const LookupResult &R) {
7770   if (!shouldWarnIfShadowedDecl(Diags, R))
7771     return nullptr;
7772 
7773   // Don't diagnose declarations at file scope.
7774   if (D->hasGlobalStorage())
7775     return nullptr;
7776 
7777   NamedDecl *ShadowedDecl = R.getFoundDecl();
7778   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7779                                                             : nullptr;
7780 }
7781 
7782 /// Return the declaration shadowed by the given typedef \p D, or null
7783 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7784 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7785                                         const LookupResult &R) {
7786   // Don't warn if typedef declaration is part of a class
7787   if (D->getDeclContext()->isRecord())
7788     return nullptr;
7789 
7790   if (!shouldWarnIfShadowedDecl(Diags, R))
7791     return nullptr;
7792 
7793   NamedDecl *ShadowedDecl = R.getFoundDecl();
7794   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7795 }
7796 
7797 /// Return the declaration shadowed by the given variable \p D, or null
7798 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7799 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7800                                         const LookupResult &R) {
7801   if (!shouldWarnIfShadowedDecl(Diags, R))
7802     return nullptr;
7803 
7804   NamedDecl *ShadowedDecl = R.getFoundDecl();
7805   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7806                                                             : nullptr;
7807 }
7808 
7809 /// Diagnose variable or built-in function shadowing.  Implements
7810 /// -Wshadow.
7811 ///
7812 /// This method is called whenever a VarDecl is added to a "useful"
7813 /// scope.
7814 ///
7815 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7816 /// \param R the lookup of the name
7817 ///
7818 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7819                        const LookupResult &R) {
7820   DeclContext *NewDC = D->getDeclContext();
7821 
7822   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7823     // Fields are not shadowed by variables in C++ static methods.
7824     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7825       if (MD->isStatic())
7826         return;
7827 
7828     // Fields shadowed by constructor parameters are a special case. Usually
7829     // the constructor initializes the field with the parameter.
7830     if (isa<CXXConstructorDecl>(NewDC))
7831       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7832         // Remember that this was shadowed so we can either warn about its
7833         // modification or its existence depending on warning settings.
7834         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7835         return;
7836       }
7837   }
7838 
7839   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7840     if (shadowedVar->isExternC()) {
7841       // For shadowing external vars, make sure that we point to the global
7842       // declaration, not a locally scoped extern declaration.
7843       for (auto I : shadowedVar->redecls())
7844         if (I->isFileVarDecl()) {
7845           ShadowedDecl = I;
7846           break;
7847         }
7848     }
7849 
7850   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7851 
7852   unsigned WarningDiag = diag::warn_decl_shadow;
7853   SourceLocation CaptureLoc;
7854   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7855       isa<CXXMethodDecl>(NewDC)) {
7856     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7857       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7858         if (RD->getLambdaCaptureDefault() == LCD_None) {
7859           // Try to avoid warnings for lambdas with an explicit capture list.
7860           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7861           // Warn only when the lambda captures the shadowed decl explicitly.
7862           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7863           if (CaptureLoc.isInvalid())
7864             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7865         } else {
7866           // Remember that this was shadowed so we can avoid the warning if the
7867           // shadowed decl isn't captured and the warning settings allow it.
7868           cast<LambdaScopeInfo>(getCurFunction())
7869               ->ShadowingDecls.push_back(
7870                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7871           return;
7872         }
7873       }
7874 
7875       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7876         // A variable can't shadow a local variable in an enclosing scope, if
7877         // they are separated by a non-capturing declaration context.
7878         for (DeclContext *ParentDC = NewDC;
7879              ParentDC && !ParentDC->Equals(OldDC);
7880              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7881           // Only block literals, captured statements, and lambda expressions
7882           // can capture; other scopes don't.
7883           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7884               !isLambdaCallOperator(ParentDC)) {
7885             return;
7886           }
7887         }
7888       }
7889     }
7890   }
7891 
7892   // Only warn about certain kinds of shadowing for class members.
7893   if (NewDC && NewDC->isRecord()) {
7894     // In particular, don't warn about shadowing non-class members.
7895     if (!OldDC->isRecord())
7896       return;
7897 
7898     // TODO: should we warn about static data members shadowing
7899     // static data members from base classes?
7900 
7901     // TODO: don't diagnose for inaccessible shadowed members.
7902     // This is hard to do perfectly because we might friend the
7903     // shadowing context, but that's just a false negative.
7904   }
7905 
7906 
7907   DeclarationName Name = R.getLookupName();
7908 
7909   // Emit warning and note.
7910   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7911   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7912   if (!CaptureLoc.isInvalid())
7913     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7914         << Name << /*explicitly*/ 1;
7915   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7916 }
7917 
7918 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7919 /// when these variables are captured by the lambda.
7920 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7921   for (const auto &Shadow : LSI->ShadowingDecls) {
7922     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7923     // Try to avoid the warning when the shadowed decl isn't captured.
7924     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7925     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7926     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7927                                        ? diag::warn_decl_shadow_uncaptured_local
7928                                        : diag::warn_decl_shadow)
7929         << Shadow.VD->getDeclName()
7930         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7931     if (!CaptureLoc.isInvalid())
7932       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7933           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7934     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7935   }
7936 }
7937 
7938 /// Check -Wshadow without the advantage of a previous lookup.
7939 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7940   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7941     return;
7942 
7943   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7944                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7945   LookupName(R, S);
7946   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7947     CheckShadow(D, ShadowedDecl, R);
7948 }
7949 
7950 /// Check if 'E', which is an expression that is about to be modified, refers
7951 /// to a constructor parameter that shadows a field.
7952 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7953   // Quickly ignore expressions that can't be shadowing ctor parameters.
7954   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7955     return;
7956   E = E->IgnoreParenImpCasts();
7957   auto *DRE = dyn_cast<DeclRefExpr>(E);
7958   if (!DRE)
7959     return;
7960   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7961   auto I = ShadowingDecls.find(D);
7962   if (I == ShadowingDecls.end())
7963     return;
7964   const NamedDecl *ShadowedDecl = I->second;
7965   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7966   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7967   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7968   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7969 
7970   // Avoid issuing multiple warnings about the same decl.
7971   ShadowingDecls.erase(I);
7972 }
7973 
7974 /// Check for conflict between this global or extern "C" declaration and
7975 /// previous global or extern "C" declarations. This is only used in C++.
7976 template<typename T>
7977 static bool checkGlobalOrExternCConflict(
7978     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7979   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7980   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7981 
7982   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7983     // The common case: this global doesn't conflict with any extern "C"
7984     // declaration.
7985     return false;
7986   }
7987 
7988   if (Prev) {
7989     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7990       // Both the old and new declarations have C language linkage. This is a
7991       // redeclaration.
7992       Previous.clear();
7993       Previous.addDecl(Prev);
7994       return true;
7995     }
7996 
7997     // This is a global, non-extern "C" declaration, and there is a previous
7998     // non-global extern "C" declaration. Diagnose if this is a variable
7999     // declaration.
8000     if (!isa<VarDecl>(ND))
8001       return false;
8002   } else {
8003     // The declaration is extern "C". Check for any declaration in the
8004     // translation unit which might conflict.
8005     if (IsGlobal) {
8006       // We have already performed the lookup into the translation unit.
8007       IsGlobal = false;
8008       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8009            I != E; ++I) {
8010         if (isa<VarDecl>(*I)) {
8011           Prev = *I;
8012           break;
8013         }
8014       }
8015     } else {
8016       DeclContext::lookup_result R =
8017           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8018       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8019            I != E; ++I) {
8020         if (isa<VarDecl>(*I)) {
8021           Prev = *I;
8022           break;
8023         }
8024         // FIXME: If we have any other entity with this name in global scope,
8025         // the declaration is ill-formed, but that is a defect: it breaks the
8026         // 'stat' hack, for instance. Only variables can have mangled name
8027         // clashes with extern "C" declarations, so only they deserve a
8028         // diagnostic.
8029       }
8030     }
8031 
8032     if (!Prev)
8033       return false;
8034   }
8035 
8036   // Use the first declaration's location to ensure we point at something which
8037   // is lexically inside an extern "C" linkage-spec.
8038   assert(Prev && "should have found a previous declaration to diagnose");
8039   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8040     Prev = FD->getFirstDecl();
8041   else
8042     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8043 
8044   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8045     << IsGlobal << ND;
8046   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8047     << IsGlobal;
8048   return false;
8049 }
8050 
8051 /// Apply special rules for handling extern "C" declarations. Returns \c true
8052 /// if we have found that this is a redeclaration of some prior entity.
8053 ///
8054 /// Per C++ [dcl.link]p6:
8055 ///   Two declarations [for a function or variable] with C language linkage
8056 ///   with the same name that appear in different scopes refer to the same
8057 ///   [entity]. An entity with C language linkage shall not be declared with
8058 ///   the same name as an entity in global scope.
8059 template<typename T>
8060 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8061                                                   LookupResult &Previous) {
8062   if (!S.getLangOpts().CPlusPlus) {
8063     // In C, when declaring a global variable, look for a corresponding 'extern'
8064     // variable declared in function scope. We don't need this in C++, because
8065     // we find local extern decls in the surrounding file-scope DeclContext.
8066     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8067       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8068         Previous.clear();
8069         Previous.addDecl(Prev);
8070         return true;
8071       }
8072     }
8073     return false;
8074   }
8075 
8076   // A declaration in the translation unit can conflict with an extern "C"
8077   // declaration.
8078   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8079     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8080 
8081   // An extern "C" declaration can conflict with a declaration in the
8082   // translation unit or can be a redeclaration of an extern "C" declaration
8083   // in another scope.
8084   if (isIncompleteDeclExternC(S,ND))
8085     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8086 
8087   // Neither global nor extern "C": nothing to do.
8088   return false;
8089 }
8090 
8091 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8092   // If the decl is already known invalid, don't check it.
8093   if (NewVD->isInvalidDecl())
8094     return;
8095 
8096   QualType T = NewVD->getType();
8097 
8098   // Defer checking an 'auto' type until its initializer is attached.
8099   if (T->isUndeducedType())
8100     return;
8101 
8102   if (NewVD->hasAttrs())
8103     CheckAlignasUnderalignment(NewVD);
8104 
8105   if (T->isObjCObjectType()) {
8106     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8107       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8108     T = Context.getObjCObjectPointerType(T);
8109     NewVD->setType(T);
8110   }
8111 
8112   // Emit an error if an address space was applied to decl with local storage.
8113   // This includes arrays of objects with address space qualifiers, but not
8114   // automatic variables that point to other address spaces.
8115   // ISO/IEC TR 18037 S5.1.2
8116   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8117       T.getAddressSpace() != LangAS::Default) {
8118     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8119     NewVD->setInvalidDecl();
8120     return;
8121   }
8122 
8123   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8124   // scope.
8125   if (getLangOpts().OpenCLVersion == 120 &&
8126       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8127                                             getLangOpts()) &&
8128       NewVD->isStaticLocal()) {
8129     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8130     NewVD->setInvalidDecl();
8131     return;
8132   }
8133 
8134   if (getLangOpts().OpenCL) {
8135     if (!diagnoseOpenCLTypes(*this, NewVD))
8136       return;
8137 
8138     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8139     if (NewVD->hasAttr<BlocksAttr>()) {
8140       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8141       return;
8142     }
8143 
8144     if (T->isBlockPointerType()) {
8145       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8146       // can't use 'extern' storage class.
8147       if (!T.isConstQualified()) {
8148         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8149             << 0 /*const*/;
8150         NewVD->setInvalidDecl();
8151         return;
8152       }
8153       if (NewVD->hasExternalStorage()) {
8154         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8155         NewVD->setInvalidDecl();
8156         return;
8157       }
8158     }
8159 
8160     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8161     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8162         NewVD->hasExternalStorage()) {
8163       if (!T->isSamplerT() && !T->isDependentType() &&
8164           !(T.getAddressSpace() == LangAS::opencl_constant ||
8165             (T.getAddressSpace() == LangAS::opencl_global &&
8166              getOpenCLOptions().areProgramScopeVariablesSupported(
8167                  getLangOpts())))) {
8168         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8169         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8170           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8171               << Scope << "global or constant";
8172         else
8173           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8174               << Scope << "constant";
8175         NewVD->setInvalidDecl();
8176         return;
8177       }
8178     } else {
8179       if (T.getAddressSpace() == LangAS::opencl_global) {
8180         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8181             << 1 /*is any function*/ << "global";
8182         NewVD->setInvalidDecl();
8183         return;
8184       }
8185       if (T.getAddressSpace() == LangAS::opencl_constant ||
8186           T.getAddressSpace() == LangAS::opencl_local) {
8187         FunctionDecl *FD = getCurFunctionDecl();
8188         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8189         // in functions.
8190         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8191           if (T.getAddressSpace() == LangAS::opencl_constant)
8192             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8193                 << 0 /*non-kernel only*/ << "constant";
8194           else
8195             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8196                 << 0 /*non-kernel only*/ << "local";
8197           NewVD->setInvalidDecl();
8198           return;
8199         }
8200         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8201         // in the outermost scope of a kernel function.
8202         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8203           if (!getCurScope()->isFunctionScope()) {
8204             if (T.getAddressSpace() == LangAS::opencl_constant)
8205               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8206                   << "constant";
8207             else
8208               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8209                   << "local";
8210             NewVD->setInvalidDecl();
8211             return;
8212           }
8213         }
8214       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8215                  // If we are parsing a template we didn't deduce an addr
8216                  // space yet.
8217                  T.getAddressSpace() != LangAS::Default) {
8218         // Do not allow other address spaces on automatic variable.
8219         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8220         NewVD->setInvalidDecl();
8221         return;
8222       }
8223     }
8224   }
8225 
8226   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8227       && !NewVD->hasAttr<BlocksAttr>()) {
8228     if (getLangOpts().getGC() != LangOptions::NonGC)
8229       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8230     else {
8231       assert(!getLangOpts().ObjCAutoRefCount);
8232       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8233     }
8234   }
8235 
8236   bool isVM = T->isVariablyModifiedType();
8237   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8238       NewVD->hasAttr<BlocksAttr>())
8239     setFunctionHasBranchProtectedScope();
8240 
8241   if ((isVM && NewVD->hasLinkage()) ||
8242       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8243     bool SizeIsNegative;
8244     llvm::APSInt Oversized;
8245     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8246         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8247     QualType FixedT;
8248     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8249       FixedT = FixedTInfo->getType();
8250     else if (FixedTInfo) {
8251       // Type and type-as-written are canonically different. We need to fix up
8252       // both types separately.
8253       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8254                                                    Oversized);
8255     }
8256     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8257       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8258       // FIXME: This won't give the correct result for
8259       // int a[10][n];
8260       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8261 
8262       if (NewVD->isFileVarDecl())
8263         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8264         << SizeRange;
8265       else if (NewVD->isStaticLocal())
8266         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8267         << SizeRange;
8268       else
8269         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8270         << SizeRange;
8271       NewVD->setInvalidDecl();
8272       return;
8273     }
8274 
8275     if (!FixedTInfo) {
8276       if (NewVD->isFileVarDecl())
8277         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8278       else
8279         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8280       NewVD->setInvalidDecl();
8281       return;
8282     }
8283 
8284     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8285     NewVD->setType(FixedT);
8286     NewVD->setTypeSourceInfo(FixedTInfo);
8287   }
8288 
8289   if (T->isVoidType()) {
8290     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8291     //                    of objects and functions.
8292     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8293       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8294         << T;
8295       NewVD->setInvalidDecl();
8296       return;
8297     }
8298   }
8299 
8300   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8301     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8302     NewVD->setInvalidDecl();
8303     return;
8304   }
8305 
8306   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8307     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8308     NewVD->setInvalidDecl();
8309     return;
8310   }
8311 
8312   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8313     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8314     NewVD->setInvalidDecl();
8315     return;
8316   }
8317 
8318   if (NewVD->isConstexpr() && !T->isDependentType() &&
8319       RequireLiteralType(NewVD->getLocation(), T,
8320                          diag::err_constexpr_var_non_literal)) {
8321     NewVD->setInvalidDecl();
8322     return;
8323   }
8324 
8325   // PPC MMA non-pointer types are not allowed as non-local variable types.
8326   if (Context.getTargetInfo().getTriple().isPPC64() &&
8327       !NewVD->isLocalVarDecl() &&
8328       CheckPPCMMAType(T, NewVD->getLocation())) {
8329     NewVD->setInvalidDecl();
8330     return;
8331   }
8332 }
8333 
8334 /// Perform semantic checking on a newly-created variable
8335 /// declaration.
8336 ///
8337 /// This routine performs all of the type-checking required for a
8338 /// variable declaration once it has been built. It is used both to
8339 /// check variables after they have been parsed and their declarators
8340 /// have been translated into a declaration, and to check variables
8341 /// that have been instantiated from a template.
8342 ///
8343 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8344 ///
8345 /// Returns true if the variable declaration is a redeclaration.
8346 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8347   CheckVariableDeclarationType(NewVD);
8348 
8349   // If the decl is already known invalid, don't check it.
8350   if (NewVD->isInvalidDecl())
8351     return false;
8352 
8353   // If we did not find anything by this name, look for a non-visible
8354   // extern "C" declaration with the same name.
8355   if (Previous.empty() &&
8356       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8357     Previous.setShadowed();
8358 
8359   if (!Previous.empty()) {
8360     MergeVarDecl(NewVD, Previous);
8361     return true;
8362   }
8363   return false;
8364 }
8365 
8366 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8367 /// and if so, check that it's a valid override and remember it.
8368 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8369   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8370 
8371   // Look for methods in base classes that this method might override.
8372   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8373                      /*DetectVirtual=*/false);
8374   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8375     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8376     DeclarationName Name = MD->getDeclName();
8377 
8378     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8379       // We really want to find the base class destructor here.
8380       QualType T = Context.getTypeDeclType(BaseRecord);
8381       CanQualType CT = Context.getCanonicalType(T);
8382       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8383     }
8384 
8385     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8386       CXXMethodDecl *BaseMD =
8387           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8388       if (!BaseMD || !BaseMD->isVirtual() ||
8389           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8390                      /*ConsiderCudaAttrs=*/true,
8391                      // C++2a [class.virtual]p2 does not consider requires
8392                      // clauses when overriding.
8393                      /*ConsiderRequiresClauses=*/false))
8394         continue;
8395 
8396       if (Overridden.insert(BaseMD).second) {
8397         MD->addOverriddenMethod(BaseMD);
8398         CheckOverridingFunctionReturnType(MD, BaseMD);
8399         CheckOverridingFunctionAttributes(MD, BaseMD);
8400         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8401         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8402       }
8403 
8404       // A method can only override one function from each base class. We
8405       // don't track indirectly overridden methods from bases of bases.
8406       return true;
8407     }
8408 
8409     return false;
8410   };
8411 
8412   DC->lookupInBases(VisitBase, Paths);
8413   return !Overridden.empty();
8414 }
8415 
8416 namespace {
8417   // Struct for holding all of the extra arguments needed by
8418   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8419   struct ActOnFDArgs {
8420     Scope *S;
8421     Declarator &D;
8422     MultiTemplateParamsArg TemplateParamLists;
8423     bool AddToScope;
8424   };
8425 } // end anonymous namespace
8426 
8427 namespace {
8428 
8429 // Callback to only accept typo corrections that have a non-zero edit distance.
8430 // Also only accept corrections that have the same parent decl.
8431 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8432  public:
8433   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8434                             CXXRecordDecl *Parent)
8435       : Context(Context), OriginalFD(TypoFD),
8436         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8437 
8438   bool ValidateCandidate(const TypoCorrection &candidate) override {
8439     if (candidate.getEditDistance() == 0)
8440       return false;
8441 
8442     SmallVector<unsigned, 1> MismatchedParams;
8443     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8444                                           CDeclEnd = candidate.end();
8445          CDecl != CDeclEnd; ++CDecl) {
8446       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8447 
8448       if (FD && !FD->hasBody() &&
8449           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8450         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8451           CXXRecordDecl *Parent = MD->getParent();
8452           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8453             return true;
8454         } else if (!ExpectedParent) {
8455           return true;
8456         }
8457       }
8458     }
8459 
8460     return false;
8461   }
8462 
8463   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8464     return std::make_unique<DifferentNameValidatorCCC>(*this);
8465   }
8466 
8467  private:
8468   ASTContext &Context;
8469   FunctionDecl *OriginalFD;
8470   CXXRecordDecl *ExpectedParent;
8471 };
8472 
8473 } // end anonymous namespace
8474 
8475 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8476   TypoCorrectedFunctionDefinitions.insert(F);
8477 }
8478 
8479 /// Generate diagnostics for an invalid function redeclaration.
8480 ///
8481 /// This routine handles generating the diagnostic messages for an invalid
8482 /// function redeclaration, including finding possible similar declarations
8483 /// or performing typo correction if there are no previous declarations with
8484 /// the same name.
8485 ///
8486 /// Returns a NamedDecl iff typo correction was performed and substituting in
8487 /// the new declaration name does not cause new errors.
8488 static NamedDecl *DiagnoseInvalidRedeclaration(
8489     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8490     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8491   DeclarationName Name = NewFD->getDeclName();
8492   DeclContext *NewDC = NewFD->getDeclContext();
8493   SmallVector<unsigned, 1> MismatchedParams;
8494   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8495   TypoCorrection Correction;
8496   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8497   unsigned DiagMsg =
8498     IsLocalFriend ? diag::err_no_matching_local_friend :
8499     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8500     diag::err_member_decl_does_not_match;
8501   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8502                     IsLocalFriend ? Sema::LookupLocalFriendName
8503                                   : Sema::LookupOrdinaryName,
8504                     Sema::ForVisibleRedeclaration);
8505 
8506   NewFD->setInvalidDecl();
8507   if (IsLocalFriend)
8508     SemaRef.LookupName(Prev, S);
8509   else
8510     SemaRef.LookupQualifiedName(Prev, NewDC);
8511   assert(!Prev.isAmbiguous() &&
8512          "Cannot have an ambiguity in previous-declaration lookup");
8513   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8514   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8515                                 MD ? MD->getParent() : nullptr);
8516   if (!Prev.empty()) {
8517     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8518          Func != FuncEnd; ++Func) {
8519       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8520       if (FD &&
8521           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8522         // Add 1 to the index so that 0 can mean the mismatch didn't
8523         // involve a parameter
8524         unsigned ParamNum =
8525             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8526         NearMatches.push_back(std::make_pair(FD, ParamNum));
8527       }
8528     }
8529   // If the qualified name lookup yielded nothing, try typo correction
8530   } else if ((Correction = SemaRef.CorrectTypo(
8531                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8532                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8533                   IsLocalFriend ? nullptr : NewDC))) {
8534     // Set up everything for the call to ActOnFunctionDeclarator
8535     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8536                               ExtraArgs.D.getIdentifierLoc());
8537     Previous.clear();
8538     Previous.setLookupName(Correction.getCorrection());
8539     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8540                                     CDeclEnd = Correction.end();
8541          CDecl != CDeclEnd; ++CDecl) {
8542       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8543       if (FD && !FD->hasBody() &&
8544           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8545         Previous.addDecl(FD);
8546       }
8547     }
8548     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8549 
8550     NamedDecl *Result;
8551     // Retry building the function declaration with the new previous
8552     // declarations, and with errors suppressed.
8553     {
8554       // Trap errors.
8555       Sema::SFINAETrap Trap(SemaRef);
8556 
8557       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8558       // pieces need to verify the typo-corrected C++ declaration and hopefully
8559       // eliminate the need for the parameter pack ExtraArgs.
8560       Result = SemaRef.ActOnFunctionDeclarator(
8561           ExtraArgs.S, ExtraArgs.D,
8562           Correction.getCorrectionDecl()->getDeclContext(),
8563           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8564           ExtraArgs.AddToScope);
8565 
8566       if (Trap.hasErrorOccurred())
8567         Result = nullptr;
8568     }
8569 
8570     if (Result) {
8571       // Determine which correction we picked.
8572       Decl *Canonical = Result->getCanonicalDecl();
8573       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8574            I != E; ++I)
8575         if ((*I)->getCanonicalDecl() == Canonical)
8576           Correction.setCorrectionDecl(*I);
8577 
8578       // Let Sema know about the correction.
8579       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8580       SemaRef.diagnoseTypo(
8581           Correction,
8582           SemaRef.PDiag(IsLocalFriend
8583                           ? diag::err_no_matching_local_friend_suggest
8584                           : diag::err_member_decl_does_not_match_suggest)
8585             << Name << NewDC << IsDefinition);
8586       return Result;
8587     }
8588 
8589     // Pretend the typo correction never occurred
8590     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8591                               ExtraArgs.D.getIdentifierLoc());
8592     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8593     Previous.clear();
8594     Previous.setLookupName(Name);
8595   }
8596 
8597   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8598       << Name << NewDC << IsDefinition << NewFD->getLocation();
8599 
8600   bool NewFDisConst = false;
8601   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8602     NewFDisConst = NewMD->isConst();
8603 
8604   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8605        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8606        NearMatch != NearMatchEnd; ++NearMatch) {
8607     FunctionDecl *FD = NearMatch->first;
8608     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8609     bool FDisConst = MD && MD->isConst();
8610     bool IsMember = MD || !IsLocalFriend;
8611 
8612     // FIXME: These notes are poorly worded for the local friend case.
8613     if (unsigned Idx = NearMatch->second) {
8614       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8615       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8616       if (Loc.isInvalid()) Loc = FD->getLocation();
8617       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8618                                  : diag::note_local_decl_close_param_match)
8619         << Idx << FDParam->getType()
8620         << NewFD->getParamDecl(Idx - 1)->getType();
8621     } else if (FDisConst != NewFDisConst) {
8622       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8623           << NewFDisConst << FD->getSourceRange().getEnd()
8624           << (NewFDisConst
8625                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8626                                                  .getConstQualifierLoc())
8627                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8628                                                    .getRParenLoc()
8629                                                    .getLocWithOffset(1),
8630                                                " const"));
8631     } else
8632       SemaRef.Diag(FD->getLocation(),
8633                    IsMember ? diag::note_member_def_close_match
8634                             : diag::note_local_decl_close_match);
8635   }
8636   return nullptr;
8637 }
8638 
8639 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8640   switch (D.getDeclSpec().getStorageClassSpec()) {
8641   default: llvm_unreachable("Unknown storage class!");
8642   case DeclSpec::SCS_auto:
8643   case DeclSpec::SCS_register:
8644   case DeclSpec::SCS_mutable:
8645     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8646                  diag::err_typecheck_sclass_func);
8647     D.getMutableDeclSpec().ClearStorageClassSpecs();
8648     D.setInvalidType();
8649     break;
8650   case DeclSpec::SCS_unspecified: break;
8651   case DeclSpec::SCS_extern:
8652     if (D.getDeclSpec().isExternInLinkageSpec())
8653       return SC_None;
8654     return SC_Extern;
8655   case DeclSpec::SCS_static: {
8656     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8657       // C99 6.7.1p5:
8658       //   The declaration of an identifier for a function that has
8659       //   block scope shall have no explicit storage-class specifier
8660       //   other than extern
8661       // See also (C++ [dcl.stc]p4).
8662       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8663                    diag::err_static_block_func);
8664       break;
8665     } else
8666       return SC_Static;
8667   }
8668   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8669   }
8670 
8671   // No explicit storage class has already been returned
8672   return SC_None;
8673 }
8674 
8675 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8676                                            DeclContext *DC, QualType &R,
8677                                            TypeSourceInfo *TInfo,
8678                                            StorageClass SC,
8679                                            bool &IsVirtualOkay) {
8680   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8681   DeclarationName Name = NameInfo.getName();
8682 
8683   FunctionDecl *NewFD = nullptr;
8684   bool isInline = D.getDeclSpec().isInlineSpecified();
8685 
8686   if (!SemaRef.getLangOpts().CPlusPlus) {
8687     // Determine whether the function was written with a
8688     // prototype. This true when:
8689     //   - there is a prototype in the declarator, or
8690     //   - the type R of the function is some kind of typedef or other non-
8691     //     attributed reference to a type name (which eventually refers to a
8692     //     function type).
8693     bool HasPrototype =
8694       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8695       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8696 
8697     NewFD = FunctionDecl::Create(
8698         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8699         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8700         ConstexprSpecKind::Unspecified,
8701         /*TrailingRequiresClause=*/nullptr);
8702     if (D.isInvalidType())
8703       NewFD->setInvalidDecl();
8704 
8705     return NewFD;
8706   }
8707 
8708   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8709 
8710   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8711   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8712     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8713                  diag::err_constexpr_wrong_decl_kind)
8714         << static_cast<int>(ConstexprKind);
8715     ConstexprKind = ConstexprSpecKind::Unspecified;
8716     D.getMutableDeclSpec().ClearConstexprSpec();
8717   }
8718   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8719 
8720   // Check that the return type is not an abstract class type.
8721   // For record types, this is done by the AbstractClassUsageDiagnoser once
8722   // the class has been completely parsed.
8723   if (!DC->isRecord() &&
8724       SemaRef.RequireNonAbstractType(
8725           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8726           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8727     D.setInvalidType();
8728 
8729   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8730     // This is a C++ constructor declaration.
8731     assert(DC->isRecord() &&
8732            "Constructors can only be declared in a member context");
8733 
8734     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8735     return CXXConstructorDecl::Create(
8736         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8737         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8738         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8739         InheritedConstructor(), TrailingRequiresClause);
8740 
8741   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8742     // This is a C++ destructor declaration.
8743     if (DC->isRecord()) {
8744       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8745       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8746       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8747           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8748           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8749           /*isImplicitlyDeclared=*/false, ConstexprKind,
8750           TrailingRequiresClause);
8751 
8752       // If the destructor needs an implicit exception specification, set it
8753       // now. FIXME: It'd be nice to be able to create the right type to start
8754       // with, but the type needs to reference the destructor declaration.
8755       if (SemaRef.getLangOpts().CPlusPlus11)
8756         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8757 
8758       IsVirtualOkay = true;
8759       return NewDD;
8760 
8761     } else {
8762       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8763       D.setInvalidType();
8764 
8765       // Create a FunctionDecl to satisfy the function definition parsing
8766       // code path.
8767       return FunctionDecl::Create(
8768           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8769           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8770           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8771     }
8772 
8773   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8774     if (!DC->isRecord()) {
8775       SemaRef.Diag(D.getIdentifierLoc(),
8776            diag::err_conv_function_not_member);
8777       return nullptr;
8778     }
8779 
8780     SemaRef.CheckConversionDeclarator(D, R, SC);
8781     if (D.isInvalidType())
8782       return nullptr;
8783 
8784     IsVirtualOkay = true;
8785     return CXXConversionDecl::Create(
8786         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8787         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8788         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8789         TrailingRequiresClause);
8790 
8791   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8792     if (TrailingRequiresClause)
8793       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8794                    diag::err_trailing_requires_clause_on_deduction_guide)
8795           << TrailingRequiresClause->getSourceRange();
8796     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8797 
8798     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8799                                          ExplicitSpecifier, NameInfo, R, TInfo,
8800                                          D.getEndLoc());
8801   } else if (DC->isRecord()) {
8802     // If the name of the function is the same as the name of the record,
8803     // then this must be an invalid constructor that has a return type.
8804     // (The parser checks for a return type and makes the declarator a
8805     // constructor if it has no return type).
8806     if (Name.getAsIdentifierInfo() &&
8807         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8808       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8809         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8810         << SourceRange(D.getIdentifierLoc());
8811       return nullptr;
8812     }
8813 
8814     // This is a C++ method declaration.
8815     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8816         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8817         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8818         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8819     IsVirtualOkay = !Ret->isStatic();
8820     return Ret;
8821   } else {
8822     bool isFriend =
8823         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8824     if (!isFriend && SemaRef.CurContext->isRecord())
8825       return nullptr;
8826 
8827     // Determine whether the function was written with a
8828     // prototype. This true when:
8829     //   - we're in C++ (where every function has a prototype),
8830     return FunctionDecl::Create(
8831         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8832         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8833         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8834   }
8835 }
8836 
8837 enum OpenCLParamType {
8838   ValidKernelParam,
8839   PtrPtrKernelParam,
8840   PtrKernelParam,
8841   InvalidAddrSpacePtrKernelParam,
8842   InvalidKernelParam,
8843   RecordKernelParam
8844 };
8845 
8846 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8847   // Size dependent types are just typedefs to normal integer types
8848   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8849   // integers other than by their names.
8850   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8851 
8852   // Remove typedefs one by one until we reach a typedef
8853   // for a size dependent type.
8854   QualType DesugaredTy = Ty;
8855   do {
8856     ArrayRef<StringRef> Names(SizeTypeNames);
8857     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8858     if (Names.end() != Match)
8859       return true;
8860 
8861     Ty = DesugaredTy;
8862     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8863   } while (DesugaredTy != Ty);
8864 
8865   return false;
8866 }
8867 
8868 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8869   if (PT->isDependentType())
8870     return InvalidKernelParam;
8871 
8872   if (PT->isPointerType() || PT->isReferenceType()) {
8873     QualType PointeeType = PT->getPointeeType();
8874     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8875         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8876         PointeeType.getAddressSpace() == LangAS::Default)
8877       return InvalidAddrSpacePtrKernelParam;
8878 
8879     if (PointeeType->isPointerType()) {
8880       // This is a pointer to pointer parameter.
8881       // Recursively check inner type.
8882       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8883       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8884           ParamKind == InvalidKernelParam)
8885         return ParamKind;
8886 
8887       return PtrPtrKernelParam;
8888     }
8889 
8890     // C++ for OpenCL v1.0 s2.4:
8891     // Moreover the types used in parameters of the kernel functions must be:
8892     // Standard layout types for pointer parameters. The same applies to
8893     // reference if an implementation supports them in kernel parameters.
8894     if (S.getLangOpts().OpenCLCPlusPlus &&
8895         !S.getOpenCLOptions().isAvailableOption(
8896             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8897         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8898         !PointeeType->isStandardLayoutType())
8899       return InvalidKernelParam;
8900 
8901     return PtrKernelParam;
8902   }
8903 
8904   // OpenCL v1.2 s6.9.k:
8905   // Arguments to kernel functions in a program cannot be declared with the
8906   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8907   // uintptr_t or a struct and/or union that contain fields declared to be one
8908   // of these built-in scalar types.
8909   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8910     return InvalidKernelParam;
8911 
8912   if (PT->isImageType())
8913     return PtrKernelParam;
8914 
8915   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8916     return InvalidKernelParam;
8917 
8918   // OpenCL extension spec v1.2 s9.5:
8919   // This extension adds support for half scalar and vector types as built-in
8920   // types that can be used for arithmetic operations, conversions etc.
8921   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8922       PT->isHalfType())
8923     return InvalidKernelParam;
8924 
8925   // Look into an array argument to check if it has a forbidden type.
8926   if (PT->isArrayType()) {
8927     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8928     // Call ourself to check an underlying type of an array. Since the
8929     // getPointeeOrArrayElementType returns an innermost type which is not an
8930     // array, this recursive call only happens once.
8931     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8932   }
8933 
8934   // C++ for OpenCL v1.0 s2.4:
8935   // Moreover the types used in parameters of the kernel functions must be:
8936   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8937   // types) for parameters passed by value;
8938   if (S.getLangOpts().OpenCLCPlusPlus &&
8939       !S.getOpenCLOptions().isAvailableOption(
8940           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8941       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8942     return InvalidKernelParam;
8943 
8944   if (PT->isRecordType())
8945     return RecordKernelParam;
8946 
8947   return ValidKernelParam;
8948 }
8949 
8950 static void checkIsValidOpenCLKernelParameter(
8951   Sema &S,
8952   Declarator &D,
8953   ParmVarDecl *Param,
8954   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8955   QualType PT = Param->getType();
8956 
8957   // Cache the valid types we encounter to avoid rechecking structs that are
8958   // used again
8959   if (ValidTypes.count(PT.getTypePtr()))
8960     return;
8961 
8962   switch (getOpenCLKernelParameterType(S, PT)) {
8963   case PtrPtrKernelParam:
8964     // OpenCL v3.0 s6.11.a:
8965     // A kernel function argument cannot be declared as a pointer to a pointer
8966     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8967     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8968       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8969       D.setInvalidType();
8970       return;
8971     }
8972 
8973     ValidTypes.insert(PT.getTypePtr());
8974     return;
8975 
8976   case InvalidAddrSpacePtrKernelParam:
8977     // OpenCL v1.0 s6.5:
8978     // __kernel function arguments declared to be a pointer of a type can point
8979     // to one of the following address spaces only : __global, __local or
8980     // __constant.
8981     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8982     D.setInvalidType();
8983     return;
8984 
8985     // OpenCL v1.2 s6.9.k:
8986     // Arguments to kernel functions in a program cannot be declared with the
8987     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8988     // uintptr_t or a struct and/or union that contain fields declared to be
8989     // one of these built-in scalar types.
8990 
8991   case InvalidKernelParam:
8992     // OpenCL v1.2 s6.8 n:
8993     // A kernel function argument cannot be declared
8994     // of event_t type.
8995     // Do not diagnose half type since it is diagnosed as invalid argument
8996     // type for any function elsewhere.
8997     if (!PT->isHalfType()) {
8998       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8999 
9000       // Explain what typedefs are involved.
9001       const TypedefType *Typedef = nullptr;
9002       while ((Typedef = PT->getAs<TypedefType>())) {
9003         SourceLocation Loc = Typedef->getDecl()->getLocation();
9004         // SourceLocation may be invalid for a built-in type.
9005         if (Loc.isValid())
9006           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9007         PT = Typedef->desugar();
9008       }
9009     }
9010 
9011     D.setInvalidType();
9012     return;
9013 
9014   case PtrKernelParam:
9015   case ValidKernelParam:
9016     ValidTypes.insert(PT.getTypePtr());
9017     return;
9018 
9019   case RecordKernelParam:
9020     break;
9021   }
9022 
9023   // Track nested structs we will inspect
9024   SmallVector<const Decl *, 4> VisitStack;
9025 
9026   // Track where we are in the nested structs. Items will migrate from
9027   // VisitStack to HistoryStack as we do the DFS for bad field.
9028   SmallVector<const FieldDecl *, 4> HistoryStack;
9029   HistoryStack.push_back(nullptr);
9030 
9031   // At this point we already handled everything except of a RecordType or
9032   // an ArrayType of a RecordType.
9033   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9034   const RecordType *RecTy =
9035       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9036   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9037 
9038   VisitStack.push_back(RecTy->getDecl());
9039   assert(VisitStack.back() && "First decl null?");
9040 
9041   do {
9042     const Decl *Next = VisitStack.pop_back_val();
9043     if (!Next) {
9044       assert(!HistoryStack.empty());
9045       // Found a marker, we have gone up a level
9046       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9047         ValidTypes.insert(Hist->getType().getTypePtr());
9048 
9049       continue;
9050     }
9051 
9052     // Adds everything except the original parameter declaration (which is not a
9053     // field itself) to the history stack.
9054     const RecordDecl *RD;
9055     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9056       HistoryStack.push_back(Field);
9057 
9058       QualType FieldTy = Field->getType();
9059       // Other field types (known to be valid or invalid) are handled while we
9060       // walk around RecordDecl::fields().
9061       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9062              "Unexpected type.");
9063       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9064 
9065       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9066     } else {
9067       RD = cast<RecordDecl>(Next);
9068     }
9069 
9070     // Add a null marker so we know when we've gone back up a level
9071     VisitStack.push_back(nullptr);
9072 
9073     for (const auto *FD : RD->fields()) {
9074       QualType QT = FD->getType();
9075 
9076       if (ValidTypes.count(QT.getTypePtr()))
9077         continue;
9078 
9079       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9080       if (ParamType == ValidKernelParam)
9081         continue;
9082 
9083       if (ParamType == RecordKernelParam) {
9084         VisitStack.push_back(FD);
9085         continue;
9086       }
9087 
9088       // OpenCL v1.2 s6.9.p:
9089       // Arguments to kernel functions that are declared to be a struct or union
9090       // do not allow OpenCL objects to be passed as elements of the struct or
9091       // union.
9092       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9093           ParamType == InvalidAddrSpacePtrKernelParam) {
9094         S.Diag(Param->getLocation(),
9095                diag::err_record_with_pointers_kernel_param)
9096           << PT->isUnionType()
9097           << PT;
9098       } else {
9099         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9100       }
9101 
9102       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9103           << OrigRecDecl->getDeclName();
9104 
9105       // We have an error, now let's go back up through history and show where
9106       // the offending field came from
9107       for (ArrayRef<const FieldDecl *>::const_iterator
9108                I = HistoryStack.begin() + 1,
9109                E = HistoryStack.end();
9110            I != E; ++I) {
9111         const FieldDecl *OuterField = *I;
9112         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9113           << OuterField->getType();
9114       }
9115 
9116       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9117         << QT->isPointerType()
9118         << QT;
9119       D.setInvalidType();
9120       return;
9121     }
9122   } while (!VisitStack.empty());
9123 }
9124 
9125 /// Find the DeclContext in which a tag is implicitly declared if we see an
9126 /// elaborated type specifier in the specified context, and lookup finds
9127 /// nothing.
9128 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9129   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9130     DC = DC->getParent();
9131   return DC;
9132 }
9133 
9134 /// Find the Scope in which a tag is implicitly declared if we see an
9135 /// elaborated type specifier in the specified context, and lookup finds
9136 /// nothing.
9137 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9138   while (S->isClassScope() ||
9139          (LangOpts.CPlusPlus &&
9140           S->isFunctionPrototypeScope()) ||
9141          ((S->getFlags() & Scope::DeclScope) == 0) ||
9142          (S->getEntity() && S->getEntity()->isTransparentContext()))
9143     S = S->getParent();
9144   return S;
9145 }
9146 
9147 NamedDecl*
9148 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9149                               TypeSourceInfo *TInfo, LookupResult &Previous,
9150                               MultiTemplateParamsArg TemplateParamListsRef,
9151                               bool &AddToScope) {
9152   QualType R = TInfo->getType();
9153 
9154   assert(R->isFunctionType());
9155   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9156     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9157 
9158   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9159   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9160   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9161     if (!TemplateParamLists.empty() &&
9162         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9163       TemplateParamLists.back() = Invented;
9164     else
9165       TemplateParamLists.push_back(Invented);
9166   }
9167 
9168   // TODO: consider using NameInfo for diagnostic.
9169   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9170   DeclarationName Name = NameInfo.getName();
9171   StorageClass SC = getFunctionStorageClass(*this, D);
9172 
9173   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9174     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9175          diag::err_invalid_thread)
9176       << DeclSpec::getSpecifierName(TSCS);
9177 
9178   if (D.isFirstDeclarationOfMember())
9179     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9180                            D.getIdentifierLoc());
9181 
9182   bool isFriend = false;
9183   FunctionTemplateDecl *FunctionTemplate = nullptr;
9184   bool isMemberSpecialization = false;
9185   bool isFunctionTemplateSpecialization = false;
9186 
9187   bool isDependentClassScopeExplicitSpecialization = false;
9188   bool HasExplicitTemplateArgs = false;
9189   TemplateArgumentListInfo TemplateArgs;
9190 
9191   bool isVirtualOkay = false;
9192 
9193   DeclContext *OriginalDC = DC;
9194   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9195 
9196   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9197                                               isVirtualOkay);
9198   if (!NewFD) return nullptr;
9199 
9200   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9201     NewFD->setTopLevelDeclInObjCContainer();
9202 
9203   // Set the lexical context. If this is a function-scope declaration, or has a
9204   // C++ scope specifier, or is the object of a friend declaration, the lexical
9205   // context will be different from the semantic context.
9206   NewFD->setLexicalDeclContext(CurContext);
9207 
9208   if (IsLocalExternDecl)
9209     NewFD->setLocalExternDecl();
9210 
9211   if (getLangOpts().CPlusPlus) {
9212     bool isInline = D.getDeclSpec().isInlineSpecified();
9213     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9214     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9215     isFriend = D.getDeclSpec().isFriendSpecified();
9216     if (isFriend && !isInline && D.isFunctionDefinition()) {
9217       // C++ [class.friend]p5
9218       //   A function can be defined in a friend declaration of a
9219       //   class . . . . Such a function is implicitly inline.
9220       NewFD->setImplicitlyInline();
9221     }
9222 
9223     // If this is a method defined in an __interface, and is not a constructor
9224     // or an overloaded operator, then set the pure flag (isVirtual will already
9225     // return true).
9226     if (const CXXRecordDecl *Parent =
9227           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9228       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9229         NewFD->setPure(true);
9230 
9231       // C++ [class.union]p2
9232       //   A union can have member functions, but not virtual functions.
9233       if (isVirtual && Parent->isUnion()) {
9234         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9235         NewFD->setInvalidDecl();
9236       }
9237       if ((Parent->isClass() || Parent->isStruct()) &&
9238           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9239           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9240           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9241         if (auto *Def = Parent->getDefinition())
9242           Def->setInitMethod(true);
9243       }
9244     }
9245 
9246     SetNestedNameSpecifier(*this, NewFD, D);
9247     isMemberSpecialization = false;
9248     isFunctionTemplateSpecialization = false;
9249     if (D.isInvalidType())
9250       NewFD->setInvalidDecl();
9251 
9252     // Match up the template parameter lists with the scope specifier, then
9253     // determine whether we have a template or a template specialization.
9254     bool Invalid = false;
9255     TemplateParameterList *TemplateParams =
9256         MatchTemplateParametersToScopeSpecifier(
9257             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9258             D.getCXXScopeSpec(),
9259             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9260                 ? D.getName().TemplateId
9261                 : nullptr,
9262             TemplateParamLists, isFriend, isMemberSpecialization,
9263             Invalid);
9264     if (TemplateParams) {
9265       // Check that we can declare a template here.
9266       if (CheckTemplateDeclScope(S, TemplateParams))
9267         NewFD->setInvalidDecl();
9268 
9269       if (TemplateParams->size() > 0) {
9270         // This is a function template
9271 
9272         // A destructor cannot be a template.
9273         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9274           Diag(NewFD->getLocation(), diag::err_destructor_template);
9275           NewFD->setInvalidDecl();
9276         }
9277 
9278         // If we're adding a template to a dependent context, we may need to
9279         // rebuilding some of the types used within the template parameter list,
9280         // now that we know what the current instantiation is.
9281         if (DC->isDependentContext()) {
9282           ContextRAII SavedContext(*this, DC);
9283           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9284             Invalid = true;
9285         }
9286 
9287         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9288                                                         NewFD->getLocation(),
9289                                                         Name, TemplateParams,
9290                                                         NewFD);
9291         FunctionTemplate->setLexicalDeclContext(CurContext);
9292         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9293 
9294         // For source fidelity, store the other template param lists.
9295         if (TemplateParamLists.size() > 1) {
9296           NewFD->setTemplateParameterListsInfo(Context,
9297               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9298                   .drop_back(1));
9299         }
9300       } else {
9301         // This is a function template specialization.
9302         isFunctionTemplateSpecialization = true;
9303         // For source fidelity, store all the template param lists.
9304         if (TemplateParamLists.size() > 0)
9305           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9306 
9307         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9308         if (isFriend) {
9309           // We want to remove the "template<>", found here.
9310           SourceRange RemoveRange = TemplateParams->getSourceRange();
9311 
9312           // If we remove the template<> and the name is not a
9313           // template-id, we're actually silently creating a problem:
9314           // the friend declaration will refer to an untemplated decl,
9315           // and clearly the user wants a template specialization.  So
9316           // we need to insert '<>' after the name.
9317           SourceLocation InsertLoc;
9318           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9319             InsertLoc = D.getName().getSourceRange().getEnd();
9320             InsertLoc = getLocForEndOfToken(InsertLoc);
9321           }
9322 
9323           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9324             << Name << RemoveRange
9325             << FixItHint::CreateRemoval(RemoveRange)
9326             << FixItHint::CreateInsertion(InsertLoc, "<>");
9327           Invalid = true;
9328         }
9329       }
9330     } else {
9331       // Check that we can declare a template here.
9332       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9333           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9334         NewFD->setInvalidDecl();
9335 
9336       // All template param lists were matched against the scope specifier:
9337       // this is NOT (an explicit specialization of) a template.
9338       if (TemplateParamLists.size() > 0)
9339         // For source fidelity, store all the template param lists.
9340         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9341     }
9342 
9343     if (Invalid) {
9344       NewFD->setInvalidDecl();
9345       if (FunctionTemplate)
9346         FunctionTemplate->setInvalidDecl();
9347     }
9348 
9349     // C++ [dcl.fct.spec]p5:
9350     //   The virtual specifier shall only be used in declarations of
9351     //   nonstatic class member functions that appear within a
9352     //   member-specification of a class declaration; see 10.3.
9353     //
9354     if (isVirtual && !NewFD->isInvalidDecl()) {
9355       if (!isVirtualOkay) {
9356         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9357              diag::err_virtual_non_function);
9358       } else if (!CurContext->isRecord()) {
9359         // 'virtual' was specified outside of the class.
9360         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9361              diag::err_virtual_out_of_class)
9362           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9363       } else if (NewFD->getDescribedFunctionTemplate()) {
9364         // C++ [temp.mem]p3:
9365         //  A member function template shall not be virtual.
9366         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9367              diag::err_virtual_member_function_template)
9368           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9369       } else {
9370         // Okay: Add virtual to the method.
9371         NewFD->setVirtualAsWritten(true);
9372       }
9373 
9374       if (getLangOpts().CPlusPlus14 &&
9375           NewFD->getReturnType()->isUndeducedType())
9376         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9377     }
9378 
9379     if (getLangOpts().CPlusPlus14 &&
9380         (NewFD->isDependentContext() ||
9381          (isFriend && CurContext->isDependentContext())) &&
9382         NewFD->getReturnType()->isUndeducedType()) {
9383       // If the function template is referenced directly (for instance, as a
9384       // member of the current instantiation), pretend it has a dependent type.
9385       // This is not really justified by the standard, but is the only sane
9386       // thing to do.
9387       // FIXME: For a friend function, we have not marked the function as being
9388       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9389       const FunctionProtoType *FPT =
9390           NewFD->getType()->castAs<FunctionProtoType>();
9391       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9392       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9393                                              FPT->getExtProtoInfo()));
9394     }
9395 
9396     // C++ [dcl.fct.spec]p3:
9397     //  The inline specifier shall not appear on a block scope function
9398     //  declaration.
9399     if (isInline && !NewFD->isInvalidDecl()) {
9400       if (CurContext->isFunctionOrMethod()) {
9401         // 'inline' is not allowed on block scope function declaration.
9402         Diag(D.getDeclSpec().getInlineSpecLoc(),
9403              diag::err_inline_declaration_block_scope) << Name
9404           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9405       }
9406     }
9407 
9408     // C++ [dcl.fct.spec]p6:
9409     //  The explicit specifier shall be used only in the declaration of a
9410     //  constructor or conversion function within its class definition;
9411     //  see 12.3.1 and 12.3.2.
9412     if (hasExplicit && !NewFD->isInvalidDecl() &&
9413         !isa<CXXDeductionGuideDecl>(NewFD)) {
9414       if (!CurContext->isRecord()) {
9415         // 'explicit' was specified outside of the class.
9416         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9417              diag::err_explicit_out_of_class)
9418             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9419       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9420                  !isa<CXXConversionDecl>(NewFD)) {
9421         // 'explicit' was specified on a function that wasn't a constructor
9422         // or conversion function.
9423         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9424              diag::err_explicit_non_ctor_or_conv_function)
9425             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9426       }
9427     }
9428 
9429     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9430     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9431       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9432       // are implicitly inline.
9433       NewFD->setImplicitlyInline();
9434 
9435       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9436       // be either constructors or to return a literal type. Therefore,
9437       // destructors cannot be declared constexpr.
9438       if (isa<CXXDestructorDecl>(NewFD) &&
9439           (!getLangOpts().CPlusPlus20 ||
9440            ConstexprKind == ConstexprSpecKind::Consteval)) {
9441         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9442             << static_cast<int>(ConstexprKind);
9443         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9444                                     ? ConstexprSpecKind::Unspecified
9445                                     : ConstexprSpecKind::Constexpr);
9446       }
9447       // C++20 [dcl.constexpr]p2: An allocation function, or a
9448       // deallocation function shall not be declared with the consteval
9449       // specifier.
9450       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9451           (NewFD->getOverloadedOperator() == OO_New ||
9452            NewFD->getOverloadedOperator() == OO_Array_New ||
9453            NewFD->getOverloadedOperator() == OO_Delete ||
9454            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9455         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9456              diag::err_invalid_consteval_decl_kind)
9457             << NewFD;
9458         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9459       }
9460     }
9461 
9462     // If __module_private__ was specified, mark the function accordingly.
9463     if (D.getDeclSpec().isModulePrivateSpecified()) {
9464       if (isFunctionTemplateSpecialization) {
9465         SourceLocation ModulePrivateLoc
9466           = D.getDeclSpec().getModulePrivateSpecLoc();
9467         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9468           << 0
9469           << FixItHint::CreateRemoval(ModulePrivateLoc);
9470       } else {
9471         NewFD->setModulePrivate();
9472         if (FunctionTemplate)
9473           FunctionTemplate->setModulePrivate();
9474       }
9475     }
9476 
9477     if (isFriend) {
9478       if (FunctionTemplate) {
9479         FunctionTemplate->setObjectOfFriendDecl();
9480         FunctionTemplate->setAccess(AS_public);
9481       }
9482       NewFD->setObjectOfFriendDecl();
9483       NewFD->setAccess(AS_public);
9484     }
9485 
9486     // If a function is defined as defaulted or deleted, mark it as such now.
9487     // We'll do the relevant checks on defaulted / deleted functions later.
9488     switch (D.getFunctionDefinitionKind()) {
9489     case FunctionDefinitionKind::Declaration:
9490     case FunctionDefinitionKind::Definition:
9491       break;
9492 
9493     case FunctionDefinitionKind::Defaulted:
9494       NewFD->setDefaulted();
9495       break;
9496 
9497     case FunctionDefinitionKind::Deleted:
9498       NewFD->setDeletedAsWritten();
9499       break;
9500     }
9501 
9502     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9503         D.isFunctionDefinition()) {
9504       // C++ [class.mfct]p2:
9505       //   A member function may be defined (8.4) in its class definition, in
9506       //   which case it is an inline member function (7.1.2)
9507       NewFD->setImplicitlyInline();
9508     }
9509 
9510     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9511         !CurContext->isRecord()) {
9512       // C++ [class.static]p1:
9513       //   A data or function member of a class may be declared static
9514       //   in a class definition, in which case it is a static member of
9515       //   the class.
9516 
9517       // Complain about the 'static' specifier if it's on an out-of-line
9518       // member function definition.
9519 
9520       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9521       // member function template declaration and class member template
9522       // declaration (MSVC versions before 2015), warn about this.
9523       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9524            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9525              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9526            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9527            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9528         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9529     }
9530 
9531     // C++11 [except.spec]p15:
9532     //   A deallocation function with no exception-specification is treated
9533     //   as if it were specified with noexcept(true).
9534     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9535     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9536          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9537         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9538       NewFD->setType(Context.getFunctionType(
9539           FPT->getReturnType(), FPT->getParamTypes(),
9540           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9541   }
9542 
9543   // Filter out previous declarations that don't match the scope.
9544   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9545                        D.getCXXScopeSpec().isNotEmpty() ||
9546                        isMemberSpecialization ||
9547                        isFunctionTemplateSpecialization);
9548 
9549   // Handle GNU asm-label extension (encoded as an attribute).
9550   if (Expr *E = (Expr*) D.getAsmLabel()) {
9551     // The parser guarantees this is a string.
9552     StringLiteral *SE = cast<StringLiteral>(E);
9553     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9554                                         /*IsLiteralLabel=*/true,
9555                                         SE->getStrTokenLoc(0)));
9556   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9557     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9558       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9559     if (I != ExtnameUndeclaredIdentifiers.end()) {
9560       if (isDeclExternC(NewFD)) {
9561         NewFD->addAttr(I->second);
9562         ExtnameUndeclaredIdentifiers.erase(I);
9563       } else
9564         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9565             << /*Variable*/0 << NewFD;
9566     }
9567   }
9568 
9569   // Copy the parameter declarations from the declarator D to the function
9570   // declaration NewFD, if they are available.  First scavenge them into Params.
9571   SmallVector<ParmVarDecl*, 16> Params;
9572   unsigned FTIIdx;
9573   if (D.isFunctionDeclarator(FTIIdx)) {
9574     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9575 
9576     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9577     // function that takes no arguments, not a function that takes a
9578     // single void argument.
9579     // We let through "const void" here because Sema::GetTypeForDeclarator
9580     // already checks for that case.
9581     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9582       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9583         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9584         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9585         Param->setDeclContext(NewFD);
9586         Params.push_back(Param);
9587 
9588         if (Param->isInvalidDecl())
9589           NewFD->setInvalidDecl();
9590       }
9591     }
9592 
9593     if (!getLangOpts().CPlusPlus) {
9594       // In C, find all the tag declarations from the prototype and move them
9595       // into the function DeclContext. Remove them from the surrounding tag
9596       // injection context of the function, which is typically but not always
9597       // the TU.
9598       DeclContext *PrototypeTagContext =
9599           getTagInjectionContext(NewFD->getLexicalDeclContext());
9600       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9601         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9602 
9603         // We don't want to reparent enumerators. Look at their parent enum
9604         // instead.
9605         if (!TD) {
9606           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9607             TD = cast<EnumDecl>(ECD->getDeclContext());
9608         }
9609         if (!TD)
9610           continue;
9611         DeclContext *TagDC = TD->getLexicalDeclContext();
9612         if (!TagDC->containsDecl(TD))
9613           continue;
9614         TagDC->removeDecl(TD);
9615         TD->setDeclContext(NewFD);
9616         NewFD->addDecl(TD);
9617 
9618         // Preserve the lexical DeclContext if it is not the surrounding tag
9619         // injection context of the FD. In this example, the semantic context of
9620         // E will be f and the lexical context will be S, while both the
9621         // semantic and lexical contexts of S will be f:
9622         //   void f(struct S { enum E { a } f; } s);
9623         if (TagDC != PrototypeTagContext)
9624           TD->setLexicalDeclContext(TagDC);
9625       }
9626     }
9627   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9628     // When we're declaring a function with a typedef, typeof, etc as in the
9629     // following example, we'll need to synthesize (unnamed)
9630     // parameters for use in the declaration.
9631     //
9632     // @code
9633     // typedef void fn(int);
9634     // fn f;
9635     // @endcode
9636 
9637     // Synthesize a parameter for each argument type.
9638     for (const auto &AI : FT->param_types()) {
9639       ParmVarDecl *Param =
9640           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9641       Param->setScopeInfo(0, Params.size());
9642       Params.push_back(Param);
9643     }
9644   } else {
9645     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9646            "Should not need args for typedef of non-prototype fn");
9647   }
9648 
9649   // Finally, we know we have the right number of parameters, install them.
9650   NewFD->setParams(Params);
9651 
9652   if (D.getDeclSpec().isNoreturnSpecified())
9653     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9654                                            D.getDeclSpec().getNoreturnSpecLoc(),
9655                                            AttributeCommonInfo::AS_Keyword));
9656 
9657   // Functions returning a variably modified type violate C99 6.7.5.2p2
9658   // because all functions have linkage.
9659   if (!NewFD->isInvalidDecl() &&
9660       NewFD->getReturnType()->isVariablyModifiedType()) {
9661     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9662     NewFD->setInvalidDecl();
9663   }
9664 
9665   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9666   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9667       !NewFD->hasAttr<SectionAttr>())
9668     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9669         Context, PragmaClangTextSection.SectionName,
9670         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9671 
9672   // Apply an implicit SectionAttr if #pragma code_seg is active.
9673   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9674       !NewFD->hasAttr<SectionAttr>()) {
9675     NewFD->addAttr(SectionAttr::CreateImplicit(
9676         Context, CodeSegStack.CurrentValue->getString(),
9677         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9678         SectionAttr::Declspec_allocate));
9679     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9680                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9681                          ASTContext::PSF_Read,
9682                      NewFD))
9683       NewFD->dropAttr<SectionAttr>();
9684   }
9685 
9686   // Apply an implicit CodeSegAttr from class declspec or
9687   // apply an implicit SectionAttr from #pragma code_seg if active.
9688   if (!NewFD->hasAttr<CodeSegAttr>()) {
9689     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9690                                                                  D.isFunctionDefinition())) {
9691       NewFD->addAttr(SAttr);
9692     }
9693   }
9694 
9695   // Handle attributes.
9696   ProcessDeclAttributes(S, NewFD, D);
9697 
9698   if (getLangOpts().OpenCL) {
9699     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9700     // type declaration will generate a compilation error.
9701     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9702     if (AddressSpace != LangAS::Default) {
9703       Diag(NewFD->getLocation(),
9704            diag::err_opencl_return_value_with_address_space);
9705       NewFD->setInvalidDecl();
9706     }
9707   }
9708 
9709   if (!getLangOpts().CPlusPlus) {
9710     // Perform semantic checking on the function declaration.
9711     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9712       CheckMain(NewFD, D.getDeclSpec());
9713 
9714     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9715       CheckMSVCRTEntryPoint(NewFD);
9716 
9717     if (!NewFD->isInvalidDecl())
9718       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9719                                                   isMemberSpecialization));
9720     else if (!Previous.empty())
9721       // Recover gracefully from an invalid redeclaration.
9722       D.setRedeclaration(true);
9723     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9724             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9725            "previous declaration set still overloaded");
9726 
9727     // Diagnose no-prototype function declarations with calling conventions that
9728     // don't support variadic calls. Only do this in C and do it after merging
9729     // possibly prototyped redeclarations.
9730     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9731     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9732       CallingConv CC = FT->getExtInfo().getCC();
9733       if (!supportsVariadicCall(CC)) {
9734         // Windows system headers sometimes accidentally use stdcall without
9735         // (void) parameters, so we relax this to a warning.
9736         int DiagID =
9737             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9738         Diag(NewFD->getLocation(), DiagID)
9739             << FunctionType::getNameForCallConv(CC);
9740       }
9741     }
9742 
9743    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9744        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9745      checkNonTrivialCUnion(NewFD->getReturnType(),
9746                            NewFD->getReturnTypeSourceRange().getBegin(),
9747                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9748   } else {
9749     // C++11 [replacement.functions]p3:
9750     //  The program's definitions shall not be specified as inline.
9751     //
9752     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9753     //
9754     // Suppress the diagnostic if the function is __attribute__((used)), since
9755     // that forces an external definition to be emitted.
9756     if (D.getDeclSpec().isInlineSpecified() &&
9757         NewFD->isReplaceableGlobalAllocationFunction() &&
9758         !NewFD->hasAttr<UsedAttr>())
9759       Diag(D.getDeclSpec().getInlineSpecLoc(),
9760            diag::ext_operator_new_delete_declared_inline)
9761         << NewFD->getDeclName();
9762 
9763     // If the declarator is a template-id, translate the parser's template
9764     // argument list into our AST format.
9765     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9766       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9767       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9768       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9769       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9770                                          TemplateId->NumArgs);
9771       translateTemplateArguments(TemplateArgsPtr,
9772                                  TemplateArgs);
9773 
9774       HasExplicitTemplateArgs = true;
9775 
9776       if (NewFD->isInvalidDecl()) {
9777         HasExplicitTemplateArgs = false;
9778       } else if (FunctionTemplate) {
9779         // Function template with explicit template arguments.
9780         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9781           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9782 
9783         HasExplicitTemplateArgs = false;
9784       } else {
9785         assert((isFunctionTemplateSpecialization ||
9786                 D.getDeclSpec().isFriendSpecified()) &&
9787                "should have a 'template<>' for this decl");
9788         // "friend void foo<>(int);" is an implicit specialization decl.
9789         isFunctionTemplateSpecialization = true;
9790       }
9791     } else if (isFriend && isFunctionTemplateSpecialization) {
9792       // This combination is only possible in a recovery case;  the user
9793       // wrote something like:
9794       //   template <> friend void foo(int);
9795       // which we're recovering from as if the user had written:
9796       //   friend void foo<>(int);
9797       // Go ahead and fake up a template id.
9798       HasExplicitTemplateArgs = true;
9799       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9800       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9801     }
9802 
9803     // We do not add HD attributes to specializations here because
9804     // they may have different constexpr-ness compared to their
9805     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9806     // may end up with different effective targets. Instead, a
9807     // specialization inherits its target attributes from its template
9808     // in the CheckFunctionTemplateSpecialization() call below.
9809     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9810       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9811 
9812     // If it's a friend (and only if it's a friend), it's possible
9813     // that either the specialized function type or the specialized
9814     // template is dependent, and therefore matching will fail.  In
9815     // this case, don't check the specialization yet.
9816     if (isFunctionTemplateSpecialization && isFriend &&
9817         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9818          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9819              TemplateArgs.arguments()))) {
9820       assert(HasExplicitTemplateArgs &&
9821              "friend function specialization without template args");
9822       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9823                                                        Previous))
9824         NewFD->setInvalidDecl();
9825     } else if (isFunctionTemplateSpecialization) {
9826       if (CurContext->isDependentContext() && CurContext->isRecord()
9827           && !isFriend) {
9828         isDependentClassScopeExplicitSpecialization = true;
9829       } else if (!NewFD->isInvalidDecl() &&
9830                  CheckFunctionTemplateSpecialization(
9831                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9832                      Previous))
9833         NewFD->setInvalidDecl();
9834 
9835       // C++ [dcl.stc]p1:
9836       //   A storage-class-specifier shall not be specified in an explicit
9837       //   specialization (14.7.3)
9838       FunctionTemplateSpecializationInfo *Info =
9839           NewFD->getTemplateSpecializationInfo();
9840       if (Info && SC != SC_None) {
9841         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9842           Diag(NewFD->getLocation(),
9843                diag::err_explicit_specialization_inconsistent_storage_class)
9844             << SC
9845             << FixItHint::CreateRemoval(
9846                                       D.getDeclSpec().getStorageClassSpecLoc());
9847 
9848         else
9849           Diag(NewFD->getLocation(),
9850                diag::ext_explicit_specialization_storage_class)
9851             << FixItHint::CreateRemoval(
9852                                       D.getDeclSpec().getStorageClassSpecLoc());
9853       }
9854     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9855       if (CheckMemberSpecialization(NewFD, Previous))
9856           NewFD->setInvalidDecl();
9857     }
9858 
9859     // Perform semantic checking on the function declaration.
9860     if (!isDependentClassScopeExplicitSpecialization) {
9861       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9862         CheckMain(NewFD, D.getDeclSpec());
9863 
9864       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9865         CheckMSVCRTEntryPoint(NewFD);
9866 
9867       if (!NewFD->isInvalidDecl())
9868         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9869                                                     isMemberSpecialization));
9870       else if (!Previous.empty())
9871         // Recover gracefully from an invalid redeclaration.
9872         D.setRedeclaration(true);
9873     }
9874 
9875     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9876             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9877            "previous declaration set still overloaded");
9878 
9879     NamedDecl *PrincipalDecl = (FunctionTemplate
9880                                 ? cast<NamedDecl>(FunctionTemplate)
9881                                 : NewFD);
9882 
9883     if (isFriend && NewFD->getPreviousDecl()) {
9884       AccessSpecifier Access = AS_public;
9885       if (!NewFD->isInvalidDecl())
9886         Access = NewFD->getPreviousDecl()->getAccess();
9887 
9888       NewFD->setAccess(Access);
9889       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9890     }
9891 
9892     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9893         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9894       PrincipalDecl->setNonMemberOperator();
9895 
9896     // If we have a function template, check the template parameter
9897     // list. This will check and merge default template arguments.
9898     if (FunctionTemplate) {
9899       FunctionTemplateDecl *PrevTemplate =
9900                                      FunctionTemplate->getPreviousDecl();
9901       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9902                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9903                                     : nullptr,
9904                             D.getDeclSpec().isFriendSpecified()
9905                               ? (D.isFunctionDefinition()
9906                                    ? TPC_FriendFunctionTemplateDefinition
9907                                    : TPC_FriendFunctionTemplate)
9908                               : (D.getCXXScopeSpec().isSet() &&
9909                                  DC && DC->isRecord() &&
9910                                  DC->isDependentContext())
9911                                   ? TPC_ClassTemplateMember
9912                                   : TPC_FunctionTemplate);
9913     }
9914 
9915     if (NewFD->isInvalidDecl()) {
9916       // Ignore all the rest of this.
9917     } else if (!D.isRedeclaration()) {
9918       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9919                                        AddToScope };
9920       // Fake up an access specifier if it's supposed to be a class member.
9921       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9922         NewFD->setAccess(AS_public);
9923 
9924       // Qualified decls generally require a previous declaration.
9925       if (D.getCXXScopeSpec().isSet()) {
9926         // ...with the major exception of templated-scope or
9927         // dependent-scope friend declarations.
9928 
9929         // TODO: we currently also suppress this check in dependent
9930         // contexts because (1) the parameter depth will be off when
9931         // matching friend templates and (2) we might actually be
9932         // selecting a friend based on a dependent factor.  But there
9933         // are situations where these conditions don't apply and we
9934         // can actually do this check immediately.
9935         //
9936         // Unless the scope is dependent, it's always an error if qualified
9937         // redeclaration lookup found nothing at all. Diagnose that now;
9938         // nothing will diagnose that error later.
9939         if (isFriend &&
9940             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9941              (!Previous.empty() && CurContext->isDependentContext()))) {
9942           // ignore these
9943         } else if (NewFD->isCPUDispatchMultiVersion() ||
9944                    NewFD->isCPUSpecificMultiVersion()) {
9945           // ignore this, we allow the redeclaration behavior here to create new
9946           // versions of the function.
9947         } else {
9948           // The user tried to provide an out-of-line definition for a
9949           // function that is a member of a class or namespace, but there
9950           // was no such member function declared (C++ [class.mfct]p2,
9951           // C++ [namespace.memdef]p2). For example:
9952           //
9953           // class X {
9954           //   void f() const;
9955           // };
9956           //
9957           // void X::f() { } // ill-formed
9958           //
9959           // Complain about this problem, and attempt to suggest close
9960           // matches (e.g., those that differ only in cv-qualifiers and
9961           // whether the parameter types are references).
9962 
9963           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9964                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9965             AddToScope = ExtraArgs.AddToScope;
9966             return Result;
9967           }
9968         }
9969 
9970         // Unqualified local friend declarations are required to resolve
9971         // to something.
9972       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9973         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9974                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9975           AddToScope = ExtraArgs.AddToScope;
9976           return Result;
9977         }
9978       }
9979     } else if (!D.isFunctionDefinition() &&
9980                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9981                !isFriend && !isFunctionTemplateSpecialization &&
9982                !isMemberSpecialization) {
9983       // An out-of-line member function declaration must also be a
9984       // definition (C++ [class.mfct]p2).
9985       // Note that this is not the case for explicit specializations of
9986       // function templates or member functions of class templates, per
9987       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9988       // extension for compatibility with old SWIG code which likes to
9989       // generate them.
9990       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9991         << D.getCXXScopeSpec().getRange();
9992     }
9993   }
9994 
9995   // If this is the first declaration of a library builtin function, add
9996   // attributes as appropriate.
9997   if (!D.isRedeclaration() &&
9998       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9999     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10000       if (unsigned BuiltinID = II->getBuiltinID()) {
10001         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10002           // Validate the type matches unless this builtin is specified as
10003           // matching regardless of its declared type.
10004           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10005             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10006           } else {
10007             ASTContext::GetBuiltinTypeError Error;
10008             LookupNecessaryTypesForBuiltin(S, BuiltinID);
10009             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10010 
10011             if (!Error && !BuiltinType.isNull() &&
10012                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10013                     NewFD->getType(), BuiltinType))
10014               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10015           }
10016         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10017                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10018           // FIXME: We should consider this a builtin only in the std namespace.
10019           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10020         }
10021       }
10022     }
10023   }
10024 
10025   ProcessPragmaWeak(S, NewFD);
10026   checkAttributesAfterMerging(*this, *NewFD);
10027 
10028   AddKnownFunctionAttributes(NewFD);
10029 
10030   if (NewFD->hasAttr<OverloadableAttr>() &&
10031       !NewFD->getType()->getAs<FunctionProtoType>()) {
10032     Diag(NewFD->getLocation(),
10033          diag::err_attribute_overloadable_no_prototype)
10034       << NewFD;
10035 
10036     // Turn this into a variadic function with no parameters.
10037     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10038     FunctionProtoType::ExtProtoInfo EPI(
10039         Context.getDefaultCallingConvention(true, false));
10040     EPI.Variadic = true;
10041     EPI.ExtInfo = FT->getExtInfo();
10042 
10043     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10044     NewFD->setType(R);
10045   }
10046 
10047   // If there's a #pragma GCC visibility in scope, and this isn't a class
10048   // member, set the visibility of this function.
10049   if (!DC->isRecord() && NewFD->isExternallyVisible())
10050     AddPushedVisibilityAttribute(NewFD);
10051 
10052   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10053   // marking the function.
10054   AddCFAuditedAttribute(NewFD);
10055 
10056   // If this is a function definition, check if we have to apply optnone due to
10057   // a pragma.
10058   if(D.isFunctionDefinition())
10059     AddRangeBasedOptnone(NewFD);
10060 
10061   // If this is the first declaration of an extern C variable, update
10062   // the map of such variables.
10063   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10064       isIncompleteDeclExternC(*this, NewFD))
10065     RegisterLocallyScopedExternCDecl(NewFD, S);
10066 
10067   // Set this FunctionDecl's range up to the right paren.
10068   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10069 
10070   if (D.isRedeclaration() && !Previous.empty()) {
10071     NamedDecl *Prev = Previous.getRepresentativeDecl();
10072     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10073                                    isMemberSpecialization ||
10074                                        isFunctionTemplateSpecialization,
10075                                    D.isFunctionDefinition());
10076   }
10077 
10078   if (getLangOpts().CUDA) {
10079     IdentifierInfo *II = NewFD->getIdentifier();
10080     if (II && II->isStr(getCudaConfigureFuncName()) &&
10081         !NewFD->isInvalidDecl() &&
10082         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10083       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10084         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10085             << getCudaConfigureFuncName();
10086       Context.setcudaConfigureCallDecl(NewFD);
10087     }
10088 
10089     // Variadic functions, other than a *declaration* of printf, are not allowed
10090     // in device-side CUDA code, unless someone passed
10091     // -fcuda-allow-variadic-functions.
10092     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10093         (NewFD->hasAttr<CUDADeviceAttr>() ||
10094          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10095         !(II && II->isStr("printf") && NewFD->isExternC() &&
10096           !D.isFunctionDefinition())) {
10097       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10098     }
10099   }
10100 
10101   MarkUnusedFileScopedDecl(NewFD);
10102 
10103 
10104 
10105   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10106     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10107     if (SC == SC_Static) {
10108       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10109       D.setInvalidType();
10110     }
10111 
10112     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10113     if (!NewFD->getReturnType()->isVoidType()) {
10114       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10115       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10116           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10117                                 : FixItHint());
10118       D.setInvalidType();
10119     }
10120 
10121     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10122     for (auto Param : NewFD->parameters())
10123       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10124 
10125     if (getLangOpts().OpenCLCPlusPlus) {
10126       if (DC->isRecord()) {
10127         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10128         D.setInvalidType();
10129       }
10130       if (FunctionTemplate) {
10131         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10132         D.setInvalidType();
10133       }
10134     }
10135   }
10136 
10137   if (getLangOpts().CPlusPlus) {
10138     if (FunctionTemplate) {
10139       if (NewFD->isInvalidDecl())
10140         FunctionTemplate->setInvalidDecl();
10141       return FunctionTemplate;
10142     }
10143 
10144     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10145       CompleteMemberSpecialization(NewFD, Previous);
10146   }
10147 
10148   for (const ParmVarDecl *Param : NewFD->parameters()) {
10149     QualType PT = Param->getType();
10150 
10151     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10152     // types.
10153     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10154       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10155         QualType ElemTy = PipeTy->getElementType();
10156           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10157             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10158             D.setInvalidType();
10159           }
10160       }
10161     }
10162   }
10163 
10164   // Here we have an function template explicit specialization at class scope.
10165   // The actual specialization will be postponed to template instatiation
10166   // time via the ClassScopeFunctionSpecializationDecl node.
10167   if (isDependentClassScopeExplicitSpecialization) {
10168     ClassScopeFunctionSpecializationDecl *NewSpec =
10169                          ClassScopeFunctionSpecializationDecl::Create(
10170                                 Context, CurContext, NewFD->getLocation(),
10171                                 cast<CXXMethodDecl>(NewFD),
10172                                 HasExplicitTemplateArgs, TemplateArgs);
10173     CurContext->addDecl(NewSpec);
10174     AddToScope = false;
10175   }
10176 
10177   // Diagnose availability attributes. Availability cannot be used on functions
10178   // that are run during load/unload.
10179   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10180     if (NewFD->hasAttr<ConstructorAttr>()) {
10181       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10182           << 1;
10183       NewFD->dropAttr<AvailabilityAttr>();
10184     }
10185     if (NewFD->hasAttr<DestructorAttr>()) {
10186       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10187           << 2;
10188       NewFD->dropAttr<AvailabilityAttr>();
10189     }
10190   }
10191 
10192   // Diagnose no_builtin attribute on function declaration that are not a
10193   // definition.
10194   // FIXME: We should really be doing this in
10195   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10196   // the FunctionDecl and at this point of the code
10197   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10198   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10199   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10200     switch (D.getFunctionDefinitionKind()) {
10201     case FunctionDefinitionKind::Defaulted:
10202     case FunctionDefinitionKind::Deleted:
10203       Diag(NBA->getLocation(),
10204            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10205           << NBA->getSpelling();
10206       break;
10207     case FunctionDefinitionKind::Declaration:
10208       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10209           << NBA->getSpelling();
10210       break;
10211     case FunctionDefinitionKind::Definition:
10212       break;
10213     }
10214 
10215   return NewFD;
10216 }
10217 
10218 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10219 /// when __declspec(code_seg) "is applied to a class, all member functions of
10220 /// the class and nested classes -- this includes compiler-generated special
10221 /// member functions -- are put in the specified segment."
10222 /// The actual behavior is a little more complicated. The Microsoft compiler
10223 /// won't check outer classes if there is an active value from #pragma code_seg.
10224 /// The CodeSeg is always applied from the direct parent but only from outer
10225 /// classes when the #pragma code_seg stack is empty. See:
10226 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10227 /// available since MS has removed the page.
10228 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10229   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10230   if (!Method)
10231     return nullptr;
10232   const CXXRecordDecl *Parent = Method->getParent();
10233   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10234     Attr *NewAttr = SAttr->clone(S.getASTContext());
10235     NewAttr->setImplicit(true);
10236     return NewAttr;
10237   }
10238 
10239   // The Microsoft compiler won't check outer classes for the CodeSeg
10240   // when the #pragma code_seg stack is active.
10241   if (S.CodeSegStack.CurrentValue)
10242    return nullptr;
10243 
10244   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10245     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10246       Attr *NewAttr = SAttr->clone(S.getASTContext());
10247       NewAttr->setImplicit(true);
10248       return NewAttr;
10249     }
10250   }
10251   return nullptr;
10252 }
10253 
10254 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10255 /// containing class. Otherwise it will return implicit SectionAttr if the
10256 /// function is a definition and there is an active value on CodeSegStack
10257 /// (from the current #pragma code-seg value).
10258 ///
10259 /// \param FD Function being declared.
10260 /// \param IsDefinition Whether it is a definition or just a declarartion.
10261 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10262 ///          nullptr if no attribute should be added.
10263 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10264                                                        bool IsDefinition) {
10265   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10266     return A;
10267   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10268       CodeSegStack.CurrentValue)
10269     return SectionAttr::CreateImplicit(
10270         getASTContext(), CodeSegStack.CurrentValue->getString(),
10271         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10272         SectionAttr::Declspec_allocate);
10273   return nullptr;
10274 }
10275 
10276 /// Determines if we can perform a correct type check for \p D as a
10277 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10278 /// best-effort check.
10279 ///
10280 /// \param NewD The new declaration.
10281 /// \param OldD The old declaration.
10282 /// \param NewT The portion of the type of the new declaration to check.
10283 /// \param OldT The portion of the type of the old declaration to check.
10284 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10285                                           QualType NewT, QualType OldT) {
10286   if (!NewD->getLexicalDeclContext()->isDependentContext())
10287     return true;
10288 
10289   // For dependently-typed local extern declarations and friends, we can't
10290   // perform a correct type check in general until instantiation:
10291   //
10292   //   int f();
10293   //   template<typename T> void g() { T f(); }
10294   //
10295   // (valid if g() is only instantiated with T = int).
10296   if (NewT->isDependentType() &&
10297       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10298     return false;
10299 
10300   // Similarly, if the previous declaration was a dependent local extern
10301   // declaration, we don't really know its type yet.
10302   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10303     return false;
10304 
10305   return true;
10306 }
10307 
10308 /// Checks if the new declaration declared in dependent context must be
10309 /// put in the same redeclaration chain as the specified declaration.
10310 ///
10311 /// \param D Declaration that is checked.
10312 /// \param PrevDecl Previous declaration found with proper lookup method for the
10313 ///                 same declaration name.
10314 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10315 ///          belongs to.
10316 ///
10317 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10318   if (!D->getLexicalDeclContext()->isDependentContext())
10319     return true;
10320 
10321   // Don't chain dependent friend function definitions until instantiation, to
10322   // permit cases like
10323   //
10324   //   void func();
10325   //   template<typename T> class C1 { friend void func() {} };
10326   //   template<typename T> class C2 { friend void func() {} };
10327   //
10328   // ... which is valid if only one of C1 and C2 is ever instantiated.
10329   //
10330   // FIXME: This need only apply to function definitions. For now, we proxy
10331   // this by checking for a file-scope function. We do not want this to apply
10332   // to friend declarations nominating member functions, because that gets in
10333   // the way of access checks.
10334   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10335     return false;
10336 
10337   auto *VD = dyn_cast<ValueDecl>(D);
10338   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10339   return !VD || !PrevVD ||
10340          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10341                                         PrevVD->getType());
10342 }
10343 
10344 /// Check the target attribute of the function for MultiVersion
10345 /// validity.
10346 ///
10347 /// Returns true if there was an error, false otherwise.
10348 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10349   const auto *TA = FD->getAttr<TargetAttr>();
10350   assert(TA && "MultiVersion Candidate requires a target attribute");
10351   ParsedTargetAttr ParseInfo = TA->parse();
10352   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10353   enum ErrType { Feature = 0, Architecture = 1 };
10354 
10355   if (!ParseInfo.Architecture.empty() &&
10356       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10357     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10358         << Architecture << ParseInfo.Architecture;
10359     return true;
10360   }
10361 
10362   for (const auto &Feat : ParseInfo.Features) {
10363     auto BareFeat = StringRef{Feat}.substr(1);
10364     if (Feat[0] == '-') {
10365       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10366           << Feature << ("no-" + BareFeat).str();
10367       return true;
10368     }
10369 
10370     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10371         !TargetInfo.isValidFeatureName(BareFeat)) {
10372       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10373           << Feature << BareFeat;
10374       return true;
10375     }
10376   }
10377   return false;
10378 }
10379 
10380 // Provide a white-list of attributes that are allowed to be combined with
10381 // multiversion functions.
10382 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10383                                            MultiVersionKind MVKind) {
10384   // Note: this list/diagnosis must match the list in
10385   // checkMultiversionAttributesAllSame.
10386   switch (Kind) {
10387   default:
10388     return false;
10389   case attr::Used:
10390     return MVKind == MultiVersionKind::Target;
10391   case attr::NonNull:
10392   case attr::NoThrow:
10393     return true;
10394   }
10395 }
10396 
10397 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10398                                                  const FunctionDecl *FD,
10399                                                  const FunctionDecl *CausedFD,
10400                                                  MultiVersionKind MVKind) {
10401   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10402     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10403         << static_cast<unsigned>(MVKind) << A;
10404     if (CausedFD)
10405       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10406     return true;
10407   };
10408 
10409   for (const Attr *A : FD->attrs()) {
10410     switch (A->getKind()) {
10411     case attr::CPUDispatch:
10412     case attr::CPUSpecific:
10413       if (MVKind != MultiVersionKind::CPUDispatch &&
10414           MVKind != MultiVersionKind::CPUSpecific)
10415         return Diagnose(S, A);
10416       break;
10417     case attr::Target:
10418       if (MVKind != MultiVersionKind::Target)
10419         return Diagnose(S, A);
10420       break;
10421     case attr::TargetClones:
10422       if (MVKind != MultiVersionKind::TargetClones)
10423         return Diagnose(S, A);
10424       break;
10425     default:
10426       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10427         return Diagnose(S, A);
10428       break;
10429     }
10430   }
10431   return false;
10432 }
10433 
10434 bool Sema::areMultiversionVariantFunctionsCompatible(
10435     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10436     const PartialDiagnostic &NoProtoDiagID,
10437     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10438     const PartialDiagnosticAt &NoSupportDiagIDAt,
10439     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10440     bool ConstexprSupported, bool CLinkageMayDiffer) {
10441   enum DoesntSupport {
10442     FuncTemplates = 0,
10443     VirtFuncs = 1,
10444     DeducedReturn = 2,
10445     Constructors = 3,
10446     Destructors = 4,
10447     DeletedFuncs = 5,
10448     DefaultedFuncs = 6,
10449     ConstexprFuncs = 7,
10450     ConstevalFuncs = 8,
10451     Lambda = 9,
10452   };
10453   enum Different {
10454     CallingConv = 0,
10455     ReturnType = 1,
10456     ConstexprSpec = 2,
10457     InlineSpec = 3,
10458     Linkage = 4,
10459     LanguageLinkage = 5,
10460   };
10461 
10462   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10463       !OldFD->getType()->getAs<FunctionProtoType>()) {
10464     Diag(OldFD->getLocation(), NoProtoDiagID);
10465     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10466     return true;
10467   }
10468 
10469   if (NoProtoDiagID.getDiagID() != 0 &&
10470       !NewFD->getType()->getAs<FunctionProtoType>())
10471     return Diag(NewFD->getLocation(), NoProtoDiagID);
10472 
10473   if (!TemplatesSupported &&
10474       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10475     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10476            << FuncTemplates;
10477 
10478   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10479     if (NewCXXFD->isVirtual())
10480       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10481              << VirtFuncs;
10482 
10483     if (isa<CXXConstructorDecl>(NewCXXFD))
10484       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10485              << Constructors;
10486 
10487     if (isa<CXXDestructorDecl>(NewCXXFD))
10488       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10489              << Destructors;
10490   }
10491 
10492   if (NewFD->isDeleted())
10493     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10494            << DeletedFuncs;
10495 
10496   if (NewFD->isDefaulted())
10497     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10498            << DefaultedFuncs;
10499 
10500   if (!ConstexprSupported && NewFD->isConstexpr())
10501     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10502            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10503 
10504   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10505   const auto *NewType = cast<FunctionType>(NewQType);
10506   QualType NewReturnType = NewType->getReturnType();
10507 
10508   if (NewReturnType->isUndeducedType())
10509     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10510            << DeducedReturn;
10511 
10512   // Ensure the return type is identical.
10513   if (OldFD) {
10514     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10515     const auto *OldType = cast<FunctionType>(OldQType);
10516     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10517     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10518 
10519     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10520       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10521 
10522     QualType OldReturnType = OldType->getReturnType();
10523 
10524     if (OldReturnType != NewReturnType)
10525       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10526 
10527     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10528       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10529 
10530     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10531       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10532 
10533     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10534       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10535 
10536     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10537       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10538 
10539     if (CheckEquivalentExceptionSpec(
10540             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10541             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10542       return true;
10543   }
10544   return false;
10545 }
10546 
10547 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10548                                              const FunctionDecl *NewFD,
10549                                              bool CausesMV,
10550                                              MultiVersionKind MVKind) {
10551   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10552     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10553     if (OldFD)
10554       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10555     return true;
10556   }
10557 
10558   bool IsCPUSpecificCPUDispatchMVKind =
10559       MVKind == MultiVersionKind::CPUDispatch ||
10560       MVKind == MultiVersionKind::CPUSpecific;
10561 
10562   if (CausesMV && OldFD &&
10563       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10564     return true;
10565 
10566   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10567     return true;
10568 
10569   // Only allow transition to MultiVersion if it hasn't been used.
10570   if (OldFD && CausesMV && OldFD->isUsed(false))
10571     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10572 
10573   return S.areMultiversionVariantFunctionsCompatible(
10574       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10575       PartialDiagnosticAt(NewFD->getLocation(),
10576                           S.PDiag(diag::note_multiversioning_caused_here)),
10577       PartialDiagnosticAt(NewFD->getLocation(),
10578                           S.PDiag(diag::err_multiversion_doesnt_support)
10579                               << static_cast<unsigned>(MVKind)),
10580       PartialDiagnosticAt(NewFD->getLocation(),
10581                           S.PDiag(diag::err_multiversion_diff)),
10582       /*TemplatesSupported=*/false,
10583       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10584       /*CLinkageMayDiffer=*/false);
10585 }
10586 
10587 /// Check the validity of a multiversion function declaration that is the
10588 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10589 ///
10590 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10591 ///
10592 /// Returns true if there was an error, false otherwise.
10593 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10594                                            MultiVersionKind MVKind,
10595                                            const TargetAttr *TA) {
10596   assert(MVKind != MultiVersionKind::None &&
10597          "Function lacks multiversion attribute");
10598 
10599   // Target only causes MV if it is default, otherwise this is a normal
10600   // function.
10601   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10602     return false;
10603 
10604   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10605     FD->setInvalidDecl();
10606     return true;
10607   }
10608 
10609   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10610     FD->setInvalidDecl();
10611     return true;
10612   }
10613 
10614   FD->setIsMultiVersion();
10615   return false;
10616 }
10617 
10618 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10619   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10620     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10621       return true;
10622   }
10623 
10624   return false;
10625 }
10626 
10627 static bool CheckTargetCausesMultiVersioning(
10628     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10629     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10630   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10631   ParsedTargetAttr NewParsed = NewTA->parse();
10632   // Sort order doesn't matter, it just needs to be consistent.
10633   llvm::sort(NewParsed.Features);
10634 
10635   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10636   // to change, this is a simple redeclaration.
10637   if (!NewTA->isDefaultVersion() &&
10638       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10639     return false;
10640 
10641   // Otherwise, this decl causes MultiVersioning.
10642   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10643                                        MultiVersionKind::Target)) {
10644     NewFD->setInvalidDecl();
10645     return true;
10646   }
10647 
10648   if (CheckMultiVersionValue(S, NewFD)) {
10649     NewFD->setInvalidDecl();
10650     return true;
10651   }
10652 
10653   // If this is 'default', permit the forward declaration.
10654   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10655     Redeclaration = true;
10656     OldDecl = OldFD;
10657     OldFD->setIsMultiVersion();
10658     NewFD->setIsMultiVersion();
10659     return false;
10660   }
10661 
10662   if (CheckMultiVersionValue(S, OldFD)) {
10663     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10664     NewFD->setInvalidDecl();
10665     return true;
10666   }
10667 
10668   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10669 
10670   if (OldParsed == NewParsed) {
10671     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10672     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10673     NewFD->setInvalidDecl();
10674     return true;
10675   }
10676 
10677   for (const auto *FD : OldFD->redecls()) {
10678     const auto *CurTA = FD->getAttr<TargetAttr>();
10679     // We allow forward declarations before ANY multiversioning attributes, but
10680     // nothing after the fact.
10681     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10682         (!CurTA || CurTA->isInherited())) {
10683       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10684           << 0;
10685       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10686       NewFD->setInvalidDecl();
10687       return true;
10688     }
10689   }
10690 
10691   OldFD->setIsMultiVersion();
10692   NewFD->setIsMultiVersion();
10693   Redeclaration = false;
10694   OldDecl = nullptr;
10695   Previous.clear();
10696   return false;
10697 }
10698 
10699 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10700                                         MultiVersionKind New) {
10701   if (Old == New || Old == MultiVersionKind::None ||
10702       New == MultiVersionKind::None)
10703     return true;
10704 
10705   return (Old == MultiVersionKind::CPUDispatch &&
10706           New == MultiVersionKind::CPUSpecific) ||
10707          (Old == MultiVersionKind::CPUSpecific &&
10708           New == MultiVersionKind::CPUDispatch);
10709 }
10710 
10711 /// Check the validity of a new function declaration being added to an existing
10712 /// multiversioned declaration collection.
10713 static bool CheckMultiVersionAdditionalDecl(
10714     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10715     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10716     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10717     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10718     LookupResult &Previous) {
10719 
10720   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10721   // Disallow mixing of multiversioning types.
10722   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10723     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10724     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10725     NewFD->setInvalidDecl();
10726     return true;
10727   }
10728 
10729   ParsedTargetAttr NewParsed;
10730   if (NewTA) {
10731     NewParsed = NewTA->parse();
10732     llvm::sort(NewParsed.Features);
10733   }
10734 
10735   bool UseMemberUsingDeclRules =
10736       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10737 
10738   bool MayNeedOverloadableChecks =
10739       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10740 
10741   // Next, check ALL non-overloads to see if this is a redeclaration of a
10742   // previous member of the MultiVersion set.
10743   for (NamedDecl *ND : Previous) {
10744     FunctionDecl *CurFD = ND->getAsFunction();
10745     if (!CurFD)
10746       continue;
10747     if (MayNeedOverloadableChecks &&
10748         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10749       continue;
10750 
10751     switch (NewMVKind) {
10752     case MultiVersionKind::None:
10753       assert(OldMVKind == MultiVersionKind::TargetClones &&
10754              "Only target_clones can be omitted in subsequent declarations");
10755       break;
10756     case MultiVersionKind::Target: {
10757       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10758       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10759         NewFD->setIsMultiVersion();
10760         Redeclaration = true;
10761         OldDecl = ND;
10762         return false;
10763       }
10764 
10765       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10766       if (CurParsed == NewParsed) {
10767         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10768         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10769         NewFD->setInvalidDecl();
10770         return true;
10771       }
10772       break;
10773     }
10774     case MultiVersionKind::TargetClones: {
10775       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10776       Redeclaration = true;
10777       OldDecl = CurFD;
10778       NewFD->setIsMultiVersion();
10779 
10780       if (CurClones && NewClones &&
10781           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10782            !std::equal(CurClones->featuresStrs_begin(),
10783                        CurClones->featuresStrs_end(),
10784                        NewClones->featuresStrs_begin()))) {
10785         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10786         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10787         NewFD->setInvalidDecl();
10788         return true;
10789       }
10790 
10791       return false;
10792     }
10793     case MultiVersionKind::CPUSpecific:
10794     case MultiVersionKind::CPUDispatch: {
10795       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10796       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10797       // Handle CPUDispatch/CPUSpecific versions.
10798       // Only 1 CPUDispatch function is allowed, this will make it go through
10799       // the redeclaration errors.
10800       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10801           CurFD->hasAttr<CPUDispatchAttr>()) {
10802         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10803             std::equal(
10804                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10805                 NewCPUDisp->cpus_begin(),
10806                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10807                   return Cur->getName() == New->getName();
10808                 })) {
10809           NewFD->setIsMultiVersion();
10810           Redeclaration = true;
10811           OldDecl = ND;
10812           return false;
10813         }
10814 
10815         // If the declarations don't match, this is an error condition.
10816         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10817         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10818         NewFD->setInvalidDecl();
10819         return true;
10820       }
10821       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10822         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10823             std::equal(
10824                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10825                 NewCPUSpec->cpus_begin(),
10826                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10827                   return Cur->getName() == New->getName();
10828                 })) {
10829           NewFD->setIsMultiVersion();
10830           Redeclaration = true;
10831           OldDecl = ND;
10832           return false;
10833         }
10834 
10835         // Only 1 version of CPUSpecific is allowed for each CPU.
10836         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10837           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10838             if (CurII == NewII) {
10839               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10840                   << NewII;
10841               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10842               NewFD->setInvalidDecl();
10843               return true;
10844             }
10845           }
10846         }
10847       }
10848       break;
10849     }
10850     }
10851   }
10852 
10853   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10854   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10855   // handled in the attribute adding step.
10856   if (NewMVKind == MultiVersionKind::Target &&
10857       CheckMultiVersionValue(S, NewFD)) {
10858     NewFD->setInvalidDecl();
10859     return true;
10860   }
10861 
10862   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10863                                        !OldFD->isMultiVersion(), NewMVKind)) {
10864     NewFD->setInvalidDecl();
10865     return true;
10866   }
10867 
10868   // Permit forward declarations in the case where these two are compatible.
10869   if (!OldFD->isMultiVersion()) {
10870     OldFD->setIsMultiVersion();
10871     NewFD->setIsMultiVersion();
10872     Redeclaration = true;
10873     OldDecl = OldFD;
10874     return false;
10875   }
10876 
10877   NewFD->setIsMultiVersion();
10878   Redeclaration = false;
10879   OldDecl = nullptr;
10880   Previous.clear();
10881   return false;
10882 }
10883 
10884 /// Check the validity of a mulitversion function declaration.
10885 /// Also sets the multiversion'ness' of the function itself.
10886 ///
10887 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10888 ///
10889 /// Returns true if there was an error, false otherwise.
10890 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10891                                       bool &Redeclaration, NamedDecl *&OldDecl,
10892                                       LookupResult &Previous) {
10893   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10894   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10895   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10896   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10897   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
10898 
10899   // Main isn't allowed to become a multiversion function, however it IS
10900   // permitted to have 'main' be marked with the 'target' optimization hint.
10901   if (NewFD->isMain()) {
10902     if (MVKind != MultiVersionKind::None &&
10903         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10904       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10905       NewFD->setInvalidDecl();
10906       return true;
10907     }
10908     return false;
10909   }
10910 
10911   if (!OldDecl || !OldDecl->getAsFunction() ||
10912       OldDecl->getDeclContext()->getRedeclContext() !=
10913           NewFD->getDeclContext()->getRedeclContext()) {
10914     // If there's no previous declaration, AND this isn't attempting to cause
10915     // multiversioning, this isn't an error condition.
10916     if (MVKind == MultiVersionKind::None)
10917       return false;
10918     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
10919   }
10920 
10921   FunctionDecl *OldFD = OldDecl->getAsFunction();
10922 
10923   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
10924     return false;
10925 
10926   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10927   // for target_clones.
10928   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
10929       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10930     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10931         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10932     NewFD->setInvalidDecl();
10933     return true;
10934   }
10935 
10936   if (!OldFD->isMultiVersion()) {
10937     switch (MVKind) {
10938     case MultiVersionKind::Target:
10939       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10940                                               Redeclaration, OldDecl, Previous);
10941     case MultiVersionKind::TargetClones:
10942       if (OldFD->isUsed(false)) {
10943         NewFD->setInvalidDecl();
10944         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10945       }
10946       OldFD->setIsMultiVersion();
10947       break;
10948     case MultiVersionKind::CPUDispatch:
10949     case MultiVersionKind::CPUSpecific:
10950     case MultiVersionKind::None:
10951       break;
10952     }
10953   }
10954 
10955   // At this point, we have a multiversion function decl (in OldFD) AND an
10956   // appropriate attribute in the current function decl.  Resolve that these are
10957   // still compatible with previous declarations.
10958   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
10959                                          NewCPUDisp, NewCPUSpec, NewClones,
10960                                          Redeclaration, OldDecl, Previous);
10961 }
10962 
10963 /// Perform semantic checking of a new function declaration.
10964 ///
10965 /// Performs semantic analysis of the new function declaration
10966 /// NewFD. This routine performs all semantic checking that does not
10967 /// require the actual declarator involved in the declaration, and is
10968 /// used both for the declaration of functions as they are parsed
10969 /// (called via ActOnDeclarator) and for the declaration of functions
10970 /// that have been instantiated via C++ template instantiation (called
10971 /// via InstantiateDecl).
10972 ///
10973 /// \param IsMemberSpecialization whether this new function declaration is
10974 /// a member specialization (that replaces any definition provided by the
10975 /// previous declaration).
10976 ///
10977 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10978 ///
10979 /// \returns true if the function declaration is a redeclaration.
10980 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10981                                     LookupResult &Previous,
10982                                     bool IsMemberSpecialization) {
10983   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10984          "Variably modified return types are not handled here");
10985 
10986   // Determine whether the type of this function should be merged with
10987   // a previous visible declaration. This never happens for functions in C++,
10988   // and always happens in C if the previous declaration was visible.
10989   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10990                                !Previous.isShadowed();
10991 
10992   bool Redeclaration = false;
10993   NamedDecl *OldDecl = nullptr;
10994   bool MayNeedOverloadableChecks = false;
10995 
10996   // Merge or overload the declaration with an existing declaration of
10997   // the same name, if appropriate.
10998   if (!Previous.empty()) {
10999     // Determine whether NewFD is an overload of PrevDecl or
11000     // a declaration that requires merging. If it's an overload,
11001     // there's no more work to do here; we'll just add the new
11002     // function to the scope.
11003     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11004       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11005       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11006         Redeclaration = true;
11007         OldDecl = Candidate;
11008       }
11009     } else {
11010       MayNeedOverloadableChecks = true;
11011       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11012                             /*NewIsUsingDecl*/ false)) {
11013       case Ovl_Match:
11014         Redeclaration = true;
11015         break;
11016 
11017       case Ovl_NonFunction:
11018         Redeclaration = true;
11019         break;
11020 
11021       case Ovl_Overload:
11022         Redeclaration = false;
11023         break;
11024       }
11025     }
11026   }
11027 
11028   // Check for a previous extern "C" declaration with this name.
11029   if (!Redeclaration &&
11030       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11031     if (!Previous.empty()) {
11032       // This is an extern "C" declaration with the same name as a previous
11033       // declaration, and thus redeclares that entity...
11034       Redeclaration = true;
11035       OldDecl = Previous.getFoundDecl();
11036       MergeTypeWithPrevious = false;
11037 
11038       // ... except in the presence of __attribute__((overloadable)).
11039       if (OldDecl->hasAttr<OverloadableAttr>() ||
11040           NewFD->hasAttr<OverloadableAttr>()) {
11041         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11042           MayNeedOverloadableChecks = true;
11043           Redeclaration = false;
11044           OldDecl = nullptr;
11045         }
11046       }
11047     }
11048   }
11049 
11050   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11051     return Redeclaration;
11052 
11053   // PPC MMA non-pointer types are not allowed as function return types.
11054   if (Context.getTargetInfo().getTriple().isPPC64() &&
11055       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11056     NewFD->setInvalidDecl();
11057   }
11058 
11059   // C++11 [dcl.constexpr]p8:
11060   //   A constexpr specifier for a non-static member function that is not
11061   //   a constructor declares that member function to be const.
11062   //
11063   // This needs to be delayed until we know whether this is an out-of-line
11064   // definition of a static member function.
11065   //
11066   // This rule is not present in C++1y, so we produce a backwards
11067   // compatibility warning whenever it happens in C++11.
11068   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11069   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11070       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11071       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11072     CXXMethodDecl *OldMD = nullptr;
11073     if (OldDecl)
11074       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11075     if (!OldMD || !OldMD->isStatic()) {
11076       const FunctionProtoType *FPT =
11077         MD->getType()->castAs<FunctionProtoType>();
11078       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11079       EPI.TypeQuals.addConst();
11080       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11081                                           FPT->getParamTypes(), EPI));
11082 
11083       // Warn that we did this, if we're not performing template instantiation.
11084       // In that case, we'll have warned already when the template was defined.
11085       if (!inTemplateInstantiation()) {
11086         SourceLocation AddConstLoc;
11087         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11088                 .IgnoreParens().getAs<FunctionTypeLoc>())
11089           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11090 
11091         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11092           << FixItHint::CreateInsertion(AddConstLoc, " const");
11093       }
11094     }
11095   }
11096 
11097   if (Redeclaration) {
11098     // NewFD and OldDecl represent declarations that need to be
11099     // merged.
11100     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11101       NewFD->setInvalidDecl();
11102       return Redeclaration;
11103     }
11104 
11105     Previous.clear();
11106     Previous.addDecl(OldDecl);
11107 
11108     if (FunctionTemplateDecl *OldTemplateDecl =
11109             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11110       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11111       FunctionTemplateDecl *NewTemplateDecl
11112         = NewFD->getDescribedFunctionTemplate();
11113       assert(NewTemplateDecl && "Template/non-template mismatch");
11114 
11115       // The call to MergeFunctionDecl above may have created some state in
11116       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11117       // can add it as a redeclaration.
11118       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11119 
11120       NewFD->setPreviousDeclaration(OldFD);
11121       if (NewFD->isCXXClassMember()) {
11122         NewFD->setAccess(OldTemplateDecl->getAccess());
11123         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11124       }
11125 
11126       // If this is an explicit specialization of a member that is a function
11127       // template, mark it as a member specialization.
11128       if (IsMemberSpecialization &&
11129           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11130         NewTemplateDecl->setMemberSpecialization();
11131         assert(OldTemplateDecl->isMemberSpecialization());
11132         // Explicit specializations of a member template do not inherit deleted
11133         // status from the parent member template that they are specializing.
11134         if (OldFD->isDeleted()) {
11135           // FIXME: This assert will not hold in the presence of modules.
11136           assert(OldFD->getCanonicalDecl() == OldFD);
11137           // FIXME: We need an update record for this AST mutation.
11138           OldFD->setDeletedAsWritten(false);
11139         }
11140       }
11141 
11142     } else {
11143       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11144         auto *OldFD = cast<FunctionDecl>(OldDecl);
11145         // This needs to happen first so that 'inline' propagates.
11146         NewFD->setPreviousDeclaration(OldFD);
11147         if (NewFD->isCXXClassMember())
11148           NewFD->setAccess(OldFD->getAccess());
11149       }
11150     }
11151   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11152              !NewFD->getAttr<OverloadableAttr>()) {
11153     assert((Previous.empty() ||
11154             llvm::any_of(Previous,
11155                          [](const NamedDecl *ND) {
11156                            return ND->hasAttr<OverloadableAttr>();
11157                          })) &&
11158            "Non-redecls shouldn't happen without overloadable present");
11159 
11160     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11161       const auto *FD = dyn_cast<FunctionDecl>(ND);
11162       return FD && !FD->hasAttr<OverloadableAttr>();
11163     });
11164 
11165     if (OtherUnmarkedIter != Previous.end()) {
11166       Diag(NewFD->getLocation(),
11167            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11168       Diag((*OtherUnmarkedIter)->getLocation(),
11169            diag::note_attribute_overloadable_prev_overload)
11170           << false;
11171 
11172       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11173     }
11174   }
11175 
11176   if (LangOpts.OpenMP)
11177     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11178 
11179   // Semantic checking for this function declaration (in isolation).
11180 
11181   if (getLangOpts().CPlusPlus) {
11182     // C++-specific checks.
11183     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11184       CheckConstructor(Constructor);
11185     } else if (CXXDestructorDecl *Destructor =
11186                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11187       CXXRecordDecl *Record = Destructor->getParent();
11188       QualType ClassType = Context.getTypeDeclType(Record);
11189 
11190       // FIXME: Shouldn't we be able to perform this check even when the class
11191       // type is dependent? Both gcc and edg can handle that.
11192       if (!ClassType->isDependentType()) {
11193         DeclarationName Name
11194           = Context.DeclarationNames.getCXXDestructorName(
11195                                         Context.getCanonicalType(ClassType));
11196         if (NewFD->getDeclName() != Name) {
11197           Diag(NewFD->getLocation(), diag::err_destructor_name);
11198           NewFD->setInvalidDecl();
11199           return Redeclaration;
11200         }
11201       }
11202     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11203       if (auto *TD = Guide->getDescribedFunctionTemplate())
11204         CheckDeductionGuideTemplate(TD);
11205 
11206       // A deduction guide is not on the list of entities that can be
11207       // explicitly specialized.
11208       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11209         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11210             << /*explicit specialization*/ 1;
11211     }
11212 
11213     // Find any virtual functions that this function overrides.
11214     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11215       if (!Method->isFunctionTemplateSpecialization() &&
11216           !Method->getDescribedFunctionTemplate() &&
11217           Method->isCanonicalDecl()) {
11218         AddOverriddenMethods(Method->getParent(), Method);
11219       }
11220       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11221         // C++2a [class.virtual]p6
11222         // A virtual method shall not have a requires-clause.
11223         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11224              diag::err_constrained_virtual_method);
11225 
11226       if (Method->isStatic())
11227         checkThisInStaticMemberFunctionType(Method);
11228     }
11229 
11230     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11231       ActOnConversionDeclarator(Conversion);
11232 
11233     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11234     if (NewFD->isOverloadedOperator() &&
11235         CheckOverloadedOperatorDeclaration(NewFD)) {
11236       NewFD->setInvalidDecl();
11237       return Redeclaration;
11238     }
11239 
11240     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11241     if (NewFD->getLiteralIdentifier() &&
11242         CheckLiteralOperatorDeclaration(NewFD)) {
11243       NewFD->setInvalidDecl();
11244       return Redeclaration;
11245     }
11246 
11247     // In C++, check default arguments now that we have merged decls. Unless
11248     // the lexical context is the class, because in this case this is done
11249     // during delayed parsing anyway.
11250     if (!CurContext->isRecord())
11251       CheckCXXDefaultArguments(NewFD);
11252 
11253     // If this function is declared as being extern "C", then check to see if
11254     // the function returns a UDT (class, struct, or union type) that is not C
11255     // compatible, and if it does, warn the user.
11256     // But, issue any diagnostic on the first declaration only.
11257     if (Previous.empty() && NewFD->isExternC()) {
11258       QualType R = NewFD->getReturnType();
11259       if (R->isIncompleteType() && !R->isVoidType())
11260         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11261             << NewFD << R;
11262       else if (!R.isPODType(Context) && !R->isVoidType() &&
11263                !R->isObjCObjectPointerType())
11264         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11265     }
11266 
11267     // C++1z [dcl.fct]p6:
11268     //   [...] whether the function has a non-throwing exception-specification
11269     //   [is] part of the function type
11270     //
11271     // This results in an ABI break between C++14 and C++17 for functions whose
11272     // declared type includes an exception-specification in a parameter or
11273     // return type. (Exception specifications on the function itself are OK in
11274     // most cases, and exception specifications are not permitted in most other
11275     // contexts where they could make it into a mangling.)
11276     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11277       auto HasNoexcept = [&](QualType T) -> bool {
11278         // Strip off declarator chunks that could be between us and a function
11279         // type. We don't need to look far, exception specifications are very
11280         // restricted prior to C++17.
11281         if (auto *RT = T->getAs<ReferenceType>())
11282           T = RT->getPointeeType();
11283         else if (T->isAnyPointerType())
11284           T = T->getPointeeType();
11285         else if (auto *MPT = T->getAs<MemberPointerType>())
11286           T = MPT->getPointeeType();
11287         if (auto *FPT = T->getAs<FunctionProtoType>())
11288           if (FPT->isNothrow())
11289             return true;
11290         return false;
11291       };
11292 
11293       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11294       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11295       for (QualType T : FPT->param_types())
11296         AnyNoexcept |= HasNoexcept(T);
11297       if (AnyNoexcept)
11298         Diag(NewFD->getLocation(),
11299              diag::warn_cxx17_compat_exception_spec_in_signature)
11300             << NewFD;
11301     }
11302 
11303     if (!Redeclaration && LangOpts.CUDA)
11304       checkCUDATargetOverload(NewFD, Previous);
11305   }
11306   return Redeclaration;
11307 }
11308 
11309 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11310   // C++11 [basic.start.main]p3:
11311   //   A program that [...] declares main to be inline, static or
11312   //   constexpr is ill-formed.
11313   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11314   //   appear in a declaration of main.
11315   // static main is not an error under C99, but we should warn about it.
11316   // We accept _Noreturn main as an extension.
11317   if (FD->getStorageClass() == SC_Static)
11318     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11319          ? diag::err_static_main : diag::warn_static_main)
11320       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11321   if (FD->isInlineSpecified())
11322     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11323       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11324   if (DS.isNoreturnSpecified()) {
11325     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11326     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11327     Diag(NoreturnLoc, diag::ext_noreturn_main);
11328     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11329       << FixItHint::CreateRemoval(NoreturnRange);
11330   }
11331   if (FD->isConstexpr()) {
11332     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11333         << FD->isConsteval()
11334         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11335     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11336   }
11337 
11338   if (getLangOpts().OpenCL) {
11339     Diag(FD->getLocation(), diag::err_opencl_no_main)
11340         << FD->hasAttr<OpenCLKernelAttr>();
11341     FD->setInvalidDecl();
11342     return;
11343   }
11344 
11345   // Functions named main in hlsl are default entries, but don't have specific
11346   // signatures they are required to conform to.
11347   if (getLangOpts().HLSL)
11348     return;
11349 
11350   QualType T = FD->getType();
11351   assert(T->isFunctionType() && "function decl is not of function type");
11352   const FunctionType* FT = T->castAs<FunctionType>();
11353 
11354   // Set default calling convention for main()
11355   if (FT->getCallConv() != CC_C) {
11356     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11357     FD->setType(QualType(FT, 0));
11358     T = Context.getCanonicalType(FD->getType());
11359   }
11360 
11361   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11362     // In C with GNU extensions we allow main() to have non-integer return
11363     // type, but we should warn about the extension, and we disable the
11364     // implicit-return-zero rule.
11365 
11366     // GCC in C mode accepts qualified 'int'.
11367     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11368       FD->setHasImplicitReturnZero(true);
11369     else {
11370       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11371       SourceRange RTRange = FD->getReturnTypeSourceRange();
11372       if (RTRange.isValid())
11373         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11374             << FixItHint::CreateReplacement(RTRange, "int");
11375     }
11376   } else {
11377     // In C and C++, main magically returns 0 if you fall off the end;
11378     // set the flag which tells us that.
11379     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11380 
11381     // All the standards say that main() should return 'int'.
11382     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11383       FD->setHasImplicitReturnZero(true);
11384     else {
11385       // Otherwise, this is just a flat-out error.
11386       SourceRange RTRange = FD->getReturnTypeSourceRange();
11387       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11388           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11389                                 : FixItHint());
11390       FD->setInvalidDecl(true);
11391     }
11392   }
11393 
11394   // Treat protoless main() as nullary.
11395   if (isa<FunctionNoProtoType>(FT)) return;
11396 
11397   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11398   unsigned nparams = FTP->getNumParams();
11399   assert(FD->getNumParams() == nparams);
11400 
11401   bool HasExtraParameters = (nparams > 3);
11402 
11403   if (FTP->isVariadic()) {
11404     Diag(FD->getLocation(), diag::ext_variadic_main);
11405     // FIXME: if we had information about the location of the ellipsis, we
11406     // could add a FixIt hint to remove it as a parameter.
11407   }
11408 
11409   // Darwin passes an undocumented fourth argument of type char**.  If
11410   // other platforms start sprouting these, the logic below will start
11411   // getting shifty.
11412   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11413     HasExtraParameters = false;
11414 
11415   if (HasExtraParameters) {
11416     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11417     FD->setInvalidDecl(true);
11418     nparams = 3;
11419   }
11420 
11421   // FIXME: a lot of the following diagnostics would be improved
11422   // if we had some location information about types.
11423 
11424   QualType CharPP =
11425     Context.getPointerType(Context.getPointerType(Context.CharTy));
11426   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11427 
11428   for (unsigned i = 0; i < nparams; ++i) {
11429     QualType AT = FTP->getParamType(i);
11430 
11431     bool mismatch = true;
11432 
11433     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11434       mismatch = false;
11435     else if (Expected[i] == CharPP) {
11436       // As an extension, the following forms are okay:
11437       //   char const **
11438       //   char const * const *
11439       //   char * const *
11440 
11441       QualifierCollector qs;
11442       const PointerType* PT;
11443       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11444           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11445           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11446                               Context.CharTy)) {
11447         qs.removeConst();
11448         mismatch = !qs.empty();
11449       }
11450     }
11451 
11452     if (mismatch) {
11453       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11454       // TODO: suggest replacing given type with expected type
11455       FD->setInvalidDecl(true);
11456     }
11457   }
11458 
11459   if (nparams == 1 && !FD->isInvalidDecl()) {
11460     Diag(FD->getLocation(), diag::warn_main_one_arg);
11461   }
11462 
11463   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11464     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11465     FD->setInvalidDecl();
11466   }
11467 }
11468 
11469 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11470 
11471   // Default calling convention for main and wmain is __cdecl
11472   if (FD->getName() == "main" || FD->getName() == "wmain")
11473     return false;
11474 
11475   // Default calling convention for MinGW is __cdecl
11476   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11477   if (T.isWindowsGNUEnvironment())
11478     return false;
11479 
11480   // Default calling convention for WinMain, wWinMain and DllMain
11481   // is __stdcall on 32 bit Windows
11482   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11483     return true;
11484 
11485   return false;
11486 }
11487 
11488 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11489   QualType T = FD->getType();
11490   assert(T->isFunctionType() && "function decl is not of function type");
11491   const FunctionType *FT = T->castAs<FunctionType>();
11492 
11493   // Set an implicit return of 'zero' if the function can return some integral,
11494   // enumeration, pointer or nullptr type.
11495   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11496       FT->getReturnType()->isAnyPointerType() ||
11497       FT->getReturnType()->isNullPtrType())
11498     // DllMain is exempt because a return value of zero means it failed.
11499     if (FD->getName() != "DllMain")
11500       FD->setHasImplicitReturnZero(true);
11501 
11502   // Explicity specified calling conventions are applied to MSVC entry points
11503   if (!hasExplicitCallingConv(T)) {
11504     if (isDefaultStdCall(FD, *this)) {
11505       if (FT->getCallConv() != CC_X86StdCall) {
11506         FT = Context.adjustFunctionType(
11507             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11508         FD->setType(QualType(FT, 0));
11509       }
11510     } else if (FT->getCallConv() != CC_C) {
11511       FT = Context.adjustFunctionType(FT,
11512                                       FT->getExtInfo().withCallingConv(CC_C));
11513       FD->setType(QualType(FT, 0));
11514     }
11515   }
11516 
11517   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11518     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11519     FD->setInvalidDecl();
11520   }
11521 }
11522 
11523 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11524   // FIXME: Need strict checking.  In C89, we need to check for
11525   // any assignment, increment, decrement, function-calls, or
11526   // commas outside of a sizeof.  In C99, it's the same list,
11527   // except that the aforementioned are allowed in unevaluated
11528   // expressions.  Everything else falls under the
11529   // "may accept other forms of constant expressions" exception.
11530   //
11531   // Regular C++ code will not end up here (exceptions: language extensions,
11532   // OpenCL C++ etc), so the constant expression rules there don't matter.
11533   if (Init->isValueDependent()) {
11534     assert(Init->containsErrors() &&
11535            "Dependent code should only occur in error-recovery path.");
11536     return true;
11537   }
11538   const Expr *Culprit;
11539   if (Init->isConstantInitializer(Context, false, &Culprit))
11540     return false;
11541   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11542     << Culprit->getSourceRange();
11543   return true;
11544 }
11545 
11546 namespace {
11547   // Visits an initialization expression to see if OrigDecl is evaluated in
11548   // its own initialization and throws a warning if it does.
11549   class SelfReferenceChecker
11550       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11551     Sema &S;
11552     Decl *OrigDecl;
11553     bool isRecordType;
11554     bool isPODType;
11555     bool isReferenceType;
11556 
11557     bool isInitList;
11558     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11559 
11560   public:
11561     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11562 
11563     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11564                                                     S(S), OrigDecl(OrigDecl) {
11565       isPODType = false;
11566       isRecordType = false;
11567       isReferenceType = false;
11568       isInitList = false;
11569       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11570         isPODType = VD->getType().isPODType(S.Context);
11571         isRecordType = VD->getType()->isRecordType();
11572         isReferenceType = VD->getType()->isReferenceType();
11573       }
11574     }
11575 
11576     // For most expressions, just call the visitor.  For initializer lists,
11577     // track the index of the field being initialized since fields are
11578     // initialized in order allowing use of previously initialized fields.
11579     void CheckExpr(Expr *E) {
11580       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11581       if (!InitList) {
11582         Visit(E);
11583         return;
11584       }
11585 
11586       // Track and increment the index here.
11587       isInitList = true;
11588       InitFieldIndex.push_back(0);
11589       for (auto Child : InitList->children()) {
11590         CheckExpr(cast<Expr>(Child));
11591         ++InitFieldIndex.back();
11592       }
11593       InitFieldIndex.pop_back();
11594     }
11595 
11596     // Returns true if MemberExpr is checked and no further checking is needed.
11597     // Returns false if additional checking is required.
11598     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11599       llvm::SmallVector<FieldDecl*, 4> Fields;
11600       Expr *Base = E;
11601       bool ReferenceField = false;
11602 
11603       // Get the field members used.
11604       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11605         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11606         if (!FD)
11607           return false;
11608         Fields.push_back(FD);
11609         if (FD->getType()->isReferenceType())
11610           ReferenceField = true;
11611         Base = ME->getBase()->IgnoreParenImpCasts();
11612       }
11613 
11614       // Keep checking only if the base Decl is the same.
11615       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11616       if (!DRE || DRE->getDecl() != OrigDecl)
11617         return false;
11618 
11619       // A reference field can be bound to an unininitialized field.
11620       if (CheckReference && !ReferenceField)
11621         return true;
11622 
11623       // Convert FieldDecls to their index number.
11624       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11625       for (const FieldDecl *I : llvm::reverse(Fields))
11626         UsedFieldIndex.push_back(I->getFieldIndex());
11627 
11628       // See if a warning is needed by checking the first difference in index
11629       // numbers.  If field being used has index less than the field being
11630       // initialized, then the use is safe.
11631       for (auto UsedIter = UsedFieldIndex.begin(),
11632                 UsedEnd = UsedFieldIndex.end(),
11633                 OrigIter = InitFieldIndex.begin(),
11634                 OrigEnd = InitFieldIndex.end();
11635            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11636         if (*UsedIter < *OrigIter)
11637           return true;
11638         if (*UsedIter > *OrigIter)
11639           break;
11640       }
11641 
11642       // TODO: Add a different warning which will print the field names.
11643       HandleDeclRefExpr(DRE);
11644       return true;
11645     }
11646 
11647     // For most expressions, the cast is directly above the DeclRefExpr.
11648     // For conditional operators, the cast can be outside the conditional
11649     // operator if both expressions are DeclRefExpr's.
11650     void HandleValue(Expr *E) {
11651       E = E->IgnoreParens();
11652       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11653         HandleDeclRefExpr(DRE);
11654         return;
11655       }
11656 
11657       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11658         Visit(CO->getCond());
11659         HandleValue(CO->getTrueExpr());
11660         HandleValue(CO->getFalseExpr());
11661         return;
11662       }
11663 
11664       if (BinaryConditionalOperator *BCO =
11665               dyn_cast<BinaryConditionalOperator>(E)) {
11666         Visit(BCO->getCond());
11667         HandleValue(BCO->getFalseExpr());
11668         return;
11669       }
11670 
11671       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11672         HandleValue(OVE->getSourceExpr());
11673         return;
11674       }
11675 
11676       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11677         if (BO->getOpcode() == BO_Comma) {
11678           Visit(BO->getLHS());
11679           HandleValue(BO->getRHS());
11680           return;
11681         }
11682       }
11683 
11684       if (isa<MemberExpr>(E)) {
11685         if (isInitList) {
11686           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11687                                       false /*CheckReference*/))
11688             return;
11689         }
11690 
11691         Expr *Base = E->IgnoreParenImpCasts();
11692         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11693           // Check for static member variables and don't warn on them.
11694           if (!isa<FieldDecl>(ME->getMemberDecl()))
11695             return;
11696           Base = ME->getBase()->IgnoreParenImpCasts();
11697         }
11698         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11699           HandleDeclRefExpr(DRE);
11700         return;
11701       }
11702 
11703       Visit(E);
11704     }
11705 
11706     // Reference types not handled in HandleValue are handled here since all
11707     // uses of references are bad, not just r-value uses.
11708     void VisitDeclRefExpr(DeclRefExpr *E) {
11709       if (isReferenceType)
11710         HandleDeclRefExpr(E);
11711     }
11712 
11713     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11714       if (E->getCastKind() == CK_LValueToRValue) {
11715         HandleValue(E->getSubExpr());
11716         return;
11717       }
11718 
11719       Inherited::VisitImplicitCastExpr(E);
11720     }
11721 
11722     void VisitMemberExpr(MemberExpr *E) {
11723       if (isInitList) {
11724         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11725           return;
11726       }
11727 
11728       // Don't warn on arrays since they can be treated as pointers.
11729       if (E->getType()->canDecayToPointerType()) return;
11730 
11731       // Warn when a non-static method call is followed by non-static member
11732       // field accesses, which is followed by a DeclRefExpr.
11733       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11734       bool Warn = (MD && !MD->isStatic());
11735       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11736       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11737         if (!isa<FieldDecl>(ME->getMemberDecl()))
11738           Warn = false;
11739         Base = ME->getBase()->IgnoreParenImpCasts();
11740       }
11741 
11742       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11743         if (Warn)
11744           HandleDeclRefExpr(DRE);
11745         return;
11746       }
11747 
11748       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11749       // Visit that expression.
11750       Visit(Base);
11751     }
11752 
11753     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11754       Expr *Callee = E->getCallee();
11755 
11756       if (isa<UnresolvedLookupExpr>(Callee))
11757         return Inherited::VisitCXXOperatorCallExpr(E);
11758 
11759       Visit(Callee);
11760       for (auto Arg: E->arguments())
11761         HandleValue(Arg->IgnoreParenImpCasts());
11762     }
11763 
11764     void VisitUnaryOperator(UnaryOperator *E) {
11765       // For POD record types, addresses of its own members are well-defined.
11766       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11767           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11768         if (!isPODType)
11769           HandleValue(E->getSubExpr());
11770         return;
11771       }
11772 
11773       if (E->isIncrementDecrementOp()) {
11774         HandleValue(E->getSubExpr());
11775         return;
11776       }
11777 
11778       Inherited::VisitUnaryOperator(E);
11779     }
11780 
11781     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11782 
11783     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11784       if (E->getConstructor()->isCopyConstructor()) {
11785         Expr *ArgExpr = E->getArg(0);
11786         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11787           if (ILE->getNumInits() == 1)
11788             ArgExpr = ILE->getInit(0);
11789         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11790           if (ICE->getCastKind() == CK_NoOp)
11791             ArgExpr = ICE->getSubExpr();
11792         HandleValue(ArgExpr);
11793         return;
11794       }
11795       Inherited::VisitCXXConstructExpr(E);
11796     }
11797 
11798     void VisitCallExpr(CallExpr *E) {
11799       // Treat std::move as a use.
11800       if (E->isCallToStdMove()) {
11801         HandleValue(E->getArg(0));
11802         return;
11803       }
11804 
11805       Inherited::VisitCallExpr(E);
11806     }
11807 
11808     void VisitBinaryOperator(BinaryOperator *E) {
11809       if (E->isCompoundAssignmentOp()) {
11810         HandleValue(E->getLHS());
11811         Visit(E->getRHS());
11812         return;
11813       }
11814 
11815       Inherited::VisitBinaryOperator(E);
11816     }
11817 
11818     // A custom visitor for BinaryConditionalOperator is needed because the
11819     // regular visitor would check the condition and true expression separately
11820     // but both point to the same place giving duplicate diagnostics.
11821     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11822       Visit(E->getCond());
11823       Visit(E->getFalseExpr());
11824     }
11825 
11826     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11827       Decl* ReferenceDecl = DRE->getDecl();
11828       if (OrigDecl != ReferenceDecl) return;
11829       unsigned diag;
11830       if (isReferenceType) {
11831         diag = diag::warn_uninit_self_reference_in_reference_init;
11832       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11833         diag = diag::warn_static_self_reference_in_init;
11834       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11835                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11836                  DRE->getDecl()->getType()->isRecordType()) {
11837         diag = diag::warn_uninit_self_reference_in_init;
11838       } else {
11839         // Local variables will be handled by the CFG analysis.
11840         return;
11841       }
11842 
11843       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11844                             S.PDiag(diag)
11845                                 << DRE->getDecl() << OrigDecl->getLocation()
11846                                 << DRE->getSourceRange());
11847     }
11848   };
11849 
11850   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11851   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11852                                  bool DirectInit) {
11853     // Parameters arguments are occassionially constructed with itself,
11854     // for instance, in recursive functions.  Skip them.
11855     if (isa<ParmVarDecl>(OrigDecl))
11856       return;
11857 
11858     E = E->IgnoreParens();
11859 
11860     // Skip checking T a = a where T is not a record or reference type.
11861     // Doing so is a way to silence uninitialized warnings.
11862     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11863       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11864         if (ICE->getCastKind() == CK_LValueToRValue)
11865           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11866             if (DRE->getDecl() == OrigDecl)
11867               return;
11868 
11869     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11870   }
11871 } // end anonymous namespace
11872 
11873 namespace {
11874   // Simple wrapper to add the name of a variable or (if no variable is
11875   // available) a DeclarationName into a diagnostic.
11876   struct VarDeclOrName {
11877     VarDecl *VDecl;
11878     DeclarationName Name;
11879 
11880     friend const Sema::SemaDiagnosticBuilder &
11881     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11882       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11883     }
11884   };
11885 } // end anonymous namespace
11886 
11887 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11888                                             DeclarationName Name, QualType Type,
11889                                             TypeSourceInfo *TSI,
11890                                             SourceRange Range, bool DirectInit,
11891                                             Expr *Init) {
11892   bool IsInitCapture = !VDecl;
11893   assert((!VDecl || !VDecl->isInitCapture()) &&
11894          "init captures are expected to be deduced prior to initialization");
11895 
11896   VarDeclOrName VN{VDecl, Name};
11897 
11898   DeducedType *Deduced = Type->getContainedDeducedType();
11899   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11900 
11901   // C++11 [dcl.spec.auto]p3
11902   if (!Init) {
11903     assert(VDecl && "no init for init capture deduction?");
11904 
11905     // Except for class argument deduction, and then for an initializing
11906     // declaration only, i.e. no static at class scope or extern.
11907     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11908         VDecl->hasExternalStorage() ||
11909         VDecl->isStaticDataMember()) {
11910       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11911         << VDecl->getDeclName() << Type;
11912       return QualType();
11913     }
11914   }
11915 
11916   ArrayRef<Expr*> DeduceInits;
11917   if (Init)
11918     DeduceInits = Init;
11919 
11920   if (DirectInit) {
11921     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11922       DeduceInits = PL->exprs();
11923   }
11924 
11925   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11926     assert(VDecl && "non-auto type for init capture deduction?");
11927     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11928     InitializationKind Kind = InitializationKind::CreateForInit(
11929         VDecl->getLocation(), DirectInit, Init);
11930     // FIXME: Initialization should not be taking a mutable list of inits.
11931     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11932     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11933                                                        InitsCopy);
11934   }
11935 
11936   if (DirectInit) {
11937     if (auto *IL = dyn_cast<InitListExpr>(Init))
11938       DeduceInits = IL->inits();
11939   }
11940 
11941   // Deduction only works if we have exactly one source expression.
11942   if (DeduceInits.empty()) {
11943     // It isn't possible to write this directly, but it is possible to
11944     // end up in this situation with "auto x(some_pack...);"
11945     Diag(Init->getBeginLoc(), IsInitCapture
11946                                   ? diag::err_init_capture_no_expression
11947                                   : diag::err_auto_var_init_no_expression)
11948         << VN << Type << Range;
11949     return QualType();
11950   }
11951 
11952   if (DeduceInits.size() > 1) {
11953     Diag(DeduceInits[1]->getBeginLoc(),
11954          IsInitCapture ? diag::err_init_capture_multiple_expressions
11955                        : diag::err_auto_var_init_multiple_expressions)
11956         << VN << Type << Range;
11957     return QualType();
11958   }
11959 
11960   Expr *DeduceInit = DeduceInits[0];
11961   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11962     Diag(Init->getBeginLoc(), IsInitCapture
11963                                   ? diag::err_init_capture_paren_braces
11964                                   : diag::err_auto_var_init_paren_braces)
11965         << isa<InitListExpr>(Init) << VN << Type << Range;
11966     return QualType();
11967   }
11968 
11969   // Expressions default to 'id' when we're in a debugger.
11970   bool DefaultedAnyToId = false;
11971   if (getLangOpts().DebuggerCastResultToId &&
11972       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11973     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11974     if (Result.isInvalid()) {
11975       return QualType();
11976     }
11977     Init = Result.get();
11978     DefaultedAnyToId = true;
11979   }
11980 
11981   // C++ [dcl.decomp]p1:
11982   //   If the assignment-expression [...] has array type A and no ref-qualifier
11983   //   is present, e has type cv A
11984   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11985       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11986       DeduceInit->getType()->isConstantArrayType())
11987     return Context.getQualifiedType(DeduceInit->getType(),
11988                                     Type.getQualifiers());
11989 
11990   QualType DeducedType;
11991   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11992     if (!IsInitCapture)
11993       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11994     else if (isa<InitListExpr>(Init))
11995       Diag(Range.getBegin(),
11996            diag::err_init_capture_deduction_failure_from_init_list)
11997           << VN
11998           << (DeduceInit->getType().isNull() ? TSI->getType()
11999                                              : DeduceInit->getType())
12000           << DeduceInit->getSourceRange();
12001     else
12002       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12003           << VN << TSI->getType()
12004           << (DeduceInit->getType().isNull() ? TSI->getType()
12005                                              : DeduceInit->getType())
12006           << DeduceInit->getSourceRange();
12007   }
12008 
12009   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12010   // 'id' instead of a specific object type prevents most of our usual
12011   // checks.
12012   // We only want to warn outside of template instantiations, though:
12013   // inside a template, the 'id' could have come from a parameter.
12014   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12015       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12016     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12017     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12018   }
12019 
12020   return DeducedType;
12021 }
12022 
12023 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12024                                          Expr *Init) {
12025   assert(!Init || !Init->containsErrors());
12026   QualType DeducedType = deduceVarTypeFromInitializer(
12027       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12028       VDecl->getSourceRange(), DirectInit, Init);
12029   if (DeducedType.isNull()) {
12030     VDecl->setInvalidDecl();
12031     return true;
12032   }
12033 
12034   VDecl->setType(DeducedType);
12035   assert(VDecl->isLinkageValid());
12036 
12037   // In ARC, infer lifetime.
12038   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12039     VDecl->setInvalidDecl();
12040 
12041   if (getLangOpts().OpenCL)
12042     deduceOpenCLAddressSpace(VDecl);
12043 
12044   // If this is a redeclaration, check that the type we just deduced matches
12045   // the previously declared type.
12046   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12047     // We never need to merge the type, because we cannot form an incomplete
12048     // array of auto, nor deduce such a type.
12049     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12050   }
12051 
12052   // Check the deduced type is valid for a variable declaration.
12053   CheckVariableDeclarationType(VDecl);
12054   return VDecl->isInvalidDecl();
12055 }
12056 
12057 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12058                                               SourceLocation Loc) {
12059   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12060     Init = EWC->getSubExpr();
12061 
12062   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12063     Init = CE->getSubExpr();
12064 
12065   QualType InitType = Init->getType();
12066   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12067           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12068          "shouldn't be called if type doesn't have a non-trivial C struct");
12069   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12070     for (auto I : ILE->inits()) {
12071       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12072           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12073         continue;
12074       SourceLocation SL = I->getExprLoc();
12075       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12076     }
12077     return;
12078   }
12079 
12080   if (isa<ImplicitValueInitExpr>(Init)) {
12081     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12082       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12083                             NTCUK_Init);
12084   } else {
12085     // Assume all other explicit initializers involving copying some existing
12086     // object.
12087     // TODO: ignore any explicit initializers where we can guarantee
12088     // copy-elision.
12089     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12090       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12091   }
12092 }
12093 
12094 namespace {
12095 
12096 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12097   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12098   // in the source code or implicitly by the compiler if it is in a union
12099   // defined in a system header and has non-trivial ObjC ownership
12100   // qualifications. We don't want those fields to participate in determining
12101   // whether the containing union is non-trivial.
12102   return FD->hasAttr<UnavailableAttr>();
12103 }
12104 
12105 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12106     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12107                                     void> {
12108   using Super =
12109       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12110                                     void>;
12111 
12112   DiagNonTrivalCUnionDefaultInitializeVisitor(
12113       QualType OrigTy, SourceLocation OrigLoc,
12114       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12115       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12116 
12117   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12118                      const FieldDecl *FD, bool InNonTrivialUnion) {
12119     if (const auto *AT = S.Context.getAsArrayType(QT))
12120       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12121                                      InNonTrivialUnion);
12122     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12123   }
12124 
12125   void visitARCStrong(QualType QT, const FieldDecl *FD,
12126                       bool InNonTrivialUnion) {
12127     if (InNonTrivialUnion)
12128       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12129           << 1 << 0 << QT << FD->getName();
12130   }
12131 
12132   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12133     if (InNonTrivialUnion)
12134       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12135           << 1 << 0 << QT << FD->getName();
12136   }
12137 
12138   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12139     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12140     if (RD->isUnion()) {
12141       if (OrigLoc.isValid()) {
12142         bool IsUnion = false;
12143         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12144           IsUnion = OrigRD->isUnion();
12145         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12146             << 0 << OrigTy << IsUnion << UseContext;
12147         // Reset OrigLoc so that this diagnostic is emitted only once.
12148         OrigLoc = SourceLocation();
12149       }
12150       InNonTrivialUnion = true;
12151     }
12152 
12153     if (InNonTrivialUnion)
12154       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12155           << 0 << 0 << QT.getUnqualifiedType() << "";
12156 
12157     for (const FieldDecl *FD : RD->fields())
12158       if (!shouldIgnoreForRecordTriviality(FD))
12159         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12160   }
12161 
12162   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12163 
12164   // The non-trivial C union type or the struct/union type that contains a
12165   // non-trivial C union.
12166   QualType OrigTy;
12167   SourceLocation OrigLoc;
12168   Sema::NonTrivialCUnionContext UseContext;
12169   Sema &S;
12170 };
12171 
12172 struct DiagNonTrivalCUnionDestructedTypeVisitor
12173     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12174   using Super =
12175       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12176 
12177   DiagNonTrivalCUnionDestructedTypeVisitor(
12178       QualType OrigTy, SourceLocation OrigLoc,
12179       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12180       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12181 
12182   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12183                      const FieldDecl *FD, bool InNonTrivialUnion) {
12184     if (const auto *AT = S.Context.getAsArrayType(QT))
12185       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12186                                      InNonTrivialUnion);
12187     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12188   }
12189 
12190   void visitARCStrong(QualType QT, const FieldDecl *FD,
12191                       bool InNonTrivialUnion) {
12192     if (InNonTrivialUnion)
12193       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12194           << 1 << 1 << QT << FD->getName();
12195   }
12196 
12197   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12198     if (InNonTrivialUnion)
12199       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12200           << 1 << 1 << QT << FD->getName();
12201   }
12202 
12203   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12204     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12205     if (RD->isUnion()) {
12206       if (OrigLoc.isValid()) {
12207         bool IsUnion = false;
12208         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12209           IsUnion = OrigRD->isUnion();
12210         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12211             << 1 << OrigTy << IsUnion << UseContext;
12212         // Reset OrigLoc so that this diagnostic is emitted only once.
12213         OrigLoc = SourceLocation();
12214       }
12215       InNonTrivialUnion = true;
12216     }
12217 
12218     if (InNonTrivialUnion)
12219       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12220           << 0 << 1 << QT.getUnqualifiedType() << "";
12221 
12222     for (const FieldDecl *FD : RD->fields())
12223       if (!shouldIgnoreForRecordTriviality(FD))
12224         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12225   }
12226 
12227   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12228   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12229                           bool InNonTrivialUnion) {}
12230 
12231   // The non-trivial C union type or the struct/union type that contains a
12232   // non-trivial C union.
12233   QualType OrigTy;
12234   SourceLocation OrigLoc;
12235   Sema::NonTrivialCUnionContext UseContext;
12236   Sema &S;
12237 };
12238 
12239 struct DiagNonTrivalCUnionCopyVisitor
12240     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12241   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12242 
12243   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12244                                  Sema::NonTrivialCUnionContext UseContext,
12245                                  Sema &S)
12246       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12247 
12248   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12249                      const FieldDecl *FD, bool InNonTrivialUnion) {
12250     if (const auto *AT = S.Context.getAsArrayType(QT))
12251       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12252                                      InNonTrivialUnion);
12253     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12254   }
12255 
12256   void visitARCStrong(QualType QT, const FieldDecl *FD,
12257                       bool InNonTrivialUnion) {
12258     if (InNonTrivialUnion)
12259       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12260           << 1 << 2 << QT << FD->getName();
12261   }
12262 
12263   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12264     if (InNonTrivialUnion)
12265       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12266           << 1 << 2 << QT << FD->getName();
12267   }
12268 
12269   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12270     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12271     if (RD->isUnion()) {
12272       if (OrigLoc.isValid()) {
12273         bool IsUnion = false;
12274         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12275           IsUnion = OrigRD->isUnion();
12276         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12277             << 2 << OrigTy << IsUnion << UseContext;
12278         // Reset OrigLoc so that this diagnostic is emitted only once.
12279         OrigLoc = SourceLocation();
12280       }
12281       InNonTrivialUnion = true;
12282     }
12283 
12284     if (InNonTrivialUnion)
12285       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12286           << 0 << 2 << QT.getUnqualifiedType() << "";
12287 
12288     for (const FieldDecl *FD : RD->fields())
12289       if (!shouldIgnoreForRecordTriviality(FD))
12290         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12291   }
12292 
12293   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12294                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12295   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12296   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12297                             bool InNonTrivialUnion) {}
12298 
12299   // The non-trivial C union type or the struct/union type that contains a
12300   // non-trivial C union.
12301   QualType OrigTy;
12302   SourceLocation OrigLoc;
12303   Sema::NonTrivialCUnionContext UseContext;
12304   Sema &S;
12305 };
12306 
12307 } // namespace
12308 
12309 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12310                                  NonTrivialCUnionContext UseContext,
12311                                  unsigned NonTrivialKind) {
12312   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12313           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12314           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12315          "shouldn't be called if type doesn't have a non-trivial C union");
12316 
12317   if ((NonTrivialKind & NTCUK_Init) &&
12318       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12319     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12320         .visit(QT, nullptr, false);
12321   if ((NonTrivialKind & NTCUK_Destruct) &&
12322       QT.hasNonTrivialToPrimitiveDestructCUnion())
12323     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12324         .visit(QT, nullptr, false);
12325   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12326     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12327         .visit(QT, nullptr, false);
12328 }
12329 
12330 /// AddInitializerToDecl - Adds the initializer Init to the
12331 /// declaration dcl. If DirectInit is true, this is C++ direct
12332 /// initialization rather than copy initialization.
12333 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12334   // If there is no declaration, there was an error parsing it.  Just ignore
12335   // the initializer.
12336   if (!RealDecl || RealDecl->isInvalidDecl()) {
12337     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12338     return;
12339   }
12340 
12341   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12342     // Pure-specifiers are handled in ActOnPureSpecifier.
12343     Diag(Method->getLocation(), diag::err_member_function_initialization)
12344       << Method->getDeclName() << Init->getSourceRange();
12345     Method->setInvalidDecl();
12346     return;
12347   }
12348 
12349   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12350   if (!VDecl) {
12351     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12352     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12353     RealDecl->setInvalidDecl();
12354     return;
12355   }
12356 
12357   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12358   if (VDecl->getType()->isUndeducedType()) {
12359     // Attempt typo correction early so that the type of the init expression can
12360     // be deduced based on the chosen correction if the original init contains a
12361     // TypoExpr.
12362     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12363     if (!Res.isUsable()) {
12364       // There are unresolved typos in Init, just drop them.
12365       // FIXME: improve the recovery strategy to preserve the Init.
12366       RealDecl->setInvalidDecl();
12367       return;
12368     }
12369     if (Res.get()->containsErrors()) {
12370       // Invalidate the decl as we don't know the type for recovery-expr yet.
12371       RealDecl->setInvalidDecl();
12372       VDecl->setInit(Res.get());
12373       return;
12374     }
12375     Init = Res.get();
12376 
12377     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12378       return;
12379   }
12380 
12381   // dllimport cannot be used on variable definitions.
12382   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12383     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12384     VDecl->setInvalidDecl();
12385     return;
12386   }
12387 
12388   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12389     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12390     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12391     VDecl->setInvalidDecl();
12392     return;
12393   }
12394 
12395   if (!VDecl->getType()->isDependentType()) {
12396     // A definition must end up with a complete type, which means it must be
12397     // complete with the restriction that an array type might be completed by
12398     // the initializer; note that later code assumes this restriction.
12399     QualType BaseDeclType = VDecl->getType();
12400     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12401       BaseDeclType = Array->getElementType();
12402     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12403                             diag::err_typecheck_decl_incomplete_type)) {
12404       RealDecl->setInvalidDecl();
12405       return;
12406     }
12407 
12408     // The variable can not have an abstract class type.
12409     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12410                                diag::err_abstract_type_in_decl,
12411                                AbstractVariableType))
12412       VDecl->setInvalidDecl();
12413   }
12414 
12415   // If adding the initializer will turn this declaration into a definition,
12416   // and we already have a definition for this variable, diagnose or otherwise
12417   // handle the situation.
12418   if (VarDecl *Def = VDecl->getDefinition())
12419     if (Def != VDecl &&
12420         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12421         !VDecl->isThisDeclarationADemotedDefinition() &&
12422         checkVarDeclRedefinition(Def, VDecl))
12423       return;
12424 
12425   if (getLangOpts().CPlusPlus) {
12426     // C++ [class.static.data]p4
12427     //   If a static data member is of const integral or const
12428     //   enumeration type, its declaration in the class definition can
12429     //   specify a constant-initializer which shall be an integral
12430     //   constant expression (5.19). In that case, the member can appear
12431     //   in integral constant expressions. The member shall still be
12432     //   defined in a namespace scope if it is used in the program and the
12433     //   namespace scope definition shall not contain an initializer.
12434     //
12435     // We already performed a redefinition check above, but for static
12436     // data members we also need to check whether there was an in-class
12437     // declaration with an initializer.
12438     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12439       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12440           << VDecl->getDeclName();
12441       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12442            diag::note_previous_initializer)
12443           << 0;
12444       return;
12445     }
12446 
12447     if (VDecl->hasLocalStorage())
12448       setFunctionHasBranchProtectedScope();
12449 
12450     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12451       VDecl->setInvalidDecl();
12452       return;
12453     }
12454   }
12455 
12456   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12457   // a kernel function cannot be initialized."
12458   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12459     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12460     VDecl->setInvalidDecl();
12461     return;
12462   }
12463 
12464   // The LoaderUninitialized attribute acts as a definition (of undef).
12465   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12466     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12467     VDecl->setInvalidDecl();
12468     return;
12469   }
12470 
12471   // Get the decls type and save a reference for later, since
12472   // CheckInitializerTypes may change it.
12473   QualType DclT = VDecl->getType(), SavT = DclT;
12474 
12475   // Expressions default to 'id' when we're in a debugger
12476   // and we are assigning it to a variable of Objective-C pointer type.
12477   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12478       Init->getType() == Context.UnknownAnyTy) {
12479     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12480     if (Result.isInvalid()) {
12481       VDecl->setInvalidDecl();
12482       return;
12483     }
12484     Init = Result.get();
12485   }
12486 
12487   // Perform the initialization.
12488   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12489   if (!VDecl->isInvalidDecl()) {
12490     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12491     InitializationKind Kind = InitializationKind::CreateForInit(
12492         VDecl->getLocation(), DirectInit, Init);
12493 
12494     MultiExprArg Args = Init;
12495     if (CXXDirectInit)
12496       Args = MultiExprArg(CXXDirectInit->getExprs(),
12497                           CXXDirectInit->getNumExprs());
12498 
12499     // Try to correct any TypoExprs in the initialization arguments.
12500     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12501       ExprResult Res = CorrectDelayedTyposInExpr(
12502           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12503           [this, Entity, Kind](Expr *E) {
12504             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12505             return Init.Failed() ? ExprError() : E;
12506           });
12507       if (Res.isInvalid()) {
12508         VDecl->setInvalidDecl();
12509       } else if (Res.get() != Args[Idx]) {
12510         Args[Idx] = Res.get();
12511       }
12512     }
12513     if (VDecl->isInvalidDecl())
12514       return;
12515 
12516     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12517                                    /*TopLevelOfInitList=*/false,
12518                                    /*TreatUnavailableAsInvalid=*/false);
12519     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12520     if (Result.isInvalid()) {
12521       // If the provided initializer fails to initialize the var decl,
12522       // we attach a recovery expr for better recovery.
12523       auto RecoveryExpr =
12524           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12525       if (RecoveryExpr.get())
12526         VDecl->setInit(RecoveryExpr.get());
12527       return;
12528     }
12529 
12530     Init = Result.getAs<Expr>();
12531   }
12532 
12533   // Check for self-references within variable initializers.
12534   // Variables declared within a function/method body (except for references)
12535   // are handled by a dataflow analysis.
12536   // This is undefined behavior in C++, but valid in C.
12537   if (getLangOpts().CPlusPlus)
12538     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12539         VDecl->getType()->isReferenceType())
12540       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12541 
12542   // If the type changed, it means we had an incomplete type that was
12543   // completed by the initializer. For example:
12544   //   int ary[] = { 1, 3, 5 };
12545   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12546   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12547     VDecl->setType(DclT);
12548 
12549   if (!VDecl->isInvalidDecl()) {
12550     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12551 
12552     if (VDecl->hasAttr<BlocksAttr>())
12553       checkRetainCycles(VDecl, Init);
12554 
12555     // It is safe to assign a weak reference into a strong variable.
12556     // Although this code can still have problems:
12557     //   id x = self.weakProp;
12558     //   id y = self.weakProp;
12559     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12560     // paths through the function. This should be revisited if
12561     // -Wrepeated-use-of-weak is made flow-sensitive.
12562     if (FunctionScopeInfo *FSI = getCurFunction())
12563       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12564            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12565           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12566                            Init->getBeginLoc()))
12567         FSI->markSafeWeakUse(Init);
12568   }
12569 
12570   // The initialization is usually a full-expression.
12571   //
12572   // FIXME: If this is a braced initialization of an aggregate, it is not
12573   // an expression, and each individual field initializer is a separate
12574   // full-expression. For instance, in:
12575   //
12576   //   struct Temp { ~Temp(); };
12577   //   struct S { S(Temp); };
12578   //   struct T { S a, b; } t = { Temp(), Temp() }
12579   //
12580   // we should destroy the first Temp before constructing the second.
12581   ExprResult Result =
12582       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12583                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12584   if (Result.isInvalid()) {
12585     VDecl->setInvalidDecl();
12586     return;
12587   }
12588   Init = Result.get();
12589 
12590   // Attach the initializer to the decl.
12591   VDecl->setInit(Init);
12592 
12593   if (VDecl->isLocalVarDecl()) {
12594     // Don't check the initializer if the declaration is malformed.
12595     if (VDecl->isInvalidDecl()) {
12596       // do nothing
12597 
12598     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12599     // This is true even in C++ for OpenCL.
12600     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12601       CheckForConstantInitializer(Init, DclT);
12602 
12603     // Otherwise, C++ does not restrict the initializer.
12604     } else if (getLangOpts().CPlusPlus) {
12605       // do nothing
12606 
12607     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12608     // static storage duration shall be constant expressions or string literals.
12609     } else if (VDecl->getStorageClass() == SC_Static) {
12610       CheckForConstantInitializer(Init, DclT);
12611 
12612     // C89 is stricter than C99 for aggregate initializers.
12613     // C89 6.5.7p3: All the expressions [...] in an initializer list
12614     // for an object that has aggregate or union type shall be
12615     // constant expressions.
12616     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12617                isa<InitListExpr>(Init)) {
12618       const Expr *Culprit;
12619       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12620         Diag(Culprit->getExprLoc(),
12621              diag::ext_aggregate_init_not_constant)
12622           << Culprit->getSourceRange();
12623       }
12624     }
12625 
12626     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12627       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12628         if (VDecl->hasLocalStorage())
12629           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12630   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12631              VDecl->getLexicalDeclContext()->isRecord()) {
12632     // This is an in-class initialization for a static data member, e.g.,
12633     //
12634     // struct S {
12635     //   static const int value = 17;
12636     // };
12637 
12638     // C++ [class.mem]p4:
12639     //   A member-declarator can contain a constant-initializer only
12640     //   if it declares a static member (9.4) of const integral or
12641     //   const enumeration type, see 9.4.2.
12642     //
12643     // C++11 [class.static.data]p3:
12644     //   If a non-volatile non-inline const static data member is of integral
12645     //   or enumeration type, its declaration in the class definition can
12646     //   specify a brace-or-equal-initializer in which every initializer-clause
12647     //   that is an assignment-expression is a constant expression. A static
12648     //   data member of literal type can be declared in the class definition
12649     //   with the constexpr specifier; if so, its declaration shall specify a
12650     //   brace-or-equal-initializer in which every initializer-clause that is
12651     //   an assignment-expression is a constant expression.
12652 
12653     // Do nothing on dependent types.
12654     if (DclT->isDependentType()) {
12655 
12656     // Allow any 'static constexpr' members, whether or not they are of literal
12657     // type. We separately check that every constexpr variable is of literal
12658     // type.
12659     } else if (VDecl->isConstexpr()) {
12660 
12661     // Require constness.
12662     } else if (!DclT.isConstQualified()) {
12663       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12664         << Init->getSourceRange();
12665       VDecl->setInvalidDecl();
12666 
12667     // We allow integer constant expressions in all cases.
12668     } else if (DclT->isIntegralOrEnumerationType()) {
12669       // Check whether the expression is a constant expression.
12670       SourceLocation Loc;
12671       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12672         // In C++11, a non-constexpr const static data member with an
12673         // in-class initializer cannot be volatile.
12674         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12675       else if (Init->isValueDependent())
12676         ; // Nothing to check.
12677       else if (Init->isIntegerConstantExpr(Context, &Loc))
12678         ; // Ok, it's an ICE!
12679       else if (Init->getType()->isScopedEnumeralType() &&
12680                Init->isCXX11ConstantExpr(Context))
12681         ; // Ok, it is a scoped-enum constant expression.
12682       else if (Init->isEvaluatable(Context)) {
12683         // If we can constant fold the initializer through heroics, accept it,
12684         // but report this as a use of an extension for -pedantic.
12685         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12686           << Init->getSourceRange();
12687       } else {
12688         // Otherwise, this is some crazy unknown case.  Report the issue at the
12689         // location provided by the isIntegerConstantExpr failed check.
12690         Diag(Loc, diag::err_in_class_initializer_non_constant)
12691           << Init->getSourceRange();
12692         VDecl->setInvalidDecl();
12693       }
12694 
12695     // We allow foldable floating-point constants as an extension.
12696     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12697       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12698       // it anyway and provide a fixit to add the 'constexpr'.
12699       if (getLangOpts().CPlusPlus11) {
12700         Diag(VDecl->getLocation(),
12701              diag::ext_in_class_initializer_float_type_cxx11)
12702             << DclT << Init->getSourceRange();
12703         Diag(VDecl->getBeginLoc(),
12704              diag::note_in_class_initializer_float_type_cxx11)
12705             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12706       } else {
12707         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12708           << DclT << Init->getSourceRange();
12709 
12710         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12711           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12712             << Init->getSourceRange();
12713           VDecl->setInvalidDecl();
12714         }
12715       }
12716 
12717     // Suggest adding 'constexpr' in C++11 for literal types.
12718     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12719       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12720           << DclT << Init->getSourceRange()
12721           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12722       VDecl->setConstexpr(true);
12723 
12724     } else {
12725       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12726         << DclT << Init->getSourceRange();
12727       VDecl->setInvalidDecl();
12728     }
12729   } else if (VDecl->isFileVarDecl()) {
12730     // In C, extern is typically used to avoid tentative definitions when
12731     // declaring variables in headers, but adding an intializer makes it a
12732     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12733     // In C++, extern is often used to give implictly static const variables
12734     // external linkage, so don't warn in that case. If selectany is present,
12735     // this might be header code intended for C and C++ inclusion, so apply the
12736     // C++ rules.
12737     if (VDecl->getStorageClass() == SC_Extern &&
12738         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12739          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12740         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12741         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12742       Diag(VDecl->getLocation(), diag::warn_extern_init);
12743 
12744     // In Microsoft C++ mode, a const variable defined in namespace scope has
12745     // external linkage by default if the variable is declared with
12746     // __declspec(dllexport).
12747     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12748         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12749         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12750       VDecl->setStorageClass(SC_Extern);
12751 
12752     // C99 6.7.8p4. All file scoped initializers need to be constant.
12753     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12754       CheckForConstantInitializer(Init, DclT);
12755   }
12756 
12757   QualType InitType = Init->getType();
12758   if (!InitType.isNull() &&
12759       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12760        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12761     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12762 
12763   // We will represent direct-initialization similarly to copy-initialization:
12764   //    int x(1);  -as-> int x = 1;
12765   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12766   //
12767   // Clients that want to distinguish between the two forms, can check for
12768   // direct initializer using VarDecl::getInitStyle().
12769   // A major benefit is that clients that don't particularly care about which
12770   // exactly form was it (like the CodeGen) can handle both cases without
12771   // special case code.
12772 
12773   // C++ 8.5p11:
12774   // The form of initialization (using parentheses or '=') is generally
12775   // insignificant, but does matter when the entity being initialized has a
12776   // class type.
12777   if (CXXDirectInit) {
12778     assert(DirectInit && "Call-style initializer must be direct init.");
12779     VDecl->setInitStyle(VarDecl::CallInit);
12780   } else if (DirectInit) {
12781     // This must be list-initialization. No other way is direct-initialization.
12782     VDecl->setInitStyle(VarDecl::ListInit);
12783   }
12784 
12785   if (LangOpts.OpenMP &&
12786       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12787       VDecl->isFileVarDecl())
12788     DeclsToCheckForDeferredDiags.insert(VDecl);
12789   CheckCompleteVariableDeclaration(VDecl);
12790 }
12791 
12792 /// ActOnInitializerError - Given that there was an error parsing an
12793 /// initializer for the given declaration, try to at least re-establish
12794 /// invariants such as whether a variable's type is either dependent or
12795 /// complete.
12796 void Sema::ActOnInitializerError(Decl *D) {
12797   // Our main concern here is re-establishing invariants like "a
12798   // variable's type is either dependent or complete".
12799   if (!D || D->isInvalidDecl()) return;
12800 
12801   VarDecl *VD = dyn_cast<VarDecl>(D);
12802   if (!VD) return;
12803 
12804   // Bindings are not usable if we can't make sense of the initializer.
12805   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12806     for (auto *BD : DD->bindings())
12807       BD->setInvalidDecl();
12808 
12809   // Auto types are meaningless if we can't make sense of the initializer.
12810   if (VD->getType()->isUndeducedType()) {
12811     D->setInvalidDecl();
12812     return;
12813   }
12814 
12815   QualType Ty = VD->getType();
12816   if (Ty->isDependentType()) return;
12817 
12818   // Require a complete type.
12819   if (RequireCompleteType(VD->getLocation(),
12820                           Context.getBaseElementType(Ty),
12821                           diag::err_typecheck_decl_incomplete_type)) {
12822     VD->setInvalidDecl();
12823     return;
12824   }
12825 
12826   // Require a non-abstract type.
12827   if (RequireNonAbstractType(VD->getLocation(), Ty,
12828                              diag::err_abstract_type_in_decl,
12829                              AbstractVariableType)) {
12830     VD->setInvalidDecl();
12831     return;
12832   }
12833 
12834   // Don't bother complaining about constructors or destructors,
12835   // though.
12836 }
12837 
12838 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12839   // If there is no declaration, there was an error parsing it. Just ignore it.
12840   if (!RealDecl)
12841     return;
12842 
12843   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12844     QualType Type = Var->getType();
12845 
12846     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12847     if (isa<DecompositionDecl>(RealDecl)) {
12848       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12849       Var->setInvalidDecl();
12850       return;
12851     }
12852 
12853     if (Type->isUndeducedType() &&
12854         DeduceVariableDeclarationType(Var, false, nullptr))
12855       return;
12856 
12857     // C++11 [class.static.data]p3: A static data member can be declared with
12858     // the constexpr specifier; if so, its declaration shall specify
12859     // a brace-or-equal-initializer.
12860     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12861     // the definition of a variable [...] or the declaration of a static data
12862     // member.
12863     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12864         !Var->isThisDeclarationADemotedDefinition()) {
12865       if (Var->isStaticDataMember()) {
12866         // C++1z removes the relevant rule; the in-class declaration is always
12867         // a definition there.
12868         if (!getLangOpts().CPlusPlus17 &&
12869             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12870           Diag(Var->getLocation(),
12871                diag::err_constexpr_static_mem_var_requires_init)
12872               << Var;
12873           Var->setInvalidDecl();
12874           return;
12875         }
12876       } else {
12877         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12878         Var->setInvalidDecl();
12879         return;
12880       }
12881     }
12882 
12883     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12884     // be initialized.
12885     if (!Var->isInvalidDecl() &&
12886         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12887         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12888       bool HasConstExprDefaultConstructor = false;
12889       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12890         for (auto *Ctor : RD->ctors()) {
12891           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12892               Ctor->getMethodQualifiers().getAddressSpace() ==
12893                   LangAS::opencl_constant) {
12894             HasConstExprDefaultConstructor = true;
12895           }
12896         }
12897       }
12898       if (!HasConstExprDefaultConstructor) {
12899         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12900         Var->setInvalidDecl();
12901         return;
12902       }
12903     }
12904 
12905     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12906       if (Var->getStorageClass() == SC_Extern) {
12907         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12908             << Var;
12909         Var->setInvalidDecl();
12910         return;
12911       }
12912       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12913                               diag::err_typecheck_decl_incomplete_type)) {
12914         Var->setInvalidDecl();
12915         return;
12916       }
12917       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12918         if (!RD->hasTrivialDefaultConstructor()) {
12919           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12920           Var->setInvalidDecl();
12921           return;
12922         }
12923       }
12924       // The declaration is unitialized, no need for further checks.
12925       return;
12926     }
12927 
12928     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12929     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12930         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12931       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12932                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12933 
12934 
12935     switch (DefKind) {
12936     case VarDecl::Definition:
12937       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12938         break;
12939 
12940       // We have an out-of-line definition of a static data member
12941       // that has an in-class initializer, so we type-check this like
12942       // a declaration.
12943       //
12944       LLVM_FALLTHROUGH;
12945 
12946     case VarDecl::DeclarationOnly:
12947       // It's only a declaration.
12948 
12949       // Block scope. C99 6.7p7: If an identifier for an object is
12950       // declared with no linkage (C99 6.2.2p6), the type for the
12951       // object shall be complete.
12952       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12953           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12954           RequireCompleteType(Var->getLocation(), Type,
12955                               diag::err_typecheck_decl_incomplete_type))
12956         Var->setInvalidDecl();
12957 
12958       // Make sure that the type is not abstract.
12959       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12960           RequireNonAbstractType(Var->getLocation(), Type,
12961                                  diag::err_abstract_type_in_decl,
12962                                  AbstractVariableType))
12963         Var->setInvalidDecl();
12964       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12965           Var->getStorageClass() == SC_PrivateExtern) {
12966         Diag(Var->getLocation(), diag::warn_private_extern);
12967         Diag(Var->getLocation(), diag::note_private_extern);
12968       }
12969 
12970       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12971           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12972         ExternalDeclarations.push_back(Var);
12973 
12974       return;
12975 
12976     case VarDecl::TentativeDefinition:
12977       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12978       // object that has file scope without an initializer, and without a
12979       // storage-class specifier or with the storage-class specifier "static",
12980       // constitutes a tentative definition. Note: A tentative definition with
12981       // external linkage is valid (C99 6.2.2p5).
12982       if (!Var->isInvalidDecl()) {
12983         if (const IncompleteArrayType *ArrayT
12984                                     = Context.getAsIncompleteArrayType(Type)) {
12985           if (RequireCompleteSizedType(
12986                   Var->getLocation(), ArrayT->getElementType(),
12987                   diag::err_array_incomplete_or_sizeless_type))
12988             Var->setInvalidDecl();
12989         } else if (Var->getStorageClass() == SC_Static) {
12990           // C99 6.9.2p3: If the declaration of an identifier for an object is
12991           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12992           // declared type shall not be an incomplete type.
12993           // NOTE: code such as the following
12994           //     static struct s;
12995           //     struct s { int a; };
12996           // is accepted by gcc. Hence here we issue a warning instead of
12997           // an error and we do not invalidate the static declaration.
12998           // NOTE: to avoid multiple warnings, only check the first declaration.
12999           if (Var->isFirstDecl())
13000             RequireCompleteType(Var->getLocation(), Type,
13001                                 diag::ext_typecheck_decl_incomplete_type);
13002         }
13003       }
13004 
13005       // Record the tentative definition; we're done.
13006       if (!Var->isInvalidDecl())
13007         TentativeDefinitions.push_back(Var);
13008       return;
13009     }
13010 
13011     // Provide a specific diagnostic for uninitialized variable
13012     // definitions with incomplete array type.
13013     if (Type->isIncompleteArrayType()) {
13014       Diag(Var->getLocation(),
13015            diag::err_typecheck_incomplete_array_needs_initializer);
13016       Var->setInvalidDecl();
13017       return;
13018     }
13019 
13020     // Provide a specific diagnostic for uninitialized variable
13021     // definitions with reference type.
13022     if (Type->isReferenceType()) {
13023       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13024           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13025       Var->setInvalidDecl();
13026       return;
13027     }
13028 
13029     // Do not attempt to type-check the default initializer for a
13030     // variable with dependent type.
13031     if (Type->isDependentType())
13032       return;
13033 
13034     if (Var->isInvalidDecl())
13035       return;
13036 
13037     if (!Var->hasAttr<AliasAttr>()) {
13038       if (RequireCompleteType(Var->getLocation(),
13039                               Context.getBaseElementType(Type),
13040                               diag::err_typecheck_decl_incomplete_type)) {
13041         Var->setInvalidDecl();
13042         return;
13043       }
13044     } else {
13045       return;
13046     }
13047 
13048     // The variable can not have an abstract class type.
13049     if (RequireNonAbstractType(Var->getLocation(), Type,
13050                                diag::err_abstract_type_in_decl,
13051                                AbstractVariableType)) {
13052       Var->setInvalidDecl();
13053       return;
13054     }
13055 
13056     // Check for jumps past the implicit initializer.  C++0x
13057     // clarifies that this applies to a "variable with automatic
13058     // storage duration", not a "local variable".
13059     // C++11 [stmt.dcl]p3
13060     //   A program that jumps from a point where a variable with automatic
13061     //   storage duration is not in scope to a point where it is in scope is
13062     //   ill-formed unless the variable has scalar type, class type with a
13063     //   trivial default constructor and a trivial destructor, a cv-qualified
13064     //   version of one of these types, or an array of one of the preceding
13065     //   types and is declared without an initializer.
13066     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13067       if (const RecordType *Record
13068             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13069         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13070         // Mark the function (if we're in one) for further checking even if the
13071         // looser rules of C++11 do not require such checks, so that we can
13072         // diagnose incompatibilities with C++98.
13073         if (!CXXRecord->isPOD())
13074           setFunctionHasBranchProtectedScope();
13075       }
13076     }
13077     // In OpenCL, we can't initialize objects in the __local address space,
13078     // even implicitly, so don't synthesize an implicit initializer.
13079     if (getLangOpts().OpenCL &&
13080         Var->getType().getAddressSpace() == LangAS::opencl_local)
13081       return;
13082     // C++03 [dcl.init]p9:
13083     //   If no initializer is specified for an object, and the
13084     //   object is of (possibly cv-qualified) non-POD class type (or
13085     //   array thereof), the object shall be default-initialized; if
13086     //   the object is of const-qualified type, the underlying class
13087     //   type shall have a user-declared default
13088     //   constructor. Otherwise, if no initializer is specified for
13089     //   a non- static object, the object and its subobjects, if
13090     //   any, have an indeterminate initial value); if the object
13091     //   or any of its subobjects are of const-qualified type, the
13092     //   program is ill-formed.
13093     // C++0x [dcl.init]p11:
13094     //   If no initializer is specified for an object, the object is
13095     //   default-initialized; [...].
13096     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13097     InitializationKind Kind
13098       = InitializationKind::CreateDefault(Var->getLocation());
13099 
13100     InitializationSequence InitSeq(*this, Entity, Kind, None);
13101     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13102 
13103     if (Init.get()) {
13104       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13105       // This is important for template substitution.
13106       Var->setInitStyle(VarDecl::CallInit);
13107     } else if (Init.isInvalid()) {
13108       // If default-init fails, attach a recovery-expr initializer to track
13109       // that initialization was attempted and failed.
13110       auto RecoveryExpr =
13111           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13112       if (RecoveryExpr.get())
13113         Var->setInit(RecoveryExpr.get());
13114     }
13115 
13116     CheckCompleteVariableDeclaration(Var);
13117   }
13118 }
13119 
13120 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13121   // If there is no declaration, there was an error parsing it. Ignore it.
13122   if (!D)
13123     return;
13124 
13125   VarDecl *VD = dyn_cast<VarDecl>(D);
13126   if (!VD) {
13127     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13128     D->setInvalidDecl();
13129     return;
13130   }
13131 
13132   VD->setCXXForRangeDecl(true);
13133 
13134   // for-range-declaration cannot be given a storage class specifier.
13135   int Error = -1;
13136   switch (VD->getStorageClass()) {
13137   case SC_None:
13138     break;
13139   case SC_Extern:
13140     Error = 0;
13141     break;
13142   case SC_Static:
13143     Error = 1;
13144     break;
13145   case SC_PrivateExtern:
13146     Error = 2;
13147     break;
13148   case SC_Auto:
13149     Error = 3;
13150     break;
13151   case SC_Register:
13152     Error = 4;
13153     break;
13154   }
13155 
13156   // for-range-declaration cannot be given a storage class specifier con't.
13157   switch (VD->getTSCSpec()) {
13158   case TSCS_thread_local:
13159     Error = 6;
13160     break;
13161   case TSCS___thread:
13162   case TSCS__Thread_local:
13163   case TSCS_unspecified:
13164     break;
13165   }
13166 
13167   if (Error != -1) {
13168     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13169         << VD << Error;
13170     D->setInvalidDecl();
13171   }
13172 }
13173 
13174 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13175                                             IdentifierInfo *Ident,
13176                                             ParsedAttributes &Attrs) {
13177   // C++1y [stmt.iter]p1:
13178   //   A range-based for statement of the form
13179   //      for ( for-range-identifier : for-range-initializer ) statement
13180   //   is equivalent to
13181   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13182   DeclSpec DS(Attrs.getPool().getFactory());
13183 
13184   const char *PrevSpec;
13185   unsigned DiagID;
13186   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13187                      getPrintingPolicy());
13188 
13189   Declarator D(DS, DeclaratorContext::ForInit);
13190   D.SetIdentifier(Ident, IdentLoc);
13191   D.takeAttributes(Attrs);
13192 
13193   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13194                 IdentLoc);
13195   Decl *Var = ActOnDeclarator(S, D);
13196   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13197   FinalizeDeclaration(Var);
13198   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13199                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13200                                                       : IdentLoc);
13201 }
13202 
13203 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13204   if (var->isInvalidDecl()) return;
13205 
13206   MaybeAddCUDAConstantAttr(var);
13207 
13208   if (getLangOpts().OpenCL) {
13209     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13210     // initialiser
13211     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13212         !var->hasInit()) {
13213       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13214           << 1 /*Init*/;
13215       var->setInvalidDecl();
13216       return;
13217     }
13218   }
13219 
13220   // In Objective-C, don't allow jumps past the implicit initialization of a
13221   // local retaining variable.
13222   if (getLangOpts().ObjC &&
13223       var->hasLocalStorage()) {
13224     switch (var->getType().getObjCLifetime()) {
13225     case Qualifiers::OCL_None:
13226     case Qualifiers::OCL_ExplicitNone:
13227     case Qualifiers::OCL_Autoreleasing:
13228       break;
13229 
13230     case Qualifiers::OCL_Weak:
13231     case Qualifiers::OCL_Strong:
13232       setFunctionHasBranchProtectedScope();
13233       break;
13234     }
13235   }
13236 
13237   if (var->hasLocalStorage() &&
13238       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13239     setFunctionHasBranchProtectedScope();
13240 
13241   // Warn about externally-visible variables being defined without a
13242   // prior declaration.  We only want to do this for global
13243   // declarations, but we also specifically need to avoid doing it for
13244   // class members because the linkage of an anonymous class can
13245   // change if it's later given a typedef name.
13246   if (var->isThisDeclarationADefinition() &&
13247       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13248       var->isExternallyVisible() && var->hasLinkage() &&
13249       !var->isInline() && !var->getDescribedVarTemplate() &&
13250       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13251       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13252       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13253                                   var->getLocation())) {
13254     // Find a previous declaration that's not a definition.
13255     VarDecl *prev = var->getPreviousDecl();
13256     while (prev && prev->isThisDeclarationADefinition())
13257       prev = prev->getPreviousDecl();
13258 
13259     if (!prev) {
13260       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13261       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13262           << /* variable */ 0;
13263     }
13264   }
13265 
13266   // Cache the result of checking for constant initialization.
13267   Optional<bool> CacheHasConstInit;
13268   const Expr *CacheCulprit = nullptr;
13269   auto checkConstInit = [&]() mutable {
13270     if (!CacheHasConstInit)
13271       CacheHasConstInit = var->getInit()->isConstantInitializer(
13272             Context, var->getType()->isReferenceType(), &CacheCulprit);
13273     return *CacheHasConstInit;
13274   };
13275 
13276   if (var->getTLSKind() == VarDecl::TLS_Static) {
13277     if (var->getType().isDestructedType()) {
13278       // GNU C++98 edits for __thread, [basic.start.term]p3:
13279       //   The type of an object with thread storage duration shall not
13280       //   have a non-trivial destructor.
13281       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13282       if (getLangOpts().CPlusPlus11)
13283         Diag(var->getLocation(), diag::note_use_thread_local);
13284     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13285       if (!checkConstInit()) {
13286         // GNU C++98 edits for __thread, [basic.start.init]p4:
13287         //   An object of thread storage duration shall not require dynamic
13288         //   initialization.
13289         // FIXME: Need strict checking here.
13290         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13291           << CacheCulprit->getSourceRange();
13292         if (getLangOpts().CPlusPlus11)
13293           Diag(var->getLocation(), diag::note_use_thread_local);
13294       }
13295     }
13296   }
13297 
13298 
13299   if (!var->getType()->isStructureType() && var->hasInit() &&
13300       isa<InitListExpr>(var->getInit())) {
13301     const auto *ILE = cast<InitListExpr>(var->getInit());
13302     unsigned NumInits = ILE->getNumInits();
13303     if (NumInits > 2)
13304       for (unsigned I = 0; I < NumInits; ++I) {
13305         const auto *Init = ILE->getInit(I);
13306         if (!Init)
13307           break;
13308         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13309         if (!SL)
13310           break;
13311 
13312         unsigned NumConcat = SL->getNumConcatenated();
13313         // Diagnose missing comma in string array initialization.
13314         // Do not warn when all the elements in the initializer are concatenated
13315         // together. Do not warn for macros too.
13316         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13317           bool OnlyOneMissingComma = true;
13318           for (unsigned J = I + 1; J < NumInits; ++J) {
13319             const auto *Init = ILE->getInit(J);
13320             if (!Init)
13321               break;
13322             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13323             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13324               OnlyOneMissingComma = false;
13325               break;
13326             }
13327           }
13328 
13329           if (OnlyOneMissingComma) {
13330             SmallVector<FixItHint, 1> Hints;
13331             for (unsigned i = 0; i < NumConcat - 1; ++i)
13332               Hints.push_back(FixItHint::CreateInsertion(
13333                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13334 
13335             Diag(SL->getStrTokenLoc(1),
13336                  diag::warn_concatenated_literal_array_init)
13337                 << Hints;
13338             Diag(SL->getBeginLoc(),
13339                  diag::note_concatenated_string_literal_silence);
13340           }
13341           // In any case, stop now.
13342           break;
13343         }
13344       }
13345   }
13346 
13347 
13348   QualType type = var->getType();
13349 
13350   if (var->hasAttr<BlocksAttr>())
13351     getCurFunction()->addByrefBlockVar(var);
13352 
13353   Expr *Init = var->getInit();
13354   bool GlobalStorage = var->hasGlobalStorage();
13355   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13356   QualType baseType = Context.getBaseElementType(type);
13357   bool HasConstInit = true;
13358 
13359   // Check whether the initializer is sufficiently constant.
13360   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13361       !Init->isValueDependent() &&
13362       (GlobalStorage || var->isConstexpr() ||
13363        var->mightBeUsableInConstantExpressions(Context))) {
13364     // If this variable might have a constant initializer or might be usable in
13365     // constant expressions, check whether or not it actually is now.  We can't
13366     // do this lazily, because the result might depend on things that change
13367     // later, such as which constexpr functions happen to be defined.
13368     SmallVector<PartialDiagnosticAt, 8> Notes;
13369     if (!getLangOpts().CPlusPlus11) {
13370       // Prior to C++11, in contexts where a constant initializer is required,
13371       // the set of valid constant initializers is described by syntactic rules
13372       // in [expr.const]p2-6.
13373       // FIXME: Stricter checking for these rules would be useful for constinit /
13374       // -Wglobal-constructors.
13375       HasConstInit = checkConstInit();
13376 
13377       // Compute and cache the constant value, and remember that we have a
13378       // constant initializer.
13379       if (HasConstInit) {
13380         (void)var->checkForConstantInitialization(Notes);
13381         Notes.clear();
13382       } else if (CacheCulprit) {
13383         Notes.emplace_back(CacheCulprit->getExprLoc(),
13384                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13385         Notes.back().second << CacheCulprit->getSourceRange();
13386       }
13387     } else {
13388       // Evaluate the initializer to see if it's a constant initializer.
13389       HasConstInit = var->checkForConstantInitialization(Notes);
13390     }
13391 
13392     if (HasConstInit) {
13393       // FIXME: Consider replacing the initializer with a ConstantExpr.
13394     } else if (var->isConstexpr()) {
13395       SourceLocation DiagLoc = var->getLocation();
13396       // If the note doesn't add any useful information other than a source
13397       // location, fold it into the primary diagnostic.
13398       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13399                                    diag::note_invalid_subexpr_in_const_expr) {
13400         DiagLoc = Notes[0].first;
13401         Notes.clear();
13402       }
13403       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13404           << var << Init->getSourceRange();
13405       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13406         Diag(Notes[I].first, Notes[I].second);
13407     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13408       auto *Attr = var->getAttr<ConstInitAttr>();
13409       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13410           << Init->getSourceRange();
13411       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13412           << Attr->getRange() << Attr->isConstinit();
13413       for (auto &it : Notes)
13414         Diag(it.first, it.second);
13415     } else if (IsGlobal &&
13416                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13417                                            var->getLocation())) {
13418       // Warn about globals which don't have a constant initializer.  Don't
13419       // warn about globals with a non-trivial destructor because we already
13420       // warned about them.
13421       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13422       if (!(RD && !RD->hasTrivialDestructor())) {
13423         // checkConstInit() here permits trivial default initialization even in
13424         // C++11 onwards, where such an initializer is not a constant initializer
13425         // but nonetheless doesn't require a global constructor.
13426         if (!checkConstInit())
13427           Diag(var->getLocation(), diag::warn_global_constructor)
13428               << Init->getSourceRange();
13429       }
13430     }
13431   }
13432 
13433   // Apply section attributes and pragmas to global variables.
13434   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13435       !inTemplateInstantiation()) {
13436     PragmaStack<StringLiteral *> *Stack = nullptr;
13437     int SectionFlags = ASTContext::PSF_Read;
13438     if (var->getType().isConstQualified()) {
13439       if (HasConstInit)
13440         Stack = &ConstSegStack;
13441       else {
13442         Stack = &BSSSegStack;
13443         SectionFlags |= ASTContext::PSF_Write;
13444       }
13445     } else if (var->hasInit() && HasConstInit) {
13446       Stack = &DataSegStack;
13447       SectionFlags |= ASTContext::PSF_Write;
13448     } else {
13449       Stack = &BSSSegStack;
13450       SectionFlags |= ASTContext::PSF_Write;
13451     }
13452     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13453       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13454         SectionFlags |= ASTContext::PSF_Implicit;
13455       UnifySection(SA->getName(), SectionFlags, var);
13456     } else if (Stack->CurrentValue) {
13457       SectionFlags |= ASTContext::PSF_Implicit;
13458       auto SectionName = Stack->CurrentValue->getString();
13459       var->addAttr(SectionAttr::CreateImplicit(
13460           Context, SectionName, Stack->CurrentPragmaLocation,
13461           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13462       if (UnifySection(SectionName, SectionFlags, var))
13463         var->dropAttr<SectionAttr>();
13464     }
13465 
13466     // Apply the init_seg attribute if this has an initializer.  If the
13467     // initializer turns out to not be dynamic, we'll end up ignoring this
13468     // attribute.
13469     if (CurInitSeg && var->getInit())
13470       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13471                                                CurInitSegLoc,
13472                                                AttributeCommonInfo::AS_Pragma));
13473   }
13474 
13475   // All the following checks are C++ only.
13476   if (!getLangOpts().CPlusPlus) {
13477     // If this variable must be emitted, add it as an initializer for the
13478     // current module.
13479     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13480       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13481     return;
13482   }
13483 
13484   // Require the destructor.
13485   if (!type->isDependentType())
13486     if (const RecordType *recordType = baseType->getAs<RecordType>())
13487       FinalizeVarWithDestructor(var, recordType);
13488 
13489   // If this variable must be emitted, add it as an initializer for the current
13490   // module.
13491   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13492     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13493 
13494   // Build the bindings if this is a structured binding declaration.
13495   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13496     CheckCompleteDecompositionDeclaration(DD);
13497 }
13498 
13499 /// Check if VD needs to be dllexport/dllimport due to being in a
13500 /// dllexport/import function.
13501 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13502   assert(VD->isStaticLocal());
13503 
13504   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13505 
13506   // Find outermost function when VD is in lambda function.
13507   while (FD && !getDLLAttr(FD) &&
13508          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13509          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13510     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13511   }
13512 
13513   if (!FD)
13514     return;
13515 
13516   // Static locals inherit dll attributes from their function.
13517   if (Attr *A = getDLLAttr(FD)) {
13518     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13519     NewAttr->setInherited(true);
13520     VD->addAttr(NewAttr);
13521   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13522     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13523     NewAttr->setInherited(true);
13524     VD->addAttr(NewAttr);
13525 
13526     // Export this function to enforce exporting this static variable even
13527     // if it is not used in this compilation unit.
13528     if (!FD->hasAttr<DLLExportAttr>())
13529       FD->addAttr(NewAttr);
13530 
13531   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13532     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13533     NewAttr->setInherited(true);
13534     VD->addAttr(NewAttr);
13535   }
13536 }
13537 
13538 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13539 /// any semantic actions necessary after any initializer has been attached.
13540 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13541   // Note that we are no longer parsing the initializer for this declaration.
13542   ParsingInitForAutoVars.erase(ThisDecl);
13543 
13544   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13545   if (!VD)
13546     return;
13547 
13548   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13549   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13550       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13551     if (PragmaClangBSSSection.Valid)
13552       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13553           Context, PragmaClangBSSSection.SectionName,
13554           PragmaClangBSSSection.PragmaLocation,
13555           AttributeCommonInfo::AS_Pragma));
13556     if (PragmaClangDataSection.Valid)
13557       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13558           Context, PragmaClangDataSection.SectionName,
13559           PragmaClangDataSection.PragmaLocation,
13560           AttributeCommonInfo::AS_Pragma));
13561     if (PragmaClangRodataSection.Valid)
13562       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13563           Context, PragmaClangRodataSection.SectionName,
13564           PragmaClangRodataSection.PragmaLocation,
13565           AttributeCommonInfo::AS_Pragma));
13566     if (PragmaClangRelroSection.Valid)
13567       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13568           Context, PragmaClangRelroSection.SectionName,
13569           PragmaClangRelroSection.PragmaLocation,
13570           AttributeCommonInfo::AS_Pragma));
13571   }
13572 
13573   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13574     for (auto *BD : DD->bindings()) {
13575       FinalizeDeclaration(BD);
13576     }
13577   }
13578 
13579   checkAttributesAfterMerging(*this, *VD);
13580 
13581   // Perform TLS alignment check here after attributes attached to the variable
13582   // which may affect the alignment have been processed. Only perform the check
13583   // if the target has a maximum TLS alignment (zero means no constraints).
13584   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13585     // Protect the check so that it's not performed on dependent types and
13586     // dependent alignments (we can't determine the alignment in that case).
13587     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13588       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13589       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13590         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13591           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13592           << (unsigned)MaxAlignChars.getQuantity();
13593       }
13594     }
13595   }
13596 
13597   if (VD->isStaticLocal())
13598     CheckStaticLocalForDllExport(VD);
13599 
13600   // Perform check for initializers of device-side global variables.
13601   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13602   // 7.5). We must also apply the same checks to all __shared__
13603   // variables whether they are local or not. CUDA also allows
13604   // constant initializers for __constant__ and __device__ variables.
13605   if (getLangOpts().CUDA)
13606     checkAllowedCUDAInitializer(VD);
13607 
13608   // Grab the dllimport or dllexport attribute off of the VarDecl.
13609   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13610 
13611   // Imported static data members cannot be defined out-of-line.
13612   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13613     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13614         VD->isThisDeclarationADefinition()) {
13615       // We allow definitions of dllimport class template static data members
13616       // with a warning.
13617       CXXRecordDecl *Context =
13618         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13619       bool IsClassTemplateMember =
13620           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13621           Context->getDescribedClassTemplate();
13622 
13623       Diag(VD->getLocation(),
13624            IsClassTemplateMember
13625                ? diag::warn_attribute_dllimport_static_field_definition
13626                : diag::err_attribute_dllimport_static_field_definition);
13627       Diag(IA->getLocation(), diag::note_attribute);
13628       if (!IsClassTemplateMember)
13629         VD->setInvalidDecl();
13630     }
13631   }
13632 
13633   // dllimport/dllexport variables cannot be thread local, their TLS index
13634   // isn't exported with the variable.
13635   if (DLLAttr && VD->getTLSKind()) {
13636     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13637     if (F && getDLLAttr(F)) {
13638       assert(VD->isStaticLocal());
13639       // But if this is a static local in a dlimport/dllexport function, the
13640       // function will never be inlined, which means the var would never be
13641       // imported, so having it marked import/export is safe.
13642     } else {
13643       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13644                                                                     << DLLAttr;
13645       VD->setInvalidDecl();
13646     }
13647   }
13648 
13649   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13650     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13651       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13652           << Attr;
13653       VD->dropAttr<UsedAttr>();
13654     }
13655   }
13656   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13657     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13658       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13659           << Attr;
13660       VD->dropAttr<RetainAttr>();
13661     }
13662   }
13663 
13664   const DeclContext *DC = VD->getDeclContext();
13665   // If there's a #pragma GCC visibility in scope, and this isn't a class
13666   // member, set the visibility of this variable.
13667   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13668     AddPushedVisibilityAttribute(VD);
13669 
13670   // FIXME: Warn on unused var template partial specializations.
13671   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13672     MarkUnusedFileScopedDecl(VD);
13673 
13674   // Now we have parsed the initializer and can update the table of magic
13675   // tag values.
13676   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13677       !VD->getType()->isIntegralOrEnumerationType())
13678     return;
13679 
13680   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13681     const Expr *MagicValueExpr = VD->getInit();
13682     if (!MagicValueExpr) {
13683       continue;
13684     }
13685     Optional<llvm::APSInt> MagicValueInt;
13686     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13687       Diag(I->getRange().getBegin(),
13688            diag::err_type_tag_for_datatype_not_ice)
13689         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13690       continue;
13691     }
13692     if (MagicValueInt->getActiveBits() > 64) {
13693       Diag(I->getRange().getBegin(),
13694            diag::err_type_tag_for_datatype_too_large)
13695         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13696       continue;
13697     }
13698     uint64_t MagicValue = MagicValueInt->getZExtValue();
13699     RegisterTypeTagForDatatype(I->getArgumentKind(),
13700                                MagicValue,
13701                                I->getMatchingCType(),
13702                                I->getLayoutCompatible(),
13703                                I->getMustBeNull());
13704   }
13705 }
13706 
13707 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13708   auto *VD = dyn_cast<VarDecl>(DD);
13709   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13710 }
13711 
13712 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13713                                                    ArrayRef<Decl *> Group) {
13714   SmallVector<Decl*, 8> Decls;
13715 
13716   if (DS.isTypeSpecOwned())
13717     Decls.push_back(DS.getRepAsDecl());
13718 
13719   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13720   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13721   bool DiagnosedMultipleDecomps = false;
13722   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13723   bool DiagnosedNonDeducedAuto = false;
13724 
13725   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13726     if (Decl *D = Group[i]) {
13727       // For declarators, there are some additional syntactic-ish checks we need
13728       // to perform.
13729       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13730         if (!FirstDeclaratorInGroup)
13731           FirstDeclaratorInGroup = DD;
13732         if (!FirstDecompDeclaratorInGroup)
13733           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13734         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13735             !hasDeducedAuto(DD))
13736           FirstNonDeducedAutoInGroup = DD;
13737 
13738         if (FirstDeclaratorInGroup != DD) {
13739           // A decomposition declaration cannot be combined with any other
13740           // declaration in the same group.
13741           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13742             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13743                  diag::err_decomp_decl_not_alone)
13744                 << FirstDeclaratorInGroup->getSourceRange()
13745                 << DD->getSourceRange();
13746             DiagnosedMultipleDecomps = true;
13747           }
13748 
13749           // A declarator that uses 'auto' in any way other than to declare a
13750           // variable with a deduced type cannot be combined with any other
13751           // declarator in the same group.
13752           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13753             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13754                  diag::err_auto_non_deduced_not_alone)
13755                 << FirstNonDeducedAutoInGroup->getType()
13756                        ->hasAutoForTrailingReturnType()
13757                 << FirstDeclaratorInGroup->getSourceRange()
13758                 << DD->getSourceRange();
13759             DiagnosedNonDeducedAuto = true;
13760           }
13761         }
13762       }
13763 
13764       Decls.push_back(D);
13765     }
13766   }
13767 
13768   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13769     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13770       handleTagNumbering(Tag, S);
13771       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13772           getLangOpts().CPlusPlus)
13773         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13774     }
13775   }
13776 
13777   return BuildDeclaratorGroup(Decls);
13778 }
13779 
13780 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13781 /// group, performing any necessary semantic checking.
13782 Sema::DeclGroupPtrTy
13783 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13784   // C++14 [dcl.spec.auto]p7: (DR1347)
13785   //   If the type that replaces the placeholder type is not the same in each
13786   //   deduction, the program is ill-formed.
13787   if (Group.size() > 1) {
13788     QualType Deduced;
13789     VarDecl *DeducedDecl = nullptr;
13790     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13791       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13792       if (!D || D->isInvalidDecl())
13793         break;
13794       DeducedType *DT = D->getType()->getContainedDeducedType();
13795       if (!DT || DT->getDeducedType().isNull())
13796         continue;
13797       if (Deduced.isNull()) {
13798         Deduced = DT->getDeducedType();
13799         DeducedDecl = D;
13800       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13801         auto *AT = dyn_cast<AutoType>(DT);
13802         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13803                         diag::err_auto_different_deductions)
13804                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13805                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13806                    << D->getDeclName();
13807         if (DeducedDecl->hasInit())
13808           Dia << DeducedDecl->getInit()->getSourceRange();
13809         if (D->getInit())
13810           Dia << D->getInit()->getSourceRange();
13811         D->setInvalidDecl();
13812         break;
13813       }
13814     }
13815   }
13816 
13817   ActOnDocumentableDecls(Group);
13818 
13819   return DeclGroupPtrTy::make(
13820       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13821 }
13822 
13823 void Sema::ActOnDocumentableDecl(Decl *D) {
13824   ActOnDocumentableDecls(D);
13825 }
13826 
13827 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13828   // Don't parse the comment if Doxygen diagnostics are ignored.
13829   if (Group.empty() || !Group[0])
13830     return;
13831 
13832   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13833                       Group[0]->getLocation()) &&
13834       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13835                       Group[0]->getLocation()))
13836     return;
13837 
13838   if (Group.size() >= 2) {
13839     // This is a decl group.  Normally it will contain only declarations
13840     // produced from declarator list.  But in case we have any definitions or
13841     // additional declaration references:
13842     //   'typedef struct S {} S;'
13843     //   'typedef struct S *S;'
13844     //   'struct S *pS;'
13845     // FinalizeDeclaratorGroup adds these as separate declarations.
13846     Decl *MaybeTagDecl = Group[0];
13847     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13848       Group = Group.slice(1);
13849     }
13850   }
13851 
13852   // FIMXE: We assume every Decl in the group is in the same file.
13853   // This is false when preprocessor constructs the group from decls in
13854   // different files (e. g. macros or #include).
13855   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13856 }
13857 
13858 /// Common checks for a parameter-declaration that should apply to both function
13859 /// parameters and non-type template parameters.
13860 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13861   // Check that there are no default arguments inside the type of this
13862   // parameter.
13863   if (getLangOpts().CPlusPlus)
13864     CheckExtraCXXDefaultArguments(D);
13865 
13866   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13867   if (D.getCXXScopeSpec().isSet()) {
13868     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13869       << D.getCXXScopeSpec().getRange();
13870   }
13871 
13872   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13873   // simple identifier except [...irrelevant cases...].
13874   switch (D.getName().getKind()) {
13875   case UnqualifiedIdKind::IK_Identifier:
13876     break;
13877 
13878   case UnqualifiedIdKind::IK_OperatorFunctionId:
13879   case UnqualifiedIdKind::IK_ConversionFunctionId:
13880   case UnqualifiedIdKind::IK_LiteralOperatorId:
13881   case UnqualifiedIdKind::IK_ConstructorName:
13882   case UnqualifiedIdKind::IK_DestructorName:
13883   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13884   case UnqualifiedIdKind::IK_DeductionGuideName:
13885     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13886       << GetNameForDeclarator(D).getName();
13887     break;
13888 
13889   case UnqualifiedIdKind::IK_TemplateId:
13890   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13891     // GetNameForDeclarator would not produce a useful name in this case.
13892     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13893     break;
13894   }
13895 }
13896 
13897 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13898 /// to introduce parameters into function prototype scope.
13899 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13900   const DeclSpec &DS = D.getDeclSpec();
13901 
13902   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13903 
13904   // C++03 [dcl.stc]p2 also permits 'auto'.
13905   StorageClass SC = SC_None;
13906   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13907     SC = SC_Register;
13908     // In C++11, the 'register' storage class specifier is deprecated.
13909     // In C++17, it is not allowed, but we tolerate it as an extension.
13910     if (getLangOpts().CPlusPlus11) {
13911       Diag(DS.getStorageClassSpecLoc(),
13912            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13913                                      : diag::warn_deprecated_register)
13914         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13915     }
13916   } else if (getLangOpts().CPlusPlus &&
13917              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13918     SC = SC_Auto;
13919   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13920     Diag(DS.getStorageClassSpecLoc(),
13921          diag::err_invalid_storage_class_in_func_decl);
13922     D.getMutableDeclSpec().ClearStorageClassSpecs();
13923   }
13924 
13925   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13926     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13927       << DeclSpec::getSpecifierName(TSCS);
13928   if (DS.isInlineSpecified())
13929     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13930         << getLangOpts().CPlusPlus17;
13931   if (DS.hasConstexprSpecifier())
13932     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13933         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13934 
13935   DiagnoseFunctionSpecifiers(DS);
13936 
13937   CheckFunctionOrTemplateParamDeclarator(S, D);
13938 
13939   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13940   QualType parmDeclType = TInfo->getType();
13941 
13942   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13943   IdentifierInfo *II = D.getIdentifier();
13944   if (II) {
13945     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13946                    ForVisibleRedeclaration);
13947     LookupName(R, S);
13948     if (R.isSingleResult()) {
13949       NamedDecl *PrevDecl = R.getFoundDecl();
13950       if (PrevDecl->isTemplateParameter()) {
13951         // Maybe we will complain about the shadowed template parameter.
13952         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13953         // Just pretend that we didn't see the previous declaration.
13954         PrevDecl = nullptr;
13955       } else if (S->isDeclScope(PrevDecl)) {
13956         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13957         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13958 
13959         // Recover by removing the name
13960         II = nullptr;
13961         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13962         D.setInvalidType(true);
13963       }
13964     }
13965   }
13966 
13967   // Temporarily put parameter variables in the translation unit, not
13968   // the enclosing context.  This prevents them from accidentally
13969   // looking like class members in C++.
13970   ParmVarDecl *New =
13971       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13972                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13973 
13974   if (D.isInvalidType())
13975     New->setInvalidDecl();
13976 
13977   assert(S->isFunctionPrototypeScope());
13978   assert(S->getFunctionPrototypeDepth() >= 1);
13979   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13980                     S->getNextFunctionPrototypeIndex());
13981 
13982   // Add the parameter declaration into this scope.
13983   S->AddDecl(New);
13984   if (II)
13985     IdResolver.AddDecl(New);
13986 
13987   ProcessDeclAttributes(S, New, D);
13988 
13989   if (D.getDeclSpec().isModulePrivateSpecified())
13990     Diag(New->getLocation(), diag::err_module_private_local)
13991         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13992         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13993 
13994   if (New->hasAttr<BlocksAttr>()) {
13995     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13996   }
13997 
13998   if (getLangOpts().OpenCL)
13999     deduceOpenCLAddressSpace(New);
14000 
14001   return New;
14002 }
14003 
14004 /// Synthesizes a variable for a parameter arising from a
14005 /// typedef.
14006 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14007                                               SourceLocation Loc,
14008                                               QualType T) {
14009   /* FIXME: setting StartLoc == Loc.
14010      Would it be worth to modify callers so as to provide proper source
14011      location for the unnamed parameters, embedding the parameter's type? */
14012   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14013                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14014                                            SC_None, nullptr);
14015   Param->setImplicit();
14016   return Param;
14017 }
14018 
14019 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14020   // Don't diagnose unused-parameter errors in template instantiations; we
14021   // will already have done so in the template itself.
14022   if (inTemplateInstantiation())
14023     return;
14024 
14025   for (const ParmVarDecl *Parameter : Parameters) {
14026     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14027         !Parameter->hasAttr<UnusedAttr>()) {
14028       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14029         << Parameter->getDeclName();
14030     }
14031   }
14032 }
14033 
14034 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14035     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14036   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14037     return;
14038 
14039   // Warn if the return value is pass-by-value and larger than the specified
14040   // threshold.
14041   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14042     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14043     if (Size > LangOpts.NumLargeByValueCopy)
14044       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14045   }
14046 
14047   // Warn if any parameter is pass-by-value and larger than the specified
14048   // threshold.
14049   for (const ParmVarDecl *Parameter : Parameters) {
14050     QualType T = Parameter->getType();
14051     if (T->isDependentType() || !T.isPODType(Context))
14052       continue;
14053     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14054     if (Size > LangOpts.NumLargeByValueCopy)
14055       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14056           << Parameter << Size;
14057   }
14058 }
14059 
14060 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14061                                   SourceLocation NameLoc, IdentifierInfo *Name,
14062                                   QualType T, TypeSourceInfo *TSInfo,
14063                                   StorageClass SC) {
14064   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14065   if (getLangOpts().ObjCAutoRefCount &&
14066       T.getObjCLifetime() == Qualifiers::OCL_None &&
14067       T->isObjCLifetimeType()) {
14068 
14069     Qualifiers::ObjCLifetime lifetime;
14070 
14071     // Special cases for arrays:
14072     //   - if it's const, use __unsafe_unretained
14073     //   - otherwise, it's an error
14074     if (T->isArrayType()) {
14075       if (!T.isConstQualified()) {
14076         if (DelayedDiagnostics.shouldDelayDiagnostics())
14077           DelayedDiagnostics.add(
14078               sema::DelayedDiagnostic::makeForbiddenType(
14079               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14080         else
14081           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14082               << TSInfo->getTypeLoc().getSourceRange();
14083       }
14084       lifetime = Qualifiers::OCL_ExplicitNone;
14085     } else {
14086       lifetime = T->getObjCARCImplicitLifetime();
14087     }
14088     T = Context.getLifetimeQualifiedType(T, lifetime);
14089   }
14090 
14091   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14092                                          Context.getAdjustedParameterType(T),
14093                                          TSInfo, SC, nullptr);
14094 
14095   // Make a note if we created a new pack in the scope of a lambda, so that
14096   // we know that references to that pack must also be expanded within the
14097   // lambda scope.
14098   if (New->isParameterPack())
14099     if (auto *LSI = getEnclosingLambda())
14100       LSI->LocalPacks.push_back(New);
14101 
14102   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14103       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14104     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14105                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14106 
14107   // Parameters can not be abstract class types.
14108   // For record types, this is done by the AbstractClassUsageDiagnoser once
14109   // the class has been completely parsed.
14110   if (!CurContext->isRecord() &&
14111       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14112                              AbstractParamType))
14113     New->setInvalidDecl();
14114 
14115   // Parameter declarators cannot be interface types. All ObjC objects are
14116   // passed by reference.
14117   if (T->isObjCObjectType()) {
14118     SourceLocation TypeEndLoc =
14119         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14120     Diag(NameLoc,
14121          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14122       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14123     T = Context.getObjCObjectPointerType(T);
14124     New->setType(T);
14125   }
14126 
14127   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14128   // duration shall not be qualified by an address-space qualifier."
14129   // Since all parameters have automatic store duration, they can not have
14130   // an address space.
14131   if (T.getAddressSpace() != LangAS::Default &&
14132       // OpenCL allows function arguments declared to be an array of a type
14133       // to be qualified with an address space.
14134       !(getLangOpts().OpenCL &&
14135         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14136     Diag(NameLoc, diag::err_arg_with_address_space);
14137     New->setInvalidDecl();
14138   }
14139 
14140   // PPC MMA non-pointer types are not allowed as function argument types.
14141   if (Context.getTargetInfo().getTriple().isPPC64() &&
14142       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14143     New->setInvalidDecl();
14144   }
14145 
14146   return New;
14147 }
14148 
14149 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14150                                            SourceLocation LocAfterDecls) {
14151   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14152 
14153   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14154   // for a K&R function.
14155   if (!FTI.hasPrototype) {
14156     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14157       --i;
14158       if (FTI.Params[i].Param == nullptr) {
14159         SmallString<256> Code;
14160         llvm::raw_svector_ostream(Code)
14161             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14162         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14163             << FTI.Params[i].Ident
14164             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14165 
14166         // Implicitly declare the argument as type 'int' for lack of a better
14167         // type.
14168         AttributeFactory attrs;
14169         DeclSpec DS(attrs);
14170         const char* PrevSpec; // unused
14171         unsigned DiagID; // unused
14172         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14173                            DiagID, Context.getPrintingPolicy());
14174         // Use the identifier location for the type source range.
14175         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14176         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14177         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14178         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14179         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14180       }
14181     }
14182   }
14183 }
14184 
14185 Decl *
14186 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14187                               MultiTemplateParamsArg TemplateParameterLists,
14188                               SkipBodyInfo *SkipBody) {
14189   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14190   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14191   Scope *ParentScope = FnBodyScope->getParent();
14192 
14193   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14194   // we define a non-templated function definition, we will create a declaration
14195   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14196   // The base function declaration will have the equivalent of an `omp declare
14197   // variant` annotation which specifies the mangled definition as a
14198   // specialization function under the OpenMP context defined as part of the
14199   // `omp begin declare variant`.
14200   SmallVector<FunctionDecl *, 4> Bases;
14201   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14202     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14203         ParentScope, D, TemplateParameterLists, Bases);
14204 
14205   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14206   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14207   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14208 
14209   if (!Bases.empty())
14210     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14211 
14212   return Dcl;
14213 }
14214 
14215 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14216   Consumer.HandleInlineFunctionDefinition(D);
14217 }
14218 
14219 static bool
14220 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14221                                 const FunctionDecl *&PossiblePrototype) {
14222   // Don't warn about invalid declarations.
14223   if (FD->isInvalidDecl())
14224     return false;
14225 
14226   // Or declarations that aren't global.
14227   if (!FD->isGlobal())
14228     return false;
14229 
14230   // Don't warn about C++ member functions.
14231   if (isa<CXXMethodDecl>(FD))
14232     return false;
14233 
14234   // Don't warn about 'main'.
14235   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14236     if (IdentifierInfo *II = FD->getIdentifier())
14237       if (II->isStr("main") || II->isStr("efi_main"))
14238         return false;
14239 
14240   // Don't warn about inline functions.
14241   if (FD->isInlined())
14242     return false;
14243 
14244   // Don't warn about function templates.
14245   if (FD->getDescribedFunctionTemplate())
14246     return false;
14247 
14248   // Don't warn about function template specializations.
14249   if (FD->isFunctionTemplateSpecialization())
14250     return false;
14251 
14252   // Don't warn for OpenCL kernels.
14253   if (FD->hasAttr<OpenCLKernelAttr>())
14254     return false;
14255 
14256   // Don't warn on explicitly deleted functions.
14257   if (FD->isDeleted())
14258     return false;
14259 
14260   // Don't warn on implicitly local functions (such as having local-typed
14261   // parameters).
14262   if (!FD->isExternallyVisible())
14263     return false;
14264 
14265   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14266        Prev; Prev = Prev->getPreviousDecl()) {
14267     // Ignore any declarations that occur in function or method
14268     // scope, because they aren't visible from the header.
14269     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14270       continue;
14271 
14272     PossiblePrototype = Prev;
14273     return Prev->getType()->isFunctionNoProtoType();
14274   }
14275 
14276   return true;
14277 }
14278 
14279 void
14280 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14281                                    const FunctionDecl *EffectiveDefinition,
14282                                    SkipBodyInfo *SkipBody) {
14283   const FunctionDecl *Definition = EffectiveDefinition;
14284   if (!Definition &&
14285       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14286     return;
14287 
14288   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14289     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14290       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14291         // A merged copy of the same function, instantiated as a member of
14292         // the same class, is OK.
14293         if (declaresSameEntity(OrigFD, OrigDef) &&
14294             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14295                                cast<Decl>(FD->getLexicalDeclContext())))
14296           return;
14297       }
14298     }
14299   }
14300 
14301   if (canRedefineFunction(Definition, getLangOpts()))
14302     return;
14303 
14304   // Don't emit an error when this is redefinition of a typo-corrected
14305   // definition.
14306   if (TypoCorrectedFunctionDefinitions.count(Definition))
14307     return;
14308 
14309   // If we don't have a visible definition of the function, and it's inline or
14310   // a template, skip the new definition.
14311   if (SkipBody && !hasVisibleDefinition(Definition) &&
14312       (Definition->getFormalLinkage() == InternalLinkage ||
14313        Definition->isInlined() ||
14314        Definition->getDescribedFunctionTemplate() ||
14315        Definition->getNumTemplateParameterLists())) {
14316     SkipBody->ShouldSkip = true;
14317     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14318     if (auto *TD = Definition->getDescribedFunctionTemplate())
14319       makeMergedDefinitionVisible(TD);
14320     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14321     return;
14322   }
14323 
14324   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14325       Definition->getStorageClass() == SC_Extern)
14326     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14327         << FD << getLangOpts().CPlusPlus;
14328   else
14329     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14330 
14331   Diag(Definition->getLocation(), diag::note_previous_definition);
14332   FD->setInvalidDecl();
14333 }
14334 
14335 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14336                                    Sema &S) {
14337   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14338 
14339   LambdaScopeInfo *LSI = S.PushLambdaScope();
14340   LSI->CallOperator = CallOperator;
14341   LSI->Lambda = LambdaClass;
14342   LSI->ReturnType = CallOperator->getReturnType();
14343   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14344 
14345   if (LCD == LCD_None)
14346     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14347   else if (LCD == LCD_ByCopy)
14348     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14349   else if (LCD == LCD_ByRef)
14350     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14351   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14352 
14353   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14354   LSI->Mutable = !CallOperator->isConst();
14355 
14356   // Add the captures to the LSI so they can be noted as already
14357   // captured within tryCaptureVar.
14358   auto I = LambdaClass->field_begin();
14359   for (const auto &C : LambdaClass->captures()) {
14360     if (C.capturesVariable()) {
14361       VarDecl *VD = C.getCapturedVar();
14362       if (VD->isInitCapture())
14363         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14364       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14365       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14366           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14367           /*EllipsisLoc*/C.isPackExpansion()
14368                          ? C.getEllipsisLoc() : SourceLocation(),
14369           I->getType(), /*Invalid*/false);
14370 
14371     } else if (C.capturesThis()) {
14372       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14373                           C.getCaptureKind() == LCK_StarThis);
14374     } else {
14375       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14376                              I->getType());
14377     }
14378     ++I;
14379   }
14380 }
14381 
14382 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14383                                     SkipBodyInfo *SkipBody) {
14384   if (!D) {
14385     // Parsing the function declaration failed in some way. Push on a fake scope
14386     // anyway so we can try to parse the function body.
14387     PushFunctionScope();
14388     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14389     return D;
14390   }
14391 
14392   FunctionDecl *FD = nullptr;
14393 
14394   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14395     FD = FunTmpl->getTemplatedDecl();
14396   else
14397     FD = cast<FunctionDecl>(D);
14398 
14399   // Do not push if it is a lambda because one is already pushed when building
14400   // the lambda in ActOnStartOfLambdaDefinition().
14401   if (!isLambdaCallOperator(FD))
14402     PushExpressionEvaluationContext(
14403         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14404                           : ExprEvalContexts.back().Context);
14405 
14406   // Check for defining attributes before the check for redefinition.
14407   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14408     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14409     FD->dropAttr<AliasAttr>();
14410     FD->setInvalidDecl();
14411   }
14412   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14413     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14414     FD->dropAttr<IFuncAttr>();
14415     FD->setInvalidDecl();
14416   }
14417 
14418   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14419     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14420         Ctor->isDefaultConstructor() &&
14421         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14422       // If this is an MS ABI dllexport default constructor, instantiate any
14423       // default arguments.
14424       InstantiateDefaultCtorDefaultArgs(Ctor);
14425     }
14426   }
14427 
14428   // See if this is a redefinition. If 'will have body' (or similar) is already
14429   // set, then these checks were already performed when it was set.
14430   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14431       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14432     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14433 
14434     // If we're skipping the body, we're done. Don't enter the scope.
14435     if (SkipBody && SkipBody->ShouldSkip)
14436       return D;
14437   }
14438 
14439   // Mark this function as "will have a body eventually".  This lets users to
14440   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14441   // this function.
14442   FD->setWillHaveBody();
14443 
14444   // If we are instantiating a generic lambda call operator, push
14445   // a LambdaScopeInfo onto the function stack.  But use the information
14446   // that's already been calculated (ActOnLambdaExpr) to prime the current
14447   // LambdaScopeInfo.
14448   // When the template operator is being specialized, the LambdaScopeInfo,
14449   // has to be properly restored so that tryCaptureVariable doesn't try
14450   // and capture any new variables. In addition when calculating potential
14451   // captures during transformation of nested lambdas, it is necessary to
14452   // have the LSI properly restored.
14453   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14454     assert(inTemplateInstantiation() &&
14455            "There should be an active template instantiation on the stack "
14456            "when instantiating a generic lambda!");
14457     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14458   } else {
14459     // Enter a new function scope
14460     PushFunctionScope();
14461   }
14462 
14463   // Builtin functions cannot be defined.
14464   if (unsigned BuiltinID = FD->getBuiltinID()) {
14465     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14466         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14467       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14468       FD->setInvalidDecl();
14469     }
14470   }
14471 
14472   // The return type of a function definition must be complete
14473   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14474   QualType ResultType = FD->getReturnType();
14475   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14476       !FD->isInvalidDecl() &&
14477       RequireCompleteType(FD->getLocation(), ResultType,
14478                           diag::err_func_def_incomplete_result))
14479     FD->setInvalidDecl();
14480 
14481   if (FnBodyScope)
14482     PushDeclContext(FnBodyScope, FD);
14483 
14484   // Check the validity of our function parameters
14485   CheckParmsForFunctionDef(FD->parameters(),
14486                            /*CheckParameterNames=*/true);
14487 
14488   // Add non-parameter declarations already in the function to the current
14489   // scope.
14490   if (FnBodyScope) {
14491     for (Decl *NPD : FD->decls()) {
14492       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14493       if (!NonParmDecl)
14494         continue;
14495       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14496              "parameters should not be in newly created FD yet");
14497 
14498       // If the decl has a name, make it accessible in the current scope.
14499       if (NonParmDecl->getDeclName())
14500         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14501 
14502       // Similarly, dive into enums and fish their constants out, making them
14503       // accessible in this scope.
14504       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14505         for (auto *EI : ED->enumerators())
14506           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14507       }
14508     }
14509   }
14510 
14511   // Introduce our parameters into the function scope
14512   for (auto Param : FD->parameters()) {
14513     Param->setOwningFunction(FD);
14514 
14515     // If this has an identifier, add it to the scope stack.
14516     if (Param->getIdentifier() && FnBodyScope) {
14517       CheckShadow(FnBodyScope, Param);
14518 
14519       PushOnScopeChains(Param, FnBodyScope);
14520     }
14521   }
14522 
14523   // Ensure that the function's exception specification is instantiated.
14524   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14525     ResolveExceptionSpec(D->getLocation(), FPT);
14526 
14527   // dllimport cannot be applied to non-inline function definitions.
14528   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14529       !FD->isTemplateInstantiation()) {
14530     assert(!FD->hasAttr<DLLExportAttr>());
14531     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14532     FD->setInvalidDecl();
14533     return D;
14534   }
14535   // We want to attach documentation to original Decl (which might be
14536   // a function template).
14537   ActOnDocumentableDecl(D);
14538   if (getCurLexicalContext()->isObjCContainer() &&
14539       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14540       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14541     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14542 
14543   return D;
14544 }
14545 
14546 /// Given the set of return statements within a function body,
14547 /// compute the variables that are subject to the named return value
14548 /// optimization.
14549 ///
14550 /// Each of the variables that is subject to the named return value
14551 /// optimization will be marked as NRVO variables in the AST, and any
14552 /// return statement that has a marked NRVO variable as its NRVO candidate can
14553 /// use the named return value optimization.
14554 ///
14555 /// This function applies a very simplistic algorithm for NRVO: if every return
14556 /// statement in the scope of a variable has the same NRVO candidate, that
14557 /// candidate is an NRVO variable.
14558 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14559   ReturnStmt **Returns = Scope->Returns.data();
14560 
14561   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14562     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14563       if (!NRVOCandidate->isNRVOVariable())
14564         Returns[I]->setNRVOCandidate(nullptr);
14565     }
14566   }
14567 }
14568 
14569 bool Sema::canDelayFunctionBody(const Declarator &D) {
14570   // We can't delay parsing the body of a constexpr function template (yet).
14571   if (D.getDeclSpec().hasConstexprSpecifier())
14572     return false;
14573 
14574   // We can't delay parsing the body of a function template with a deduced
14575   // return type (yet).
14576   if (D.getDeclSpec().hasAutoTypeSpec()) {
14577     // If the placeholder introduces a non-deduced trailing return type,
14578     // we can still delay parsing it.
14579     if (D.getNumTypeObjects()) {
14580       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14581       if (Outer.Kind == DeclaratorChunk::Function &&
14582           Outer.Fun.hasTrailingReturnType()) {
14583         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14584         return Ty.isNull() || !Ty->isUndeducedType();
14585       }
14586     }
14587     return false;
14588   }
14589 
14590   return true;
14591 }
14592 
14593 bool Sema::canSkipFunctionBody(Decl *D) {
14594   // We cannot skip the body of a function (or function template) which is
14595   // constexpr, since we may need to evaluate its body in order to parse the
14596   // rest of the file.
14597   // We cannot skip the body of a function with an undeduced return type,
14598   // because any callers of that function need to know the type.
14599   if (const FunctionDecl *FD = D->getAsFunction()) {
14600     if (FD->isConstexpr())
14601       return false;
14602     // We can't simply call Type::isUndeducedType here, because inside template
14603     // auto can be deduced to a dependent type, which is not considered
14604     // "undeduced".
14605     if (FD->getReturnType()->getContainedDeducedType())
14606       return false;
14607   }
14608   return Consumer.shouldSkipFunctionBody(D);
14609 }
14610 
14611 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14612   if (!Decl)
14613     return nullptr;
14614   if (FunctionDecl *FD = Decl->getAsFunction())
14615     FD->setHasSkippedBody();
14616   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14617     MD->setHasSkippedBody();
14618   return Decl;
14619 }
14620 
14621 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14622   return ActOnFinishFunctionBody(D, BodyArg, false);
14623 }
14624 
14625 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14626 /// body.
14627 class ExitFunctionBodyRAII {
14628 public:
14629   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14630   ~ExitFunctionBodyRAII() {
14631     if (!IsLambda)
14632       S.PopExpressionEvaluationContext();
14633   }
14634 
14635 private:
14636   Sema &S;
14637   bool IsLambda = false;
14638 };
14639 
14640 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14641   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14642 
14643   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14644     if (EscapeInfo.count(BD))
14645       return EscapeInfo[BD];
14646 
14647     bool R = false;
14648     const BlockDecl *CurBD = BD;
14649 
14650     do {
14651       R = !CurBD->doesNotEscape();
14652       if (R)
14653         break;
14654       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14655     } while (CurBD);
14656 
14657     return EscapeInfo[BD] = R;
14658   };
14659 
14660   // If the location where 'self' is implicitly retained is inside a escaping
14661   // block, emit a diagnostic.
14662   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14663        S.ImplicitlyRetainedSelfLocs)
14664     if (IsOrNestedInEscapingBlock(P.second))
14665       S.Diag(P.first, diag::warn_implicitly_retains_self)
14666           << FixItHint::CreateInsertion(P.first, "self->");
14667 }
14668 
14669 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14670                                     bool IsInstantiation) {
14671   FunctionScopeInfo *FSI = getCurFunction();
14672   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14673 
14674   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14675     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14676 
14677   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14678   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14679 
14680   if (getLangOpts().Coroutines && FSI->isCoroutine())
14681     CheckCompletedCoroutineBody(FD, Body);
14682 
14683   {
14684     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14685     // one is already popped when finishing the lambda in BuildLambdaExpr().
14686     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14687     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14688 
14689     if (FD) {
14690       FD->setBody(Body);
14691       FD->setWillHaveBody(false);
14692 
14693       if (getLangOpts().CPlusPlus14) {
14694         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14695             FD->getReturnType()->isUndeducedType()) {
14696           // For a function with a deduced result type to return void,
14697           // the result type as written must be 'auto' or 'decltype(auto)',
14698           // possibly cv-qualified or constrained, but not ref-qualified.
14699           if (!FD->getReturnType()->getAs<AutoType>()) {
14700             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14701                 << FD->getReturnType();
14702             FD->setInvalidDecl();
14703           } else {
14704             // Falling off the end of the function is the same as 'return;'.
14705             Expr *Dummy = nullptr;
14706             if (DeduceFunctionTypeFromReturnExpr(
14707                     FD, dcl->getLocation(), Dummy,
14708                     FD->getReturnType()->getAs<AutoType>()))
14709               FD->setInvalidDecl();
14710           }
14711         }
14712       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14713         // In C++11, we don't use 'auto' deduction rules for lambda call
14714         // operators because we don't support return type deduction.
14715         auto *LSI = getCurLambda();
14716         if (LSI->HasImplicitReturnType) {
14717           deduceClosureReturnType(*LSI);
14718 
14719           // C++11 [expr.prim.lambda]p4:
14720           //   [...] if there are no return statements in the compound-statement
14721           //   [the deduced type is] the type void
14722           QualType RetType =
14723               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14724 
14725           // Update the return type to the deduced type.
14726           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14727           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14728                                               Proto->getExtProtoInfo()));
14729         }
14730       }
14731 
14732       // If the function implicitly returns zero (like 'main') or is naked,
14733       // don't complain about missing return statements.
14734       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14735         WP.disableCheckFallThrough();
14736 
14737       // MSVC permits the use of pure specifier (=0) on function definition,
14738       // defined at class scope, warn about this non-standard construct.
14739       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14740         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14741 
14742       if (!FD->isInvalidDecl()) {
14743         // Don't diagnose unused parameters of defaulted, deleted or naked
14744         // functions.
14745         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14746             !FD->hasAttr<NakedAttr>())
14747           DiagnoseUnusedParameters(FD->parameters());
14748         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14749                                                FD->getReturnType(), FD);
14750 
14751         // If this is a structor, we need a vtable.
14752         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14753           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14754         else if (CXXDestructorDecl *Destructor =
14755                      dyn_cast<CXXDestructorDecl>(FD))
14756           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14757 
14758         // Try to apply the named return value optimization. We have to check
14759         // if we can do this here because lambdas keep return statements around
14760         // to deduce an implicit return type.
14761         if (FD->getReturnType()->isRecordType() &&
14762             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14763           computeNRVO(Body, FSI);
14764       }
14765 
14766       // GNU warning -Wmissing-prototypes:
14767       //   Warn if a global function is defined without a previous
14768       //   prototype declaration. This warning is issued even if the
14769       //   definition itself provides a prototype. The aim is to detect
14770       //   global functions that fail to be declared in header files.
14771       const FunctionDecl *PossiblePrototype = nullptr;
14772       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14773         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14774 
14775         if (PossiblePrototype) {
14776           // We found a declaration that is not a prototype,
14777           // but that could be a zero-parameter prototype
14778           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14779             TypeLoc TL = TI->getTypeLoc();
14780             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14781               Diag(PossiblePrototype->getLocation(),
14782                    diag::note_declaration_not_a_prototype)
14783                   << (FD->getNumParams() != 0)
14784                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14785                                                     FTL.getRParenLoc(), "void")
14786                                               : FixItHint{});
14787           }
14788         } else {
14789           // Returns true if the token beginning at this Loc is `const`.
14790           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14791                                   const LangOptions &LangOpts) {
14792             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14793             if (LocInfo.first.isInvalid())
14794               return false;
14795 
14796             bool Invalid = false;
14797             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14798             if (Invalid)
14799               return false;
14800 
14801             if (LocInfo.second > Buffer.size())
14802               return false;
14803 
14804             const char *LexStart = Buffer.data() + LocInfo.second;
14805             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14806 
14807             return StartTok.consume_front("const") &&
14808                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14809                     StartTok.startswith("/*") || StartTok.startswith("//"));
14810           };
14811 
14812           auto findBeginLoc = [&]() {
14813             // If the return type has `const` qualifier, we want to insert
14814             // `static` before `const` (and not before the typename).
14815             if ((FD->getReturnType()->isAnyPointerType() &&
14816                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14817                 FD->getReturnType().isConstQualified()) {
14818               // But only do this if we can determine where the `const` is.
14819 
14820               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14821                                getLangOpts()))
14822 
14823                 return FD->getBeginLoc();
14824             }
14825             return FD->getTypeSpecStartLoc();
14826           };
14827           Diag(FD->getTypeSpecStartLoc(),
14828                diag::note_static_for_internal_linkage)
14829               << /* function */ 1
14830               << (FD->getStorageClass() == SC_None
14831                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14832                       : FixItHint{});
14833         }
14834 
14835         // GNU warning -Wstrict-prototypes
14836         //   Warn if K&R function is defined without a previous declaration.
14837         //   This warning is issued only if the definition itself does not
14838         //   provide a prototype. Only K&R definitions do not provide a
14839         //   prototype.
14840         if (!FD->hasWrittenPrototype()) {
14841           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14842           TypeLoc TL = TI->getTypeLoc();
14843           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14844           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14845         }
14846       }
14847 
14848       // Warn on CPUDispatch with an actual body.
14849       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14850         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14851           if (!CmpndBody->body_empty())
14852             Diag(CmpndBody->body_front()->getBeginLoc(),
14853                  diag::warn_dispatch_body_ignored);
14854 
14855       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14856         const CXXMethodDecl *KeyFunction;
14857         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14858             MD->isVirtual() &&
14859             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14860             MD == KeyFunction->getCanonicalDecl()) {
14861           // Update the key-function state if necessary for this ABI.
14862           if (FD->isInlined() &&
14863               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14864             Context.setNonKeyFunction(MD);
14865 
14866             // If the newly-chosen key function is already defined, then we
14867             // need to mark the vtable as used retroactively.
14868             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14869             const FunctionDecl *Definition;
14870             if (KeyFunction && KeyFunction->isDefined(Definition))
14871               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14872           } else {
14873             // We just defined they key function; mark the vtable as used.
14874             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14875           }
14876         }
14877       }
14878 
14879       assert(
14880           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14881           "Function parsing confused");
14882     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14883       assert(MD == getCurMethodDecl() && "Method parsing confused");
14884       MD->setBody(Body);
14885       if (!MD->isInvalidDecl()) {
14886         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14887                                                MD->getReturnType(), MD);
14888 
14889         if (Body)
14890           computeNRVO(Body, FSI);
14891       }
14892       if (FSI->ObjCShouldCallSuper) {
14893         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14894             << MD->getSelector().getAsString();
14895         FSI->ObjCShouldCallSuper = false;
14896       }
14897       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14898         const ObjCMethodDecl *InitMethod = nullptr;
14899         bool isDesignated =
14900             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14901         assert(isDesignated && InitMethod);
14902         (void)isDesignated;
14903 
14904         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14905           auto IFace = MD->getClassInterface();
14906           if (!IFace)
14907             return false;
14908           auto SuperD = IFace->getSuperClass();
14909           if (!SuperD)
14910             return false;
14911           return SuperD->getIdentifier() ==
14912                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14913         };
14914         // Don't issue this warning for unavailable inits or direct subclasses
14915         // of NSObject.
14916         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14917           Diag(MD->getLocation(),
14918                diag::warn_objc_designated_init_missing_super_call);
14919           Diag(InitMethod->getLocation(),
14920                diag::note_objc_designated_init_marked_here);
14921         }
14922         FSI->ObjCWarnForNoDesignatedInitChain = false;
14923       }
14924       if (FSI->ObjCWarnForNoInitDelegation) {
14925         // Don't issue this warning for unavaialable inits.
14926         if (!MD->isUnavailable())
14927           Diag(MD->getLocation(),
14928                diag::warn_objc_secondary_init_missing_init_call);
14929         FSI->ObjCWarnForNoInitDelegation = false;
14930       }
14931 
14932       diagnoseImplicitlyRetainedSelf(*this);
14933     } else {
14934       // Parsing the function declaration failed in some way. Pop the fake scope
14935       // we pushed on.
14936       PopFunctionScopeInfo(ActivePolicy, dcl);
14937       return nullptr;
14938     }
14939 
14940     if (Body && FSI->HasPotentialAvailabilityViolations)
14941       DiagnoseUnguardedAvailabilityViolations(dcl);
14942 
14943     assert(!FSI->ObjCShouldCallSuper &&
14944            "This should only be set for ObjC methods, which should have been "
14945            "handled in the block above.");
14946 
14947     // Verify and clean out per-function state.
14948     if (Body && (!FD || !FD->isDefaulted())) {
14949       // C++ constructors that have function-try-blocks can't have return
14950       // statements in the handlers of that block. (C++ [except.handle]p14)
14951       // Verify this.
14952       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14953         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14954 
14955       // Verify that gotos and switch cases don't jump into scopes illegally.
14956       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14957         DiagnoseInvalidJumps(Body);
14958 
14959       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14960         if (!Destructor->getParent()->isDependentType())
14961           CheckDestructor(Destructor);
14962 
14963         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14964                                                Destructor->getParent());
14965       }
14966 
14967       // If any errors have occurred, clear out any temporaries that may have
14968       // been leftover. This ensures that these temporaries won't be picked up
14969       // for deletion in some later function.
14970       if (hasUncompilableErrorOccurred() ||
14971           getDiagnostics().getSuppressAllDiagnostics()) {
14972         DiscardCleanupsInEvaluationContext();
14973       }
14974       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14975         // Since the body is valid, issue any analysis-based warnings that are
14976         // enabled.
14977         ActivePolicy = &WP;
14978       }
14979 
14980       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14981           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14982         FD->setInvalidDecl();
14983 
14984       if (FD && FD->hasAttr<NakedAttr>()) {
14985         for (const Stmt *S : Body->children()) {
14986           // Allow local register variables without initializer as they don't
14987           // require prologue.
14988           bool RegisterVariables = false;
14989           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14990             for (const auto *Decl : DS->decls()) {
14991               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14992                 RegisterVariables =
14993                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14994                 if (!RegisterVariables)
14995                   break;
14996               }
14997             }
14998           }
14999           if (RegisterVariables)
15000             continue;
15001           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15002             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15003             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15004             FD->setInvalidDecl();
15005             break;
15006           }
15007         }
15008       }
15009 
15010       assert(ExprCleanupObjects.size() ==
15011                  ExprEvalContexts.back().NumCleanupObjects &&
15012              "Leftover temporaries in function");
15013       assert(!Cleanup.exprNeedsCleanups() &&
15014              "Unaccounted cleanups in function");
15015       assert(MaybeODRUseExprs.empty() &&
15016              "Leftover expressions for odr-use checking");
15017     }
15018   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15019     // the declaration context below. Otherwise, we're unable to transform
15020     // 'this' expressions when transforming immediate context functions.
15021 
15022   if (!IsInstantiation)
15023     PopDeclContext();
15024 
15025   PopFunctionScopeInfo(ActivePolicy, dcl);
15026   // If any errors have occurred, clear out any temporaries that may have
15027   // been leftover. This ensures that these temporaries won't be picked up for
15028   // deletion in some later function.
15029   if (hasUncompilableErrorOccurred()) {
15030     DiscardCleanupsInEvaluationContext();
15031   }
15032 
15033   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15034                                   !LangOpts.OMPTargetTriples.empty())) ||
15035              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15036     auto ES = getEmissionStatus(FD);
15037     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15038         ES == Sema::FunctionEmissionStatus::Unknown)
15039       DeclsToCheckForDeferredDiags.insert(FD);
15040   }
15041 
15042   if (FD && !FD->isDeleted())
15043     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15044 
15045   return dcl;
15046 }
15047 
15048 /// When we finish delayed parsing of an attribute, we must attach it to the
15049 /// relevant Decl.
15050 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15051                                        ParsedAttributes &Attrs) {
15052   // Always attach attributes to the underlying decl.
15053   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15054     D = TD->getTemplatedDecl();
15055   ProcessDeclAttributeList(S, D, Attrs);
15056 
15057   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15058     if (Method->isStatic())
15059       checkThisInStaticMemberFunctionAttributes(Method);
15060 }
15061 
15062 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15063 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15064 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15065                                           IdentifierInfo &II, Scope *S) {
15066   // Find the scope in which the identifier is injected and the corresponding
15067   // DeclContext.
15068   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15069   // In that case, we inject the declaration into the translation unit scope
15070   // instead.
15071   Scope *BlockScope = S;
15072   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15073     BlockScope = BlockScope->getParent();
15074 
15075   Scope *ContextScope = BlockScope;
15076   while (!ContextScope->getEntity())
15077     ContextScope = ContextScope->getParent();
15078   ContextRAII SavedContext(*this, ContextScope->getEntity());
15079 
15080   // Before we produce a declaration for an implicitly defined
15081   // function, see whether there was a locally-scoped declaration of
15082   // this name as a function or variable. If so, use that
15083   // (non-visible) declaration, and complain about it.
15084   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15085   if (ExternCPrev) {
15086     // We still need to inject the function into the enclosing block scope so
15087     // that later (non-call) uses can see it.
15088     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15089 
15090     // C89 footnote 38:
15091     //   If in fact it is not defined as having type "function returning int",
15092     //   the behavior is undefined.
15093     if (!isa<FunctionDecl>(ExternCPrev) ||
15094         !Context.typesAreCompatible(
15095             cast<FunctionDecl>(ExternCPrev)->getType(),
15096             Context.getFunctionNoProtoType(Context.IntTy))) {
15097       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15098           << ExternCPrev << !getLangOpts().C99;
15099       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15100       return ExternCPrev;
15101     }
15102   }
15103 
15104   // Extension in C99.  Legal in C90, but warn about it.
15105   unsigned diag_id;
15106   if (II.getName().startswith("__builtin_"))
15107     diag_id = diag::warn_builtin_unknown;
15108   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15109   else if (getLangOpts().OpenCL)
15110     diag_id = diag::err_opencl_implicit_function_decl;
15111   else if (getLangOpts().C99)
15112     diag_id = diag::ext_implicit_function_decl;
15113   else
15114     diag_id = diag::warn_implicit_function_decl;
15115 
15116   TypoCorrection Corrected;
15117   // Because typo correction is expensive, only do it if the implicit
15118   // function declaration is going to be treated as an error.
15119   //
15120   // Perform the corection before issuing the main diagnostic, as some consumers
15121   // use typo-correction callbacks to enhance the main diagnostic.
15122   if (S && !ExternCPrev &&
15123       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15124     DeclFilterCCC<FunctionDecl> CCC{};
15125     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15126                             S, nullptr, CCC, CTK_NonError);
15127   }
15128 
15129   Diag(Loc, diag_id) << &II;
15130   if (Corrected)
15131     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15132                  /*ErrorRecovery*/ false);
15133 
15134   // If we found a prior declaration of this function, don't bother building
15135   // another one. We've already pushed that one into scope, so there's nothing
15136   // more to do.
15137   if (ExternCPrev)
15138     return ExternCPrev;
15139 
15140   // Set a Declarator for the implicit definition: int foo();
15141   const char *Dummy;
15142   AttributeFactory attrFactory;
15143   DeclSpec DS(attrFactory);
15144   unsigned DiagID;
15145   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15146                                   Context.getPrintingPolicy());
15147   (void)Error; // Silence warning.
15148   assert(!Error && "Error setting up implicit decl!");
15149   SourceLocation NoLoc;
15150   Declarator D(DS, DeclaratorContext::Block);
15151   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15152                                              /*IsAmbiguous=*/false,
15153                                              /*LParenLoc=*/NoLoc,
15154                                              /*Params=*/nullptr,
15155                                              /*NumParams=*/0,
15156                                              /*EllipsisLoc=*/NoLoc,
15157                                              /*RParenLoc=*/NoLoc,
15158                                              /*RefQualifierIsLvalueRef=*/true,
15159                                              /*RefQualifierLoc=*/NoLoc,
15160                                              /*MutableLoc=*/NoLoc, EST_None,
15161                                              /*ESpecRange=*/SourceRange(),
15162                                              /*Exceptions=*/nullptr,
15163                                              /*ExceptionRanges=*/nullptr,
15164                                              /*NumExceptions=*/0,
15165                                              /*NoexceptExpr=*/nullptr,
15166                                              /*ExceptionSpecTokens=*/nullptr,
15167                                              /*DeclsInPrototype=*/None, Loc,
15168                                              Loc, D),
15169                 std::move(DS.getAttributes()), SourceLocation());
15170   D.SetIdentifier(&II, Loc);
15171 
15172   // Insert this function into the enclosing block scope.
15173   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15174   FD->setImplicit();
15175 
15176   AddKnownFunctionAttributes(FD);
15177 
15178   return FD;
15179 }
15180 
15181 /// If this function is a C++ replaceable global allocation function
15182 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15183 /// adds any function attributes that we know a priori based on the standard.
15184 ///
15185 /// We need to check for duplicate attributes both here and where user-written
15186 /// attributes are applied to declarations.
15187 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15188     FunctionDecl *FD) {
15189   if (FD->isInvalidDecl())
15190     return;
15191 
15192   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15193       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15194     return;
15195 
15196   Optional<unsigned> AlignmentParam;
15197   bool IsNothrow = false;
15198   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15199     return;
15200 
15201   // C++2a [basic.stc.dynamic.allocation]p4:
15202   //   An allocation function that has a non-throwing exception specification
15203   //   indicates failure by returning a null pointer value. Any other allocation
15204   //   function never returns a null pointer value and indicates failure only by
15205   //   throwing an exception [...]
15206   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15207     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15208 
15209   // C++2a [basic.stc.dynamic.allocation]p2:
15210   //   An allocation function attempts to allocate the requested amount of
15211   //   storage. [...] If the request succeeds, the value returned by a
15212   //   replaceable allocation function is a [...] pointer value p0 different
15213   //   from any previously returned value p1 [...]
15214   //
15215   // However, this particular information is being added in codegen,
15216   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15217 
15218   // C++2a [basic.stc.dynamic.allocation]p2:
15219   //   An allocation function attempts to allocate the requested amount of
15220   //   storage. If it is successful, it returns the address of the start of a
15221   //   block of storage whose length in bytes is at least as large as the
15222   //   requested size.
15223   if (!FD->hasAttr<AllocSizeAttr>()) {
15224     FD->addAttr(AllocSizeAttr::CreateImplicit(
15225         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15226         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15227   }
15228 
15229   // C++2a [basic.stc.dynamic.allocation]p3:
15230   //   For an allocation function [...], the pointer returned on a successful
15231   //   call shall represent the address of storage that is aligned as follows:
15232   //   (3.1) If the allocation function takes an argument of type
15233   //         std​::​align_­val_­t, the storage will have the alignment
15234   //         specified by the value of this argument.
15235   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15236     FD->addAttr(AllocAlignAttr::CreateImplicit(
15237         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15238   }
15239 
15240   // FIXME:
15241   // C++2a [basic.stc.dynamic.allocation]p3:
15242   //   For an allocation function [...], the pointer returned on a successful
15243   //   call shall represent the address of storage that is aligned as follows:
15244   //   (3.2) Otherwise, if the allocation function is named operator new[],
15245   //         the storage is aligned for any object that does not have
15246   //         new-extended alignment ([basic.align]) and is no larger than the
15247   //         requested size.
15248   //   (3.3) Otherwise, the storage is aligned for any object that does not
15249   //         have new-extended alignment and is of the requested size.
15250 }
15251 
15252 /// Adds any function attributes that we know a priori based on
15253 /// the declaration of this function.
15254 ///
15255 /// These attributes can apply both to implicitly-declared builtins
15256 /// (like __builtin___printf_chk) or to library-declared functions
15257 /// like NSLog or printf.
15258 ///
15259 /// We need to check for duplicate attributes both here and where user-written
15260 /// attributes are applied to declarations.
15261 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15262   if (FD->isInvalidDecl())
15263     return;
15264 
15265   // If this is a built-in function, map its builtin attributes to
15266   // actual attributes.
15267   if (unsigned BuiltinID = FD->getBuiltinID()) {
15268     // Handle printf-formatting attributes.
15269     unsigned FormatIdx;
15270     bool HasVAListArg;
15271     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15272       if (!FD->hasAttr<FormatAttr>()) {
15273         const char *fmt = "printf";
15274         unsigned int NumParams = FD->getNumParams();
15275         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15276             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15277           fmt = "NSString";
15278         FD->addAttr(FormatAttr::CreateImplicit(Context,
15279                                                &Context.Idents.get(fmt),
15280                                                FormatIdx+1,
15281                                                HasVAListArg ? 0 : FormatIdx+2,
15282                                                FD->getLocation()));
15283       }
15284     }
15285     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15286                                              HasVAListArg)) {
15287      if (!FD->hasAttr<FormatAttr>())
15288        FD->addAttr(FormatAttr::CreateImplicit(Context,
15289                                               &Context.Idents.get("scanf"),
15290                                               FormatIdx+1,
15291                                               HasVAListArg ? 0 : FormatIdx+2,
15292                                               FD->getLocation()));
15293     }
15294 
15295     // Handle automatically recognized callbacks.
15296     SmallVector<int, 4> Encoding;
15297     if (!FD->hasAttr<CallbackAttr>() &&
15298         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15299       FD->addAttr(CallbackAttr::CreateImplicit(
15300           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15301 
15302     // Mark const if we don't care about errno and that is the only thing
15303     // preventing the function from being const. This allows IRgen to use LLVM
15304     // intrinsics for such functions.
15305     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15306         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15307       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15308 
15309     // We make "fma" on GNU or Windows const because we know it does not set
15310     // errno in those environments even though it could set errno based on the
15311     // C standard.
15312     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15313     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15314         !FD->hasAttr<ConstAttr>()) {
15315       switch (BuiltinID) {
15316       case Builtin::BI__builtin_fma:
15317       case Builtin::BI__builtin_fmaf:
15318       case Builtin::BI__builtin_fmal:
15319       case Builtin::BIfma:
15320       case Builtin::BIfmaf:
15321       case Builtin::BIfmal:
15322         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15323         break;
15324       default:
15325         break;
15326       }
15327     }
15328 
15329     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15330         !FD->hasAttr<ReturnsTwiceAttr>())
15331       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15332                                          FD->getLocation()));
15333     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15334       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15335     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15336       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15337     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15338       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15339     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15340         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15341       // Add the appropriate attribute, depending on the CUDA compilation mode
15342       // and which target the builtin belongs to. For example, during host
15343       // compilation, aux builtins are __device__, while the rest are __host__.
15344       if (getLangOpts().CUDAIsDevice !=
15345           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15346         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15347       else
15348         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15349     }
15350 
15351     // Add known guaranteed alignment for allocation functions.
15352     switch (BuiltinID) {
15353     case Builtin::BImemalign:
15354     case Builtin::BIaligned_alloc:
15355       if (!FD->hasAttr<AllocAlignAttr>())
15356         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15357                                                    FD->getLocation()));
15358       break;
15359     default:
15360       break;
15361     }
15362 
15363     // Add allocsize attribute for allocation functions.
15364     switch (BuiltinID) {
15365     case Builtin::BIcalloc:
15366       FD->addAttr(AllocSizeAttr::CreateImplicit(
15367           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15368       break;
15369     case Builtin::BImemalign:
15370     case Builtin::BIaligned_alloc:
15371     case Builtin::BIrealloc:
15372       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15373                                                 ParamIdx(), FD->getLocation()));
15374       break;
15375     case Builtin::BImalloc:
15376       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15377                                                 ParamIdx(), FD->getLocation()));
15378       break;
15379     default:
15380       break;
15381     }
15382   }
15383 
15384   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15385 
15386   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15387   // throw, add an implicit nothrow attribute to any extern "C" function we come
15388   // across.
15389   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15390       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15391     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15392     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15393       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15394   }
15395 
15396   IdentifierInfo *Name = FD->getIdentifier();
15397   if (!Name)
15398     return;
15399   if ((!getLangOpts().CPlusPlus &&
15400        FD->getDeclContext()->isTranslationUnit()) ||
15401       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15402        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15403        LinkageSpecDecl::lang_c)) {
15404     // Okay: this could be a libc/libm/Objective-C function we know
15405     // about.
15406   } else
15407     return;
15408 
15409   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15410     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15411     // target-specific builtins, perhaps?
15412     if (!FD->hasAttr<FormatAttr>())
15413       FD->addAttr(FormatAttr::CreateImplicit(Context,
15414                                              &Context.Idents.get("printf"), 2,
15415                                              Name->isStr("vasprintf") ? 0 : 3,
15416                                              FD->getLocation()));
15417   }
15418 
15419   if (Name->isStr("__CFStringMakeConstantString")) {
15420     // We already have a __builtin___CFStringMakeConstantString,
15421     // but builds that use -fno-constant-cfstrings don't go through that.
15422     if (!FD->hasAttr<FormatArgAttr>())
15423       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15424                                                 FD->getLocation()));
15425   }
15426 }
15427 
15428 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15429                                     TypeSourceInfo *TInfo) {
15430   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15431   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15432 
15433   if (!TInfo) {
15434     assert(D.isInvalidType() && "no declarator info for valid type");
15435     TInfo = Context.getTrivialTypeSourceInfo(T);
15436   }
15437 
15438   // Scope manipulation handled by caller.
15439   TypedefDecl *NewTD =
15440       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15441                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15442 
15443   // Bail out immediately if we have an invalid declaration.
15444   if (D.isInvalidType()) {
15445     NewTD->setInvalidDecl();
15446     return NewTD;
15447   }
15448 
15449   if (D.getDeclSpec().isModulePrivateSpecified()) {
15450     if (CurContext->isFunctionOrMethod())
15451       Diag(NewTD->getLocation(), diag::err_module_private_local)
15452           << 2 << NewTD
15453           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15454           << FixItHint::CreateRemoval(
15455                  D.getDeclSpec().getModulePrivateSpecLoc());
15456     else
15457       NewTD->setModulePrivate();
15458   }
15459 
15460   // C++ [dcl.typedef]p8:
15461   //   If the typedef declaration defines an unnamed class (or
15462   //   enum), the first typedef-name declared by the declaration
15463   //   to be that class type (or enum type) is used to denote the
15464   //   class type (or enum type) for linkage purposes only.
15465   // We need to check whether the type was declared in the declaration.
15466   switch (D.getDeclSpec().getTypeSpecType()) {
15467   case TST_enum:
15468   case TST_struct:
15469   case TST_interface:
15470   case TST_union:
15471   case TST_class: {
15472     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15473     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15474     break;
15475   }
15476 
15477   default:
15478     break;
15479   }
15480 
15481   return NewTD;
15482 }
15483 
15484 /// Check that this is a valid underlying type for an enum declaration.
15485 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15486   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15487   QualType T = TI->getType();
15488 
15489   if (T->isDependentType())
15490     return false;
15491 
15492   // This doesn't use 'isIntegralType' despite the error message mentioning
15493   // integral type because isIntegralType would also allow enum types in C.
15494   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15495     if (BT->isInteger())
15496       return false;
15497 
15498   if (T->isBitIntType())
15499     return false;
15500 
15501   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15502 }
15503 
15504 /// Check whether this is a valid redeclaration of a previous enumeration.
15505 /// \return true if the redeclaration was invalid.
15506 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15507                                   QualType EnumUnderlyingTy, bool IsFixed,
15508                                   const EnumDecl *Prev) {
15509   if (IsScoped != Prev->isScoped()) {
15510     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15511       << Prev->isScoped();
15512     Diag(Prev->getLocation(), diag::note_previous_declaration);
15513     return true;
15514   }
15515 
15516   if (IsFixed && Prev->isFixed()) {
15517     if (!EnumUnderlyingTy->isDependentType() &&
15518         !Prev->getIntegerType()->isDependentType() &&
15519         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15520                                         Prev->getIntegerType())) {
15521       // TODO: Highlight the underlying type of the redeclaration.
15522       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15523         << EnumUnderlyingTy << Prev->getIntegerType();
15524       Diag(Prev->getLocation(), diag::note_previous_declaration)
15525           << Prev->getIntegerTypeRange();
15526       return true;
15527     }
15528   } else if (IsFixed != Prev->isFixed()) {
15529     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15530       << Prev->isFixed();
15531     Diag(Prev->getLocation(), diag::note_previous_declaration);
15532     return true;
15533   }
15534 
15535   return false;
15536 }
15537 
15538 /// Get diagnostic %select index for tag kind for
15539 /// redeclaration diagnostic message.
15540 /// WARNING: Indexes apply to particular diagnostics only!
15541 ///
15542 /// \returns diagnostic %select index.
15543 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15544   switch (Tag) {
15545   case TTK_Struct: return 0;
15546   case TTK_Interface: return 1;
15547   case TTK_Class:  return 2;
15548   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15549   }
15550 }
15551 
15552 /// Determine if tag kind is a class-key compatible with
15553 /// class for redeclaration (class, struct, or __interface).
15554 ///
15555 /// \returns true iff the tag kind is compatible.
15556 static bool isClassCompatTagKind(TagTypeKind Tag)
15557 {
15558   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15559 }
15560 
15561 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15562                                              TagTypeKind TTK) {
15563   if (isa<TypedefDecl>(PrevDecl))
15564     return NTK_Typedef;
15565   else if (isa<TypeAliasDecl>(PrevDecl))
15566     return NTK_TypeAlias;
15567   else if (isa<ClassTemplateDecl>(PrevDecl))
15568     return NTK_Template;
15569   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15570     return NTK_TypeAliasTemplate;
15571   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15572     return NTK_TemplateTemplateArgument;
15573   switch (TTK) {
15574   case TTK_Struct:
15575   case TTK_Interface:
15576   case TTK_Class:
15577     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15578   case TTK_Union:
15579     return NTK_NonUnion;
15580   case TTK_Enum:
15581     return NTK_NonEnum;
15582   }
15583   llvm_unreachable("invalid TTK");
15584 }
15585 
15586 /// Determine whether a tag with a given kind is acceptable
15587 /// as a redeclaration of the given tag declaration.
15588 ///
15589 /// \returns true if the new tag kind is acceptable, false otherwise.
15590 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15591                                         TagTypeKind NewTag, bool isDefinition,
15592                                         SourceLocation NewTagLoc,
15593                                         const IdentifierInfo *Name) {
15594   // C++ [dcl.type.elab]p3:
15595   //   The class-key or enum keyword present in the
15596   //   elaborated-type-specifier shall agree in kind with the
15597   //   declaration to which the name in the elaborated-type-specifier
15598   //   refers. This rule also applies to the form of
15599   //   elaborated-type-specifier that declares a class-name or
15600   //   friend class since it can be construed as referring to the
15601   //   definition of the class. Thus, in any
15602   //   elaborated-type-specifier, the enum keyword shall be used to
15603   //   refer to an enumeration (7.2), the union class-key shall be
15604   //   used to refer to a union (clause 9), and either the class or
15605   //   struct class-key shall be used to refer to a class (clause 9)
15606   //   declared using the class or struct class-key.
15607   TagTypeKind OldTag = Previous->getTagKind();
15608   if (OldTag != NewTag &&
15609       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15610     return false;
15611 
15612   // Tags are compatible, but we might still want to warn on mismatched tags.
15613   // Non-class tags can't be mismatched at this point.
15614   if (!isClassCompatTagKind(NewTag))
15615     return true;
15616 
15617   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15618   // by our warning analysis. We don't want to warn about mismatches with (eg)
15619   // declarations in system headers that are designed to be specialized, but if
15620   // a user asks us to warn, we should warn if their code contains mismatched
15621   // declarations.
15622   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15623     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15624                                       Loc);
15625   };
15626   if (IsIgnoredLoc(NewTagLoc))
15627     return true;
15628 
15629   auto IsIgnored = [&](const TagDecl *Tag) {
15630     return IsIgnoredLoc(Tag->getLocation());
15631   };
15632   while (IsIgnored(Previous)) {
15633     Previous = Previous->getPreviousDecl();
15634     if (!Previous)
15635       return true;
15636     OldTag = Previous->getTagKind();
15637   }
15638 
15639   bool isTemplate = false;
15640   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15641     isTemplate = Record->getDescribedClassTemplate();
15642 
15643   if (inTemplateInstantiation()) {
15644     if (OldTag != NewTag) {
15645       // In a template instantiation, do not offer fix-its for tag mismatches
15646       // since they usually mess up the template instead of fixing the problem.
15647       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15648         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15649         << getRedeclDiagFromTagKind(OldTag);
15650       // FIXME: Note previous location?
15651     }
15652     return true;
15653   }
15654 
15655   if (isDefinition) {
15656     // On definitions, check all previous tags and issue a fix-it for each
15657     // one that doesn't match the current tag.
15658     if (Previous->getDefinition()) {
15659       // Don't suggest fix-its for redefinitions.
15660       return true;
15661     }
15662 
15663     bool previousMismatch = false;
15664     for (const TagDecl *I : Previous->redecls()) {
15665       if (I->getTagKind() != NewTag) {
15666         // Ignore previous declarations for which the warning was disabled.
15667         if (IsIgnored(I))
15668           continue;
15669 
15670         if (!previousMismatch) {
15671           previousMismatch = true;
15672           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15673             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15674             << getRedeclDiagFromTagKind(I->getTagKind());
15675         }
15676         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15677           << getRedeclDiagFromTagKind(NewTag)
15678           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15679                TypeWithKeyword::getTagTypeKindName(NewTag));
15680       }
15681     }
15682     return true;
15683   }
15684 
15685   // Identify the prevailing tag kind: this is the kind of the definition (if
15686   // there is a non-ignored definition), or otherwise the kind of the prior
15687   // (non-ignored) declaration.
15688   const TagDecl *PrevDef = Previous->getDefinition();
15689   if (PrevDef && IsIgnored(PrevDef))
15690     PrevDef = nullptr;
15691   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15692   if (Redecl->getTagKind() != NewTag) {
15693     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15694       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15695       << getRedeclDiagFromTagKind(OldTag);
15696     Diag(Redecl->getLocation(), diag::note_previous_use);
15697 
15698     // If there is a previous definition, suggest a fix-it.
15699     if (PrevDef) {
15700       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15701         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15702         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15703              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15704     }
15705   }
15706 
15707   return true;
15708 }
15709 
15710 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15711 /// from an outer enclosing namespace or file scope inside a friend declaration.
15712 /// This should provide the commented out code in the following snippet:
15713 ///   namespace N {
15714 ///     struct X;
15715 ///     namespace M {
15716 ///       struct Y { friend struct /*N::*/ X; };
15717 ///     }
15718 ///   }
15719 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15720                                          SourceLocation NameLoc) {
15721   // While the decl is in a namespace, do repeated lookup of that name and see
15722   // if we get the same namespace back.  If we do not, continue until
15723   // translation unit scope, at which point we have a fully qualified NNS.
15724   SmallVector<IdentifierInfo *, 4> Namespaces;
15725   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15726   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15727     // This tag should be declared in a namespace, which can only be enclosed by
15728     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15729     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15730     if (!Namespace || Namespace->isAnonymousNamespace())
15731       return FixItHint();
15732     IdentifierInfo *II = Namespace->getIdentifier();
15733     Namespaces.push_back(II);
15734     NamedDecl *Lookup = SemaRef.LookupSingleName(
15735         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15736     if (Lookup == Namespace)
15737       break;
15738   }
15739 
15740   // Once we have all the namespaces, reverse them to go outermost first, and
15741   // build an NNS.
15742   SmallString<64> Insertion;
15743   llvm::raw_svector_ostream OS(Insertion);
15744   if (DC->isTranslationUnit())
15745     OS << "::";
15746   std::reverse(Namespaces.begin(), Namespaces.end());
15747   for (auto *II : Namespaces)
15748     OS << II->getName() << "::";
15749   return FixItHint::CreateInsertion(NameLoc, Insertion);
15750 }
15751 
15752 /// Determine whether a tag originally declared in context \p OldDC can
15753 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15754 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15755 /// using-declaration).
15756 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15757                                          DeclContext *NewDC) {
15758   OldDC = OldDC->getRedeclContext();
15759   NewDC = NewDC->getRedeclContext();
15760 
15761   if (OldDC->Equals(NewDC))
15762     return true;
15763 
15764   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15765   // encloses the other).
15766   if (S.getLangOpts().MSVCCompat &&
15767       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15768     return true;
15769 
15770   return false;
15771 }
15772 
15773 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15774 /// former case, Name will be non-null.  In the later case, Name will be null.
15775 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15776 /// reference/declaration/definition of a tag.
15777 ///
15778 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15779 /// trailing-type-specifier) other than one in an alias-declaration.
15780 ///
15781 /// \param SkipBody If non-null, will be set to indicate if the caller should
15782 /// skip the definition of this tag and treat it as if it were a declaration.
15783 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15784                      SourceLocation KWLoc, CXXScopeSpec &SS,
15785                      IdentifierInfo *Name, SourceLocation NameLoc,
15786                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15787                      SourceLocation ModulePrivateLoc,
15788                      MultiTemplateParamsArg TemplateParameterLists,
15789                      bool &OwnedDecl, bool &IsDependent,
15790                      SourceLocation ScopedEnumKWLoc,
15791                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15792                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15793                      SkipBodyInfo *SkipBody) {
15794   // If this is not a definition, it must have a name.
15795   IdentifierInfo *OrigName = Name;
15796   assert((Name != nullptr || TUK == TUK_Definition) &&
15797          "Nameless record must be a definition!");
15798   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15799 
15800   OwnedDecl = false;
15801   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15802   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15803 
15804   // FIXME: Check member specializations more carefully.
15805   bool isMemberSpecialization = false;
15806   bool Invalid = false;
15807 
15808   // We only need to do this matching if we have template parameters
15809   // or a scope specifier, which also conveniently avoids this work
15810   // for non-C++ cases.
15811   if (TemplateParameterLists.size() > 0 ||
15812       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15813     if (TemplateParameterList *TemplateParams =
15814             MatchTemplateParametersToScopeSpecifier(
15815                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15816                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15817       if (Kind == TTK_Enum) {
15818         Diag(KWLoc, diag::err_enum_template);
15819         return nullptr;
15820       }
15821 
15822       if (TemplateParams->size() > 0) {
15823         // This is a declaration or definition of a class template (which may
15824         // be a member of another template).
15825 
15826         if (Invalid)
15827           return nullptr;
15828 
15829         OwnedDecl = false;
15830         DeclResult Result = CheckClassTemplate(
15831             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15832             AS, ModulePrivateLoc,
15833             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15834             TemplateParameterLists.data(), SkipBody);
15835         return Result.get();
15836       } else {
15837         // The "template<>" header is extraneous.
15838         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15839           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15840         isMemberSpecialization = true;
15841       }
15842     }
15843 
15844     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15845         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15846       return nullptr;
15847   }
15848 
15849   // Figure out the underlying type if this a enum declaration. We need to do
15850   // this early, because it's needed to detect if this is an incompatible
15851   // redeclaration.
15852   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15853   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15854 
15855   if (Kind == TTK_Enum) {
15856     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15857       // No underlying type explicitly specified, or we failed to parse the
15858       // type, default to int.
15859       EnumUnderlying = Context.IntTy.getTypePtr();
15860     } else if (UnderlyingType.get()) {
15861       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15862       // integral type; any cv-qualification is ignored.
15863       TypeSourceInfo *TI = nullptr;
15864       GetTypeFromParser(UnderlyingType.get(), &TI);
15865       EnumUnderlying = TI;
15866 
15867       if (CheckEnumUnderlyingType(TI))
15868         // Recover by falling back to int.
15869         EnumUnderlying = Context.IntTy.getTypePtr();
15870 
15871       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15872                                           UPPC_FixedUnderlyingType))
15873         EnumUnderlying = Context.IntTy.getTypePtr();
15874 
15875     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15876       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15877       // of 'int'. However, if this is an unfixed forward declaration, don't set
15878       // the underlying type unless the user enables -fms-compatibility. This
15879       // makes unfixed forward declared enums incomplete and is more conforming.
15880       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15881         EnumUnderlying = Context.IntTy.getTypePtr();
15882     }
15883   }
15884 
15885   DeclContext *SearchDC = CurContext;
15886   DeclContext *DC = CurContext;
15887   bool isStdBadAlloc = false;
15888   bool isStdAlignValT = false;
15889 
15890   RedeclarationKind Redecl = forRedeclarationInCurContext();
15891   if (TUK == TUK_Friend || TUK == TUK_Reference)
15892     Redecl = NotForRedeclaration;
15893 
15894   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15895   /// implemented asks for structural equivalence checking, the returned decl
15896   /// here is passed back to the parser, allowing the tag body to be parsed.
15897   auto createTagFromNewDecl = [&]() -> TagDecl * {
15898     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15899     // If there is an identifier, use the location of the identifier as the
15900     // location of the decl, otherwise use the location of the struct/union
15901     // keyword.
15902     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15903     TagDecl *New = nullptr;
15904 
15905     if (Kind == TTK_Enum) {
15906       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15907                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15908       // If this is an undefined enum, bail.
15909       if (TUK != TUK_Definition && !Invalid)
15910         return nullptr;
15911       if (EnumUnderlying) {
15912         EnumDecl *ED = cast<EnumDecl>(New);
15913         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15914           ED->setIntegerTypeSourceInfo(TI);
15915         else
15916           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15917         ED->setPromotionType(ED->getIntegerType());
15918       }
15919     } else { // struct/union
15920       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15921                                nullptr);
15922     }
15923 
15924     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15925       // Add alignment attributes if necessary; these attributes are checked
15926       // when the ASTContext lays out the structure.
15927       //
15928       // It is important for implementing the correct semantics that this
15929       // happen here (in ActOnTag). The #pragma pack stack is
15930       // maintained as a result of parser callbacks which can occur at
15931       // many points during the parsing of a struct declaration (because
15932       // the #pragma tokens are effectively skipped over during the
15933       // parsing of the struct).
15934       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15935         AddAlignmentAttributesForRecord(RD);
15936         AddMsStructLayoutForRecord(RD);
15937       }
15938     }
15939     New->setLexicalDeclContext(CurContext);
15940     return New;
15941   };
15942 
15943   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15944   if (Name && SS.isNotEmpty()) {
15945     // We have a nested-name tag ('struct foo::bar').
15946 
15947     // Check for invalid 'foo::'.
15948     if (SS.isInvalid()) {
15949       Name = nullptr;
15950       goto CreateNewDecl;
15951     }
15952 
15953     // If this is a friend or a reference to a class in a dependent
15954     // context, don't try to make a decl for it.
15955     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15956       DC = computeDeclContext(SS, false);
15957       if (!DC) {
15958         IsDependent = true;
15959         return nullptr;
15960       }
15961     } else {
15962       DC = computeDeclContext(SS, true);
15963       if (!DC) {
15964         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15965           << SS.getRange();
15966         return nullptr;
15967       }
15968     }
15969 
15970     if (RequireCompleteDeclContext(SS, DC))
15971       return nullptr;
15972 
15973     SearchDC = DC;
15974     // Look-up name inside 'foo::'.
15975     LookupQualifiedName(Previous, DC);
15976 
15977     if (Previous.isAmbiguous())
15978       return nullptr;
15979 
15980     if (Previous.empty()) {
15981       // Name lookup did not find anything. However, if the
15982       // nested-name-specifier refers to the current instantiation,
15983       // and that current instantiation has any dependent base
15984       // classes, we might find something at instantiation time: treat
15985       // this as a dependent elaborated-type-specifier.
15986       // But this only makes any sense for reference-like lookups.
15987       if (Previous.wasNotFoundInCurrentInstantiation() &&
15988           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15989         IsDependent = true;
15990         return nullptr;
15991       }
15992 
15993       // A tag 'foo::bar' must already exist.
15994       Diag(NameLoc, diag::err_not_tag_in_scope)
15995         << Kind << Name << DC << SS.getRange();
15996       Name = nullptr;
15997       Invalid = true;
15998       goto CreateNewDecl;
15999     }
16000   } else if (Name) {
16001     // C++14 [class.mem]p14:
16002     //   If T is the name of a class, then each of the following shall have a
16003     //   name different from T:
16004     //    -- every member of class T that is itself a type
16005     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16006         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16007       return nullptr;
16008 
16009     // If this is a named struct, check to see if there was a previous forward
16010     // declaration or definition.
16011     // FIXME: We're looking into outer scopes here, even when we
16012     // shouldn't be. Doing so can result in ambiguities that we
16013     // shouldn't be diagnosing.
16014     LookupName(Previous, S);
16015 
16016     // When declaring or defining a tag, ignore ambiguities introduced
16017     // by types using'ed into this scope.
16018     if (Previous.isAmbiguous() &&
16019         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16020       LookupResult::Filter F = Previous.makeFilter();
16021       while (F.hasNext()) {
16022         NamedDecl *ND = F.next();
16023         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16024                 SearchDC->getRedeclContext()))
16025           F.erase();
16026       }
16027       F.done();
16028     }
16029 
16030     // C++11 [namespace.memdef]p3:
16031     //   If the name in a friend declaration is neither qualified nor
16032     //   a template-id and the declaration is a function or an
16033     //   elaborated-type-specifier, the lookup to determine whether
16034     //   the entity has been previously declared shall not consider
16035     //   any scopes outside the innermost enclosing namespace.
16036     //
16037     // MSVC doesn't implement the above rule for types, so a friend tag
16038     // declaration may be a redeclaration of a type declared in an enclosing
16039     // scope.  They do implement this rule for friend functions.
16040     //
16041     // Does it matter that this should be by scope instead of by
16042     // semantic context?
16043     if (!Previous.empty() && TUK == TUK_Friend) {
16044       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16045       LookupResult::Filter F = Previous.makeFilter();
16046       bool FriendSawTagOutsideEnclosingNamespace = false;
16047       while (F.hasNext()) {
16048         NamedDecl *ND = F.next();
16049         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16050         if (DC->isFileContext() &&
16051             !EnclosingNS->Encloses(ND->getDeclContext())) {
16052           if (getLangOpts().MSVCCompat)
16053             FriendSawTagOutsideEnclosingNamespace = true;
16054           else
16055             F.erase();
16056         }
16057       }
16058       F.done();
16059 
16060       // Diagnose this MSVC extension in the easy case where lookup would have
16061       // unambiguously found something outside the enclosing namespace.
16062       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16063         NamedDecl *ND = Previous.getFoundDecl();
16064         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16065             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16066       }
16067     }
16068 
16069     // Note:  there used to be some attempt at recovery here.
16070     if (Previous.isAmbiguous())
16071       return nullptr;
16072 
16073     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16074       // FIXME: This makes sure that we ignore the contexts associated
16075       // with C structs, unions, and enums when looking for a matching
16076       // tag declaration or definition. See the similar lookup tweak
16077       // in Sema::LookupName; is there a better way to deal with this?
16078       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16079         SearchDC = SearchDC->getParent();
16080     } else if (getLangOpts().CPlusPlus) {
16081       // Inside ObjCContainer want to keep it as a lexical decl context but go
16082       // past it (most often to TranslationUnit) to find the semantic decl
16083       // context.
16084       while (isa<ObjCContainerDecl>(SearchDC))
16085         SearchDC = SearchDC->getParent();
16086     }
16087   } else if (getLangOpts().CPlusPlus) {
16088     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16089     // TagDecl the same way as we skip it for named TagDecl.
16090     while (isa<ObjCContainerDecl>(SearchDC))
16091       SearchDC = SearchDC->getParent();
16092   }
16093 
16094   if (Previous.isSingleResult() &&
16095       Previous.getFoundDecl()->isTemplateParameter()) {
16096     // Maybe we will complain about the shadowed template parameter.
16097     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16098     // Just pretend that we didn't see the previous declaration.
16099     Previous.clear();
16100   }
16101 
16102   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16103       DC->Equals(getStdNamespace())) {
16104     if (Name->isStr("bad_alloc")) {
16105       // This is a declaration of or a reference to "std::bad_alloc".
16106       isStdBadAlloc = true;
16107 
16108       // If std::bad_alloc has been implicitly declared (but made invisible to
16109       // name lookup), fill in this implicit declaration as the previous
16110       // declaration, so that the declarations get chained appropriately.
16111       if (Previous.empty() && StdBadAlloc)
16112         Previous.addDecl(getStdBadAlloc());
16113     } else if (Name->isStr("align_val_t")) {
16114       isStdAlignValT = true;
16115       if (Previous.empty() && StdAlignValT)
16116         Previous.addDecl(getStdAlignValT());
16117     }
16118   }
16119 
16120   // If we didn't find a previous declaration, and this is a reference
16121   // (or friend reference), move to the correct scope.  In C++, we
16122   // also need to do a redeclaration lookup there, just in case
16123   // there's a shadow friend decl.
16124   if (Name && Previous.empty() &&
16125       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16126     if (Invalid) goto CreateNewDecl;
16127     assert(SS.isEmpty());
16128 
16129     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16130       // C++ [basic.scope.pdecl]p5:
16131       //   -- for an elaborated-type-specifier of the form
16132       //
16133       //          class-key identifier
16134       //
16135       //      if the elaborated-type-specifier is used in the
16136       //      decl-specifier-seq or parameter-declaration-clause of a
16137       //      function defined in namespace scope, the identifier is
16138       //      declared as a class-name in the namespace that contains
16139       //      the declaration; otherwise, except as a friend
16140       //      declaration, the identifier is declared in the smallest
16141       //      non-class, non-function-prototype scope that contains the
16142       //      declaration.
16143       //
16144       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16145       // C structs and unions.
16146       //
16147       // It is an error in C++ to declare (rather than define) an enum
16148       // type, including via an elaborated type specifier.  We'll
16149       // diagnose that later; for now, declare the enum in the same
16150       // scope as we would have picked for any other tag type.
16151       //
16152       // GNU C also supports this behavior as part of its incomplete
16153       // enum types extension, while GNU C++ does not.
16154       //
16155       // Find the context where we'll be declaring the tag.
16156       // FIXME: We would like to maintain the current DeclContext as the
16157       // lexical context,
16158       SearchDC = getTagInjectionContext(SearchDC);
16159 
16160       // Find the scope where we'll be declaring the tag.
16161       S = getTagInjectionScope(S, getLangOpts());
16162     } else {
16163       assert(TUK == TUK_Friend);
16164       // C++ [namespace.memdef]p3:
16165       //   If a friend declaration in a non-local class first declares a
16166       //   class or function, the friend class or function is a member of
16167       //   the innermost enclosing namespace.
16168       SearchDC = SearchDC->getEnclosingNamespaceContext();
16169     }
16170 
16171     // In C++, we need to do a redeclaration lookup to properly
16172     // diagnose some problems.
16173     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16174     // hidden declaration so that we don't get ambiguity errors when using a
16175     // type declared by an elaborated-type-specifier.  In C that is not correct
16176     // and we should instead merge compatible types found by lookup.
16177     if (getLangOpts().CPlusPlus) {
16178       // FIXME: This can perform qualified lookups into function contexts,
16179       // which are meaningless.
16180       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16181       LookupQualifiedName(Previous, SearchDC);
16182     } else {
16183       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16184       LookupName(Previous, S);
16185     }
16186   }
16187 
16188   // If we have a known previous declaration to use, then use it.
16189   if (Previous.empty() && SkipBody && SkipBody->Previous)
16190     Previous.addDecl(SkipBody->Previous);
16191 
16192   if (!Previous.empty()) {
16193     NamedDecl *PrevDecl = Previous.getFoundDecl();
16194     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16195 
16196     // It's okay to have a tag decl in the same scope as a typedef
16197     // which hides a tag decl in the same scope.  Finding this
16198     // with a redeclaration lookup can only actually happen in C++.
16199     //
16200     // This is also okay for elaborated-type-specifiers, which is
16201     // technically forbidden by the current standard but which is
16202     // okay according to the likely resolution of an open issue;
16203     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16204     if (getLangOpts().CPlusPlus) {
16205       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16206         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16207           TagDecl *Tag = TT->getDecl();
16208           if (Tag->getDeclName() == Name &&
16209               Tag->getDeclContext()->getRedeclContext()
16210                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16211             PrevDecl = Tag;
16212             Previous.clear();
16213             Previous.addDecl(Tag);
16214             Previous.resolveKind();
16215           }
16216         }
16217       }
16218     }
16219 
16220     // If this is a redeclaration of a using shadow declaration, it must
16221     // declare a tag in the same context. In MSVC mode, we allow a
16222     // redefinition if either context is within the other.
16223     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16224       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16225       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16226           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16227           !(OldTag && isAcceptableTagRedeclContext(
16228                           *this, OldTag->getDeclContext(), SearchDC))) {
16229         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16230         Diag(Shadow->getTargetDecl()->getLocation(),
16231              diag::note_using_decl_target);
16232         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16233             << 0;
16234         // Recover by ignoring the old declaration.
16235         Previous.clear();
16236         goto CreateNewDecl;
16237       }
16238     }
16239 
16240     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16241       // If this is a use of a previous tag, or if the tag is already declared
16242       // in the same scope (so that the definition/declaration completes or
16243       // rementions the tag), reuse the decl.
16244       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16245           isDeclInScope(DirectPrevDecl, SearchDC, S,
16246                         SS.isNotEmpty() || isMemberSpecialization)) {
16247         // Make sure that this wasn't declared as an enum and now used as a
16248         // struct or something similar.
16249         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16250                                           TUK == TUK_Definition, KWLoc,
16251                                           Name)) {
16252           bool SafeToContinue
16253             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16254                Kind != TTK_Enum);
16255           if (SafeToContinue)
16256             Diag(KWLoc, diag::err_use_with_wrong_tag)
16257               << Name
16258               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16259                                               PrevTagDecl->getKindName());
16260           else
16261             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16262           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16263 
16264           if (SafeToContinue)
16265             Kind = PrevTagDecl->getTagKind();
16266           else {
16267             // Recover by making this an anonymous redefinition.
16268             Name = nullptr;
16269             Previous.clear();
16270             Invalid = true;
16271           }
16272         }
16273 
16274         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16275           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16276           if (TUK == TUK_Reference || TUK == TUK_Friend)
16277             return PrevTagDecl;
16278 
16279           QualType EnumUnderlyingTy;
16280           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16281             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16282           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16283             EnumUnderlyingTy = QualType(T, 0);
16284 
16285           // All conflicts with previous declarations are recovered by
16286           // returning the previous declaration, unless this is a definition,
16287           // in which case we want the caller to bail out.
16288           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16289                                      ScopedEnum, EnumUnderlyingTy,
16290                                      IsFixed, PrevEnum))
16291             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16292         }
16293 
16294         // C++11 [class.mem]p1:
16295         //   A member shall not be declared twice in the member-specification,
16296         //   except that a nested class or member class template can be declared
16297         //   and then later defined.
16298         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16299             S->isDeclScope(PrevDecl)) {
16300           Diag(NameLoc, diag::ext_member_redeclared);
16301           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16302         }
16303 
16304         if (!Invalid) {
16305           // If this is a use, just return the declaration we found, unless
16306           // we have attributes.
16307           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16308             if (!Attrs.empty()) {
16309               // FIXME: Diagnose these attributes. For now, we create a new
16310               // declaration to hold them.
16311             } else if (TUK == TUK_Reference &&
16312                        (PrevTagDecl->getFriendObjectKind() ==
16313                             Decl::FOK_Undeclared ||
16314                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16315                        SS.isEmpty()) {
16316               // This declaration is a reference to an existing entity, but
16317               // has different visibility from that entity: it either makes
16318               // a friend visible or it makes a type visible in a new module.
16319               // In either case, create a new declaration. We only do this if
16320               // the declaration would have meant the same thing if no prior
16321               // declaration were found, that is, if it was found in the same
16322               // scope where we would have injected a declaration.
16323               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16324                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16325                 return PrevTagDecl;
16326               // This is in the injected scope, create a new declaration in
16327               // that scope.
16328               S = getTagInjectionScope(S, getLangOpts());
16329             } else {
16330               return PrevTagDecl;
16331             }
16332           }
16333 
16334           // Diagnose attempts to redefine a tag.
16335           if (TUK == TUK_Definition) {
16336             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16337               // If we're defining a specialization and the previous definition
16338               // is from an implicit instantiation, don't emit an error
16339               // here; we'll catch this in the general case below.
16340               bool IsExplicitSpecializationAfterInstantiation = false;
16341               if (isMemberSpecialization) {
16342                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16343                   IsExplicitSpecializationAfterInstantiation =
16344                     RD->getTemplateSpecializationKind() !=
16345                     TSK_ExplicitSpecialization;
16346                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16347                   IsExplicitSpecializationAfterInstantiation =
16348                     ED->getTemplateSpecializationKind() !=
16349                     TSK_ExplicitSpecialization;
16350               }
16351 
16352               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16353               // not keep more that one definition around (merge them). However,
16354               // ensure the decl passes the structural compatibility check in
16355               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16356               NamedDecl *Hidden = nullptr;
16357               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16358                 // There is a definition of this tag, but it is not visible. We
16359                 // explicitly make use of C++'s one definition rule here, and
16360                 // assume that this definition is identical to the hidden one
16361                 // we already have. Make the existing definition visible and
16362                 // use it in place of this one.
16363                 if (!getLangOpts().CPlusPlus) {
16364                   // Postpone making the old definition visible until after we
16365                   // complete parsing the new one and do the structural
16366                   // comparison.
16367                   SkipBody->CheckSameAsPrevious = true;
16368                   SkipBody->New = createTagFromNewDecl();
16369                   SkipBody->Previous = Def;
16370                   return Def;
16371                 } else {
16372                   SkipBody->ShouldSkip = true;
16373                   SkipBody->Previous = Def;
16374                   makeMergedDefinitionVisible(Hidden);
16375                   // Carry on and handle it like a normal definition. We'll
16376                   // skip starting the definitiion later.
16377                 }
16378               } else if (!IsExplicitSpecializationAfterInstantiation) {
16379                 // A redeclaration in function prototype scope in C isn't
16380                 // visible elsewhere, so merely issue a warning.
16381                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16382                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16383                 else
16384                   Diag(NameLoc, diag::err_redefinition) << Name;
16385                 notePreviousDefinition(Def,
16386                                        NameLoc.isValid() ? NameLoc : KWLoc);
16387                 // If this is a redefinition, recover by making this
16388                 // struct be anonymous, which will make any later
16389                 // references get the previous definition.
16390                 Name = nullptr;
16391                 Previous.clear();
16392                 Invalid = true;
16393               }
16394             } else {
16395               // If the type is currently being defined, complain
16396               // about a nested redefinition.
16397               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16398               if (TD->isBeingDefined()) {
16399                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16400                 Diag(PrevTagDecl->getLocation(),
16401                      diag::note_previous_definition);
16402                 Name = nullptr;
16403                 Previous.clear();
16404                 Invalid = true;
16405               }
16406             }
16407 
16408             // Okay, this is definition of a previously declared or referenced
16409             // tag. We're going to create a new Decl for it.
16410           }
16411 
16412           // Okay, we're going to make a redeclaration.  If this is some kind
16413           // of reference, make sure we build the redeclaration in the same DC
16414           // as the original, and ignore the current access specifier.
16415           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16416             SearchDC = PrevTagDecl->getDeclContext();
16417             AS = AS_none;
16418           }
16419         }
16420         // If we get here we have (another) forward declaration or we
16421         // have a definition.  Just create a new decl.
16422 
16423       } else {
16424         // If we get here, this is a definition of a new tag type in a nested
16425         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16426         // new decl/type.  We set PrevDecl to NULL so that the entities
16427         // have distinct types.
16428         Previous.clear();
16429       }
16430       // If we get here, we're going to create a new Decl. If PrevDecl
16431       // is non-NULL, it's a definition of the tag declared by
16432       // PrevDecl. If it's NULL, we have a new definition.
16433 
16434     // Otherwise, PrevDecl is not a tag, but was found with tag
16435     // lookup.  This is only actually possible in C++, where a few
16436     // things like templates still live in the tag namespace.
16437     } else {
16438       // Use a better diagnostic if an elaborated-type-specifier
16439       // found the wrong kind of type on the first
16440       // (non-redeclaration) lookup.
16441       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16442           !Previous.isForRedeclaration()) {
16443         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16444         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16445                                                        << Kind;
16446         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16447         Invalid = true;
16448 
16449       // Otherwise, only diagnose if the declaration is in scope.
16450       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16451                                 SS.isNotEmpty() || isMemberSpecialization)) {
16452         // do nothing
16453 
16454       // Diagnose implicit declarations introduced by elaborated types.
16455       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16456         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16457         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16458         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16459         Invalid = true;
16460 
16461       // Otherwise it's a declaration.  Call out a particularly common
16462       // case here.
16463       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16464         unsigned Kind = 0;
16465         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16466         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16467           << Name << Kind << TND->getUnderlyingType();
16468         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16469         Invalid = true;
16470 
16471       // Otherwise, diagnose.
16472       } else {
16473         // The tag name clashes with something else in the target scope,
16474         // issue an error and recover by making this tag be anonymous.
16475         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16476         notePreviousDefinition(PrevDecl, NameLoc);
16477         Name = nullptr;
16478         Invalid = true;
16479       }
16480 
16481       // The existing declaration isn't relevant to us; we're in a
16482       // new scope, so clear out the previous declaration.
16483       Previous.clear();
16484     }
16485   }
16486 
16487 CreateNewDecl:
16488 
16489   TagDecl *PrevDecl = nullptr;
16490   if (Previous.isSingleResult())
16491     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16492 
16493   // If there is an identifier, use the location of the identifier as the
16494   // location of the decl, otherwise use the location of the struct/union
16495   // keyword.
16496   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16497 
16498   // Otherwise, create a new declaration. If there is a previous
16499   // declaration of the same entity, the two will be linked via
16500   // PrevDecl.
16501   TagDecl *New;
16502 
16503   if (Kind == TTK_Enum) {
16504     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16505     // enum X { A, B, C } D;    D should chain to X.
16506     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16507                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16508                            ScopedEnumUsesClassTag, IsFixed);
16509 
16510     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16511       StdAlignValT = cast<EnumDecl>(New);
16512 
16513     // If this is an undefined enum, warn.
16514     if (TUK != TUK_Definition && !Invalid) {
16515       TagDecl *Def;
16516       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16517         // C++0x: 7.2p2: opaque-enum-declaration.
16518         // Conflicts are diagnosed above. Do nothing.
16519       }
16520       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16521         Diag(Loc, diag::ext_forward_ref_enum_def)
16522           << New;
16523         Diag(Def->getLocation(), diag::note_previous_definition);
16524       } else {
16525         unsigned DiagID = diag::ext_forward_ref_enum;
16526         if (getLangOpts().MSVCCompat)
16527           DiagID = diag::ext_ms_forward_ref_enum;
16528         else if (getLangOpts().CPlusPlus)
16529           DiagID = diag::err_forward_ref_enum;
16530         Diag(Loc, DiagID);
16531       }
16532     }
16533 
16534     if (EnumUnderlying) {
16535       EnumDecl *ED = cast<EnumDecl>(New);
16536       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16537         ED->setIntegerTypeSourceInfo(TI);
16538       else
16539         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16540       ED->setPromotionType(ED->getIntegerType());
16541       assert(ED->isComplete() && "enum with type should be complete");
16542     }
16543   } else {
16544     // struct/union/class
16545 
16546     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16547     // struct X { int A; } D;    D should chain to X.
16548     if (getLangOpts().CPlusPlus) {
16549       // FIXME: Look for a way to use RecordDecl for simple structs.
16550       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16551                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16552 
16553       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16554         StdBadAlloc = cast<CXXRecordDecl>(New);
16555     } else
16556       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16557                                cast_or_null<RecordDecl>(PrevDecl));
16558   }
16559 
16560   // C++11 [dcl.type]p3:
16561   //   A type-specifier-seq shall not define a class or enumeration [...].
16562   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16563       TUK == TUK_Definition) {
16564     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16565       << Context.getTagDeclType(New);
16566     Invalid = true;
16567   }
16568 
16569   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16570       DC->getDeclKind() == Decl::Enum) {
16571     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16572       << Context.getTagDeclType(New);
16573     Invalid = true;
16574   }
16575 
16576   // Maybe add qualifier info.
16577   if (SS.isNotEmpty()) {
16578     if (SS.isSet()) {
16579       // If this is either a declaration or a definition, check the
16580       // nested-name-specifier against the current context.
16581       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16582           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16583                                        isMemberSpecialization))
16584         Invalid = true;
16585 
16586       New->setQualifierInfo(SS.getWithLocInContext(Context));
16587       if (TemplateParameterLists.size() > 0) {
16588         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16589       }
16590     }
16591     else
16592       Invalid = true;
16593   }
16594 
16595   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16596     // Add alignment attributes if necessary; these attributes are checked when
16597     // the ASTContext lays out the structure.
16598     //
16599     // It is important for implementing the correct semantics that this
16600     // happen here (in ActOnTag). The #pragma pack stack is
16601     // maintained as a result of parser callbacks which can occur at
16602     // many points during the parsing of a struct declaration (because
16603     // the #pragma tokens are effectively skipped over during the
16604     // parsing of the struct).
16605     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16606       AddAlignmentAttributesForRecord(RD);
16607       AddMsStructLayoutForRecord(RD);
16608     }
16609   }
16610 
16611   if (ModulePrivateLoc.isValid()) {
16612     if (isMemberSpecialization)
16613       Diag(New->getLocation(), diag::err_module_private_specialization)
16614         << 2
16615         << FixItHint::CreateRemoval(ModulePrivateLoc);
16616     // __module_private__ does not apply to local classes. However, we only
16617     // diagnose this as an error when the declaration specifiers are
16618     // freestanding. Here, we just ignore the __module_private__.
16619     else if (!SearchDC->isFunctionOrMethod())
16620       New->setModulePrivate();
16621   }
16622 
16623   // If this is a specialization of a member class (of a class template),
16624   // check the specialization.
16625   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16626     Invalid = true;
16627 
16628   // If we're declaring or defining a tag in function prototype scope in C,
16629   // note that this type can only be used within the function and add it to
16630   // the list of decls to inject into the function definition scope.
16631   if ((Name || Kind == TTK_Enum) &&
16632       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16633     if (getLangOpts().CPlusPlus) {
16634       // C++ [dcl.fct]p6:
16635       //   Types shall not be defined in return or parameter types.
16636       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16637         Diag(Loc, diag::err_type_defined_in_param_type)
16638             << Name;
16639         Invalid = true;
16640       }
16641     } else if (!PrevDecl) {
16642       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16643     }
16644   }
16645 
16646   if (Invalid)
16647     New->setInvalidDecl();
16648 
16649   // Set the lexical context. If the tag has a C++ scope specifier, the
16650   // lexical context will be different from the semantic context.
16651   New->setLexicalDeclContext(CurContext);
16652 
16653   // Mark this as a friend decl if applicable.
16654   // In Microsoft mode, a friend declaration also acts as a forward
16655   // declaration so we always pass true to setObjectOfFriendDecl to make
16656   // the tag name visible.
16657   if (TUK == TUK_Friend)
16658     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16659 
16660   // Set the access specifier.
16661   if (!Invalid && SearchDC->isRecord())
16662     SetMemberAccessSpecifier(New, PrevDecl, AS);
16663 
16664   if (PrevDecl)
16665     CheckRedeclarationInModule(New, PrevDecl);
16666 
16667   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16668     New->startDefinition();
16669 
16670   ProcessDeclAttributeList(S, New, Attrs);
16671   AddPragmaAttributes(S, New);
16672 
16673   // If this has an identifier, add it to the scope stack.
16674   if (TUK == TUK_Friend) {
16675     // We might be replacing an existing declaration in the lookup tables;
16676     // if so, borrow its access specifier.
16677     if (PrevDecl)
16678       New->setAccess(PrevDecl->getAccess());
16679 
16680     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16681     DC->makeDeclVisibleInContext(New);
16682     if (Name) // can be null along some error paths
16683       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16684         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16685   } else if (Name) {
16686     S = getNonFieldDeclScope(S);
16687     PushOnScopeChains(New, S, true);
16688   } else {
16689     CurContext->addDecl(New);
16690   }
16691 
16692   // If this is the C FILE type, notify the AST context.
16693   if (IdentifierInfo *II = New->getIdentifier())
16694     if (!New->isInvalidDecl() &&
16695         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16696         II->isStr("FILE"))
16697       Context.setFILEDecl(New);
16698 
16699   if (PrevDecl)
16700     mergeDeclAttributes(New, PrevDecl);
16701 
16702   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16703     inferGslOwnerPointerAttribute(CXXRD);
16704 
16705   // If there's a #pragma GCC visibility in scope, set the visibility of this
16706   // record.
16707   AddPushedVisibilityAttribute(New);
16708 
16709   if (isMemberSpecialization && !New->isInvalidDecl())
16710     CompleteMemberSpecialization(New, Previous);
16711 
16712   OwnedDecl = true;
16713   // In C++, don't return an invalid declaration. We can't recover well from
16714   // the cases where we make the type anonymous.
16715   if (Invalid && getLangOpts().CPlusPlus) {
16716     if (New->isBeingDefined())
16717       if (auto RD = dyn_cast<RecordDecl>(New))
16718         RD->completeDefinition();
16719     return nullptr;
16720   } else if (SkipBody && SkipBody->ShouldSkip) {
16721     return SkipBody->Previous;
16722   } else {
16723     return New;
16724   }
16725 }
16726 
16727 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16728   AdjustDeclIfTemplate(TagD);
16729   TagDecl *Tag = cast<TagDecl>(TagD);
16730 
16731   // Enter the tag context.
16732   PushDeclContext(S, Tag);
16733 
16734   ActOnDocumentableDecl(TagD);
16735 
16736   // If there's a #pragma GCC visibility in scope, set the visibility of this
16737   // record.
16738   AddPushedVisibilityAttribute(Tag);
16739 }
16740 
16741 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16742   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16743     return false;
16744 
16745   // Make the previous decl visible.
16746   makeMergedDefinitionVisible(SkipBody.Previous);
16747   return true;
16748 }
16749 
16750 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16751   assert(isa<ObjCContainerDecl>(IDecl) &&
16752          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16753   DeclContext *OCD = cast<DeclContext>(IDecl);
16754   assert(OCD->getLexicalParent() == CurContext &&
16755       "The next DeclContext should be lexically contained in the current one.");
16756   CurContext = OCD;
16757   return IDecl;
16758 }
16759 
16760 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16761                                            SourceLocation FinalLoc,
16762                                            bool IsFinalSpelledSealed,
16763                                            bool IsAbstract,
16764                                            SourceLocation LBraceLoc) {
16765   AdjustDeclIfTemplate(TagD);
16766   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16767 
16768   FieldCollector->StartClass();
16769 
16770   if (!Record->getIdentifier())
16771     return;
16772 
16773   if (IsAbstract)
16774     Record->markAbstract();
16775 
16776   if (FinalLoc.isValid()) {
16777     Record->addAttr(FinalAttr::Create(
16778         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16779         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16780   }
16781   // C++ [class]p2:
16782   //   [...] The class-name is also inserted into the scope of the
16783   //   class itself; this is known as the injected-class-name. For
16784   //   purposes of access checking, the injected-class-name is treated
16785   //   as if it were a public member name.
16786   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16787       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16788       Record->getLocation(), Record->getIdentifier(),
16789       /*PrevDecl=*/nullptr,
16790       /*DelayTypeCreation=*/true);
16791   Context.getTypeDeclType(InjectedClassName, Record);
16792   InjectedClassName->setImplicit();
16793   InjectedClassName->setAccess(AS_public);
16794   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16795       InjectedClassName->setDescribedClassTemplate(Template);
16796   PushOnScopeChains(InjectedClassName, S);
16797   assert(InjectedClassName->isInjectedClassName() &&
16798          "Broken injected-class-name");
16799 }
16800 
16801 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16802                                     SourceRange BraceRange) {
16803   AdjustDeclIfTemplate(TagD);
16804   TagDecl *Tag = cast<TagDecl>(TagD);
16805   Tag->setBraceRange(BraceRange);
16806 
16807   // Make sure we "complete" the definition even it is invalid.
16808   if (Tag->isBeingDefined()) {
16809     assert(Tag->isInvalidDecl() && "We should already have completed it");
16810     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16811       RD->completeDefinition();
16812   }
16813 
16814   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16815     FieldCollector->FinishClass();
16816     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16817       auto *Def = RD->getDefinition();
16818       assert(Def && "The record is expected to have a completed definition");
16819       unsigned NumInitMethods = 0;
16820       for (auto *Method : Def->methods()) {
16821         if (!Method->getIdentifier())
16822             continue;
16823         if (Method->getName() == "__init")
16824           NumInitMethods++;
16825       }
16826       if (NumInitMethods > 1 || !Def->hasInitMethod())
16827         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16828     }
16829   }
16830 
16831   // Exit this scope of this tag's definition.
16832   PopDeclContext();
16833 
16834   if (getCurLexicalContext()->isObjCContainer() &&
16835       Tag->getDeclContext()->isFileContext())
16836     Tag->setTopLevelDeclInObjCContainer();
16837 
16838   // Notify the consumer that we've defined a tag.
16839   if (!Tag->isInvalidDecl())
16840     Consumer.HandleTagDeclDefinition(Tag);
16841 
16842   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16843   // from XLs and instead matches the XL #pragma pack(1) behavior.
16844   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16845       AlignPackStack.hasValue()) {
16846     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16847     // Only diagnose #pragma align(packed).
16848     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16849       return;
16850     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16851     if (!RD)
16852       return;
16853     // Only warn if there is at least 1 bitfield member.
16854     if (llvm::any_of(RD->fields(),
16855                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16856       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16857   }
16858 }
16859 
16860 void Sema::ActOnObjCContainerFinishDefinition() {
16861   // Exit this scope of this interface definition.
16862   PopDeclContext();
16863 }
16864 
16865 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16866   assert(DC == CurContext && "Mismatch of container contexts");
16867   OriginalLexicalContext = DC;
16868   ActOnObjCContainerFinishDefinition();
16869 }
16870 
16871 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16872   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16873   OriginalLexicalContext = nullptr;
16874 }
16875 
16876 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16877   AdjustDeclIfTemplate(TagD);
16878   TagDecl *Tag = cast<TagDecl>(TagD);
16879   Tag->setInvalidDecl();
16880 
16881   // Make sure we "complete" the definition even it is invalid.
16882   if (Tag->isBeingDefined()) {
16883     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16884       RD->completeDefinition();
16885   }
16886 
16887   // We're undoing ActOnTagStartDefinition here, not
16888   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16889   // the FieldCollector.
16890 
16891   PopDeclContext();
16892 }
16893 
16894 // Note that FieldName may be null for anonymous bitfields.
16895 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16896                                 IdentifierInfo *FieldName,
16897                                 QualType FieldTy, bool IsMsStruct,
16898                                 Expr *BitWidth, bool *ZeroWidth) {
16899   assert(BitWidth);
16900   if (BitWidth->containsErrors())
16901     return ExprError();
16902 
16903   // Default to true; that shouldn't confuse checks for emptiness
16904   if (ZeroWidth)
16905     *ZeroWidth = true;
16906 
16907   // C99 6.7.2.1p4 - verify the field type.
16908   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16909   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16910     // Handle incomplete and sizeless types with a specific error.
16911     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16912                                  diag::err_field_incomplete_or_sizeless))
16913       return ExprError();
16914     if (FieldName)
16915       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16916         << FieldName << FieldTy << BitWidth->getSourceRange();
16917     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16918       << FieldTy << BitWidth->getSourceRange();
16919   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16920                                              UPPC_BitFieldWidth))
16921     return ExprError();
16922 
16923   // If the bit-width is type- or value-dependent, don't try to check
16924   // it now.
16925   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16926     return BitWidth;
16927 
16928   llvm::APSInt Value;
16929   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16930   if (ICE.isInvalid())
16931     return ICE;
16932   BitWidth = ICE.get();
16933 
16934   if (Value != 0 && ZeroWidth)
16935     *ZeroWidth = false;
16936 
16937   // Zero-width bitfield is ok for anonymous field.
16938   if (Value == 0 && FieldName)
16939     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16940 
16941   if (Value.isSigned() && Value.isNegative()) {
16942     if (FieldName)
16943       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16944                << FieldName << toString(Value, 10);
16945     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16946       << toString(Value, 10);
16947   }
16948 
16949   // The size of the bit-field must not exceed our maximum permitted object
16950   // size.
16951   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16952     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16953            << !FieldName << FieldName << toString(Value, 10);
16954   }
16955 
16956   if (!FieldTy->isDependentType()) {
16957     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16958     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16959     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16960 
16961     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16962     // ABI.
16963     bool CStdConstraintViolation =
16964         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16965     bool MSBitfieldViolation =
16966         Value.ugt(TypeStorageSize) &&
16967         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16968     if (CStdConstraintViolation || MSBitfieldViolation) {
16969       unsigned DiagWidth =
16970           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16971       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16972              << (bool)FieldName << FieldName << toString(Value, 10)
16973              << !CStdConstraintViolation << DiagWidth;
16974     }
16975 
16976     // Warn on types where the user might conceivably expect to get all
16977     // specified bits as value bits: that's all integral types other than
16978     // 'bool'.
16979     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16980       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16981           << FieldName << toString(Value, 10)
16982           << (unsigned)TypeWidth;
16983     }
16984   }
16985 
16986   return BitWidth;
16987 }
16988 
16989 /// ActOnField - Each field of a C struct/union is passed into this in order
16990 /// to create a FieldDecl object for it.
16991 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16992                        Declarator &D, Expr *BitfieldWidth) {
16993   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16994                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16995                                /*InitStyle=*/ICIS_NoInit, AS_public);
16996   return Res;
16997 }
16998 
16999 /// HandleField - Analyze a field of a C struct or a C++ data member.
17000 ///
17001 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17002                              SourceLocation DeclStart,
17003                              Declarator &D, Expr *BitWidth,
17004                              InClassInitStyle InitStyle,
17005                              AccessSpecifier AS) {
17006   if (D.isDecompositionDeclarator()) {
17007     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17008     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17009       << Decomp.getSourceRange();
17010     return nullptr;
17011   }
17012 
17013   IdentifierInfo *II = D.getIdentifier();
17014   SourceLocation Loc = DeclStart;
17015   if (II) Loc = D.getIdentifierLoc();
17016 
17017   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17018   QualType T = TInfo->getType();
17019   if (getLangOpts().CPlusPlus) {
17020     CheckExtraCXXDefaultArguments(D);
17021 
17022     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17023                                         UPPC_DataMemberType)) {
17024       D.setInvalidType();
17025       T = Context.IntTy;
17026       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17027     }
17028   }
17029 
17030   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17031 
17032   if (D.getDeclSpec().isInlineSpecified())
17033     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17034         << getLangOpts().CPlusPlus17;
17035   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17036     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17037          diag::err_invalid_thread)
17038       << DeclSpec::getSpecifierName(TSCS);
17039 
17040   // Check to see if this name was declared as a member previously
17041   NamedDecl *PrevDecl = nullptr;
17042   LookupResult Previous(*this, II, Loc, LookupMemberName,
17043                         ForVisibleRedeclaration);
17044   LookupName(Previous, S);
17045   switch (Previous.getResultKind()) {
17046     case LookupResult::Found:
17047     case LookupResult::FoundUnresolvedValue:
17048       PrevDecl = Previous.getAsSingle<NamedDecl>();
17049       break;
17050 
17051     case LookupResult::FoundOverloaded:
17052       PrevDecl = Previous.getRepresentativeDecl();
17053       break;
17054 
17055     case LookupResult::NotFound:
17056     case LookupResult::NotFoundInCurrentInstantiation:
17057     case LookupResult::Ambiguous:
17058       break;
17059   }
17060   Previous.suppressDiagnostics();
17061 
17062   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17063     // Maybe we will complain about the shadowed template parameter.
17064     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17065     // Just pretend that we didn't see the previous declaration.
17066     PrevDecl = nullptr;
17067   }
17068 
17069   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17070     PrevDecl = nullptr;
17071 
17072   bool Mutable
17073     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17074   SourceLocation TSSL = D.getBeginLoc();
17075   FieldDecl *NewFD
17076     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17077                      TSSL, AS, PrevDecl, &D);
17078 
17079   if (NewFD->isInvalidDecl())
17080     Record->setInvalidDecl();
17081 
17082   if (D.getDeclSpec().isModulePrivateSpecified())
17083     NewFD->setModulePrivate();
17084 
17085   if (NewFD->isInvalidDecl() && PrevDecl) {
17086     // Don't introduce NewFD into scope; there's already something
17087     // with the same name in the same scope.
17088   } else if (II) {
17089     PushOnScopeChains(NewFD, S);
17090   } else
17091     Record->addDecl(NewFD);
17092 
17093   return NewFD;
17094 }
17095 
17096 /// Build a new FieldDecl and check its well-formedness.
17097 ///
17098 /// This routine builds a new FieldDecl given the fields name, type,
17099 /// record, etc. \p PrevDecl should refer to any previous declaration
17100 /// with the same name and in the same scope as the field to be
17101 /// created.
17102 ///
17103 /// \returns a new FieldDecl.
17104 ///
17105 /// \todo The Declarator argument is a hack. It will be removed once
17106 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17107                                 TypeSourceInfo *TInfo,
17108                                 RecordDecl *Record, SourceLocation Loc,
17109                                 bool Mutable, Expr *BitWidth,
17110                                 InClassInitStyle InitStyle,
17111                                 SourceLocation TSSL,
17112                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17113                                 Declarator *D) {
17114   IdentifierInfo *II = Name.getAsIdentifierInfo();
17115   bool InvalidDecl = false;
17116   if (D) InvalidDecl = D->isInvalidType();
17117 
17118   // If we receive a broken type, recover by assuming 'int' and
17119   // marking this declaration as invalid.
17120   if (T.isNull() || T->containsErrors()) {
17121     InvalidDecl = true;
17122     T = Context.IntTy;
17123   }
17124 
17125   QualType EltTy = Context.getBaseElementType(T);
17126   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17127     if (RequireCompleteSizedType(Loc, EltTy,
17128                                  diag::err_field_incomplete_or_sizeless)) {
17129       // Fields of incomplete type force their record to be invalid.
17130       Record->setInvalidDecl();
17131       InvalidDecl = true;
17132     } else {
17133       NamedDecl *Def;
17134       EltTy->isIncompleteType(&Def);
17135       if (Def && Def->isInvalidDecl()) {
17136         Record->setInvalidDecl();
17137         InvalidDecl = true;
17138       }
17139     }
17140   }
17141 
17142   // TR 18037 does not allow fields to be declared with address space
17143   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17144       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17145     Diag(Loc, diag::err_field_with_address_space);
17146     Record->setInvalidDecl();
17147     InvalidDecl = true;
17148   }
17149 
17150   if (LangOpts.OpenCL) {
17151     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17152     // used as structure or union field: image, sampler, event or block types.
17153     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17154         T->isBlockPointerType()) {
17155       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17156       Record->setInvalidDecl();
17157       InvalidDecl = true;
17158     }
17159     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17160     // is enabled.
17161     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17162                         "__cl_clang_bitfields", LangOpts)) {
17163       Diag(Loc, diag::err_opencl_bitfields);
17164       InvalidDecl = true;
17165     }
17166   }
17167 
17168   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17169   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17170       T.hasQualifiers()) {
17171     InvalidDecl = true;
17172     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17173   }
17174 
17175   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17176   // than a variably modified type.
17177   if (!InvalidDecl && T->isVariablyModifiedType()) {
17178     if (!tryToFixVariablyModifiedVarType(
17179             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17180       InvalidDecl = true;
17181   }
17182 
17183   // Fields can not have abstract class types
17184   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17185                                              diag::err_abstract_type_in_decl,
17186                                              AbstractFieldType))
17187     InvalidDecl = true;
17188 
17189   bool ZeroWidth = false;
17190   if (InvalidDecl)
17191     BitWidth = nullptr;
17192   // If this is declared as a bit-field, check the bit-field.
17193   if (BitWidth) {
17194     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17195                               &ZeroWidth).get();
17196     if (!BitWidth) {
17197       InvalidDecl = true;
17198       BitWidth = nullptr;
17199       ZeroWidth = false;
17200     }
17201   }
17202 
17203   // Check that 'mutable' is consistent with the type of the declaration.
17204   if (!InvalidDecl && Mutable) {
17205     unsigned DiagID = 0;
17206     if (T->isReferenceType())
17207       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17208                                         : diag::err_mutable_reference;
17209     else if (T.isConstQualified())
17210       DiagID = diag::err_mutable_const;
17211 
17212     if (DiagID) {
17213       SourceLocation ErrLoc = Loc;
17214       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17215         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17216       Diag(ErrLoc, DiagID);
17217       if (DiagID != diag::ext_mutable_reference) {
17218         Mutable = false;
17219         InvalidDecl = true;
17220       }
17221     }
17222   }
17223 
17224   // C++11 [class.union]p8 (DR1460):
17225   //   At most one variant member of a union may have a
17226   //   brace-or-equal-initializer.
17227   if (InitStyle != ICIS_NoInit)
17228     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17229 
17230   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17231                                        BitWidth, Mutable, InitStyle);
17232   if (InvalidDecl)
17233     NewFD->setInvalidDecl();
17234 
17235   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17236     Diag(Loc, diag::err_duplicate_member) << II;
17237     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17238     NewFD->setInvalidDecl();
17239   }
17240 
17241   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17242     if (Record->isUnion()) {
17243       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17244         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17245         if (RDecl->getDefinition()) {
17246           // C++ [class.union]p1: An object of a class with a non-trivial
17247           // constructor, a non-trivial copy constructor, a non-trivial
17248           // destructor, or a non-trivial copy assignment operator
17249           // cannot be a member of a union, nor can an array of such
17250           // objects.
17251           if (CheckNontrivialField(NewFD))
17252             NewFD->setInvalidDecl();
17253         }
17254       }
17255 
17256       // C++ [class.union]p1: If a union contains a member of reference type,
17257       // the program is ill-formed, except when compiling with MSVC extensions
17258       // enabled.
17259       if (EltTy->isReferenceType()) {
17260         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17261                                     diag::ext_union_member_of_reference_type :
17262                                     diag::err_union_member_of_reference_type)
17263           << NewFD->getDeclName() << EltTy;
17264         if (!getLangOpts().MicrosoftExt)
17265           NewFD->setInvalidDecl();
17266       }
17267     }
17268   }
17269 
17270   // FIXME: We need to pass in the attributes given an AST
17271   // representation, not a parser representation.
17272   if (D) {
17273     // FIXME: The current scope is almost... but not entirely... correct here.
17274     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17275 
17276     if (NewFD->hasAttrs())
17277       CheckAlignasUnderalignment(NewFD);
17278   }
17279 
17280   // In auto-retain/release, infer strong retension for fields of
17281   // retainable type.
17282   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17283     NewFD->setInvalidDecl();
17284 
17285   if (T.isObjCGCWeak())
17286     Diag(Loc, diag::warn_attribute_weak_on_field);
17287 
17288   // PPC MMA non-pointer types are not allowed as field types.
17289   if (Context.getTargetInfo().getTriple().isPPC64() &&
17290       CheckPPCMMAType(T, NewFD->getLocation()))
17291     NewFD->setInvalidDecl();
17292 
17293   NewFD->setAccess(AS);
17294   return NewFD;
17295 }
17296 
17297 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17298   assert(FD);
17299   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17300 
17301   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17302     return false;
17303 
17304   QualType EltTy = Context.getBaseElementType(FD->getType());
17305   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17306     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17307     if (RDecl->getDefinition()) {
17308       // We check for copy constructors before constructors
17309       // because otherwise we'll never get complaints about
17310       // copy constructors.
17311 
17312       CXXSpecialMember member = CXXInvalid;
17313       // We're required to check for any non-trivial constructors. Since the
17314       // implicit default constructor is suppressed if there are any
17315       // user-declared constructors, we just need to check that there is a
17316       // trivial default constructor and a trivial copy constructor. (We don't
17317       // worry about move constructors here, since this is a C++98 check.)
17318       if (RDecl->hasNonTrivialCopyConstructor())
17319         member = CXXCopyConstructor;
17320       else if (!RDecl->hasTrivialDefaultConstructor())
17321         member = CXXDefaultConstructor;
17322       else if (RDecl->hasNonTrivialCopyAssignment())
17323         member = CXXCopyAssignment;
17324       else if (RDecl->hasNonTrivialDestructor())
17325         member = CXXDestructor;
17326 
17327       if (member != CXXInvalid) {
17328         if (!getLangOpts().CPlusPlus11 &&
17329             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17330           // Objective-C++ ARC: it is an error to have a non-trivial field of
17331           // a union. However, system headers in Objective-C programs
17332           // occasionally have Objective-C lifetime objects within unions,
17333           // and rather than cause the program to fail, we make those
17334           // members unavailable.
17335           SourceLocation Loc = FD->getLocation();
17336           if (getSourceManager().isInSystemHeader(Loc)) {
17337             if (!FD->hasAttr<UnavailableAttr>())
17338               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17339                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17340             return false;
17341           }
17342         }
17343 
17344         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17345                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17346                diag::err_illegal_union_or_anon_struct_member)
17347           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17348         DiagnoseNontrivial(RDecl, member);
17349         return !getLangOpts().CPlusPlus11;
17350       }
17351     }
17352   }
17353 
17354   return false;
17355 }
17356 
17357 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17358 ///  AST enum value.
17359 static ObjCIvarDecl::AccessControl
17360 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17361   switch (ivarVisibility) {
17362   default: llvm_unreachable("Unknown visitibility kind");
17363   case tok::objc_private: return ObjCIvarDecl::Private;
17364   case tok::objc_public: return ObjCIvarDecl::Public;
17365   case tok::objc_protected: return ObjCIvarDecl::Protected;
17366   case tok::objc_package: return ObjCIvarDecl::Package;
17367   }
17368 }
17369 
17370 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17371 /// in order to create an IvarDecl object for it.
17372 Decl *Sema::ActOnIvar(Scope *S,
17373                                 SourceLocation DeclStart,
17374                                 Declarator &D, Expr *BitfieldWidth,
17375                                 tok::ObjCKeywordKind Visibility) {
17376 
17377   IdentifierInfo *II = D.getIdentifier();
17378   Expr *BitWidth = (Expr*)BitfieldWidth;
17379   SourceLocation Loc = DeclStart;
17380   if (II) Loc = D.getIdentifierLoc();
17381 
17382   // FIXME: Unnamed fields can be handled in various different ways, for
17383   // example, unnamed unions inject all members into the struct namespace!
17384 
17385   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17386   QualType T = TInfo->getType();
17387 
17388   if (BitWidth) {
17389     // 6.7.2.1p3, 6.7.2.1p4
17390     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17391     if (!BitWidth)
17392       D.setInvalidType();
17393   } else {
17394     // Not a bitfield.
17395 
17396     // validate II.
17397 
17398   }
17399   if (T->isReferenceType()) {
17400     Diag(Loc, diag::err_ivar_reference_type);
17401     D.setInvalidType();
17402   }
17403   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17404   // than a variably modified type.
17405   else if (T->isVariablyModifiedType()) {
17406     if (!tryToFixVariablyModifiedVarType(
17407             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17408       D.setInvalidType();
17409   }
17410 
17411   // Get the visibility (access control) for this ivar.
17412   ObjCIvarDecl::AccessControl ac =
17413     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17414                                         : ObjCIvarDecl::None;
17415   // Must set ivar's DeclContext to its enclosing interface.
17416   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17417   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17418     return nullptr;
17419   ObjCContainerDecl *EnclosingContext;
17420   if (ObjCImplementationDecl *IMPDecl =
17421       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17422     if (LangOpts.ObjCRuntime.isFragile()) {
17423     // Case of ivar declared in an implementation. Context is that of its class.
17424       EnclosingContext = IMPDecl->getClassInterface();
17425       assert(EnclosingContext && "Implementation has no class interface!");
17426     }
17427     else
17428       EnclosingContext = EnclosingDecl;
17429   } else {
17430     if (ObjCCategoryDecl *CDecl =
17431         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17432       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17433         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17434         return nullptr;
17435       }
17436     }
17437     EnclosingContext = EnclosingDecl;
17438   }
17439 
17440   // Construct the decl.
17441   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17442                                              DeclStart, Loc, II, T,
17443                                              TInfo, ac, (Expr *)BitfieldWidth);
17444 
17445   if (II) {
17446     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17447                                            ForVisibleRedeclaration);
17448     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17449         && !isa<TagDecl>(PrevDecl)) {
17450       Diag(Loc, diag::err_duplicate_member) << II;
17451       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17452       NewID->setInvalidDecl();
17453     }
17454   }
17455 
17456   // Process attributes attached to the ivar.
17457   ProcessDeclAttributes(S, NewID, D);
17458 
17459   if (D.isInvalidType())
17460     NewID->setInvalidDecl();
17461 
17462   // In ARC, infer 'retaining' for ivars of retainable type.
17463   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17464     NewID->setInvalidDecl();
17465 
17466   if (D.getDeclSpec().isModulePrivateSpecified())
17467     NewID->setModulePrivate();
17468 
17469   if (II) {
17470     // FIXME: When interfaces are DeclContexts, we'll need to add
17471     // these to the interface.
17472     S->AddDecl(NewID);
17473     IdResolver.AddDecl(NewID);
17474   }
17475 
17476   if (LangOpts.ObjCRuntime.isNonFragile() &&
17477       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17478     Diag(Loc, diag::warn_ivars_in_interface);
17479 
17480   return NewID;
17481 }
17482 
17483 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17484 /// class and class extensions. For every class \@interface and class
17485 /// extension \@interface, if the last ivar is a bitfield of any type,
17486 /// then add an implicit `char :0` ivar to the end of that interface.
17487 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17488                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17489   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17490     return;
17491 
17492   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17493   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17494 
17495   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17496     return;
17497   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17498   if (!ID) {
17499     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17500       if (!CD->IsClassExtension())
17501         return;
17502     }
17503     // No need to add this to end of @implementation.
17504     else
17505       return;
17506   }
17507   // All conditions are met. Add a new bitfield to the tail end of ivars.
17508   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17509   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17510 
17511   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17512                               DeclLoc, DeclLoc, nullptr,
17513                               Context.CharTy,
17514                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17515                                                                DeclLoc),
17516                               ObjCIvarDecl::Private, BW,
17517                               true);
17518   AllIvarDecls.push_back(Ivar);
17519 }
17520 
17521 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17522                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17523                        SourceLocation RBrac,
17524                        const ParsedAttributesView &Attrs) {
17525   assert(EnclosingDecl && "missing record or interface decl");
17526 
17527   // If this is an Objective-C @implementation or category and we have
17528   // new fields here we should reset the layout of the interface since
17529   // it will now change.
17530   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17531     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17532     switch (DC->getKind()) {
17533     default: break;
17534     case Decl::ObjCCategory:
17535       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17536       break;
17537     case Decl::ObjCImplementation:
17538       Context.
17539         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17540       break;
17541     }
17542   }
17543 
17544   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17545   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17546 
17547   // Start counting up the number of named members; make sure to include
17548   // members of anonymous structs and unions in the total.
17549   unsigned NumNamedMembers = 0;
17550   if (Record) {
17551     for (const auto *I : Record->decls()) {
17552       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17553         if (IFD->getDeclName())
17554           ++NumNamedMembers;
17555     }
17556   }
17557 
17558   // Verify that all the fields are okay.
17559   SmallVector<FieldDecl*, 32> RecFields;
17560 
17561   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17562        i != end; ++i) {
17563     FieldDecl *FD = cast<FieldDecl>(*i);
17564 
17565     // Get the type for the field.
17566     const Type *FDTy = FD->getType().getTypePtr();
17567 
17568     if (!FD->isAnonymousStructOrUnion()) {
17569       // Remember all fields written by the user.
17570       RecFields.push_back(FD);
17571     }
17572 
17573     // If the field is already invalid for some reason, don't emit more
17574     // diagnostics about it.
17575     if (FD->isInvalidDecl()) {
17576       EnclosingDecl->setInvalidDecl();
17577       continue;
17578     }
17579 
17580     // C99 6.7.2.1p2:
17581     //   A structure or union shall not contain a member with
17582     //   incomplete or function type (hence, a structure shall not
17583     //   contain an instance of itself, but may contain a pointer to
17584     //   an instance of itself), except that the last member of a
17585     //   structure with more than one named member may have incomplete
17586     //   array type; such a structure (and any union containing,
17587     //   possibly recursively, a member that is such a structure)
17588     //   shall not be a member of a structure or an element of an
17589     //   array.
17590     bool IsLastField = (i + 1 == Fields.end());
17591     if (FDTy->isFunctionType()) {
17592       // Field declared as a function.
17593       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17594         << FD->getDeclName();
17595       FD->setInvalidDecl();
17596       EnclosingDecl->setInvalidDecl();
17597       continue;
17598     } else if (FDTy->isIncompleteArrayType() &&
17599                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17600       if (Record) {
17601         // Flexible array member.
17602         // Microsoft and g++ is more permissive regarding flexible array.
17603         // It will accept flexible array in union and also
17604         // as the sole element of a struct/class.
17605         unsigned DiagID = 0;
17606         if (!Record->isUnion() && !IsLastField) {
17607           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17608             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17609           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17610           FD->setInvalidDecl();
17611           EnclosingDecl->setInvalidDecl();
17612           continue;
17613         } else if (Record->isUnion())
17614           DiagID = getLangOpts().MicrosoftExt
17615                        ? diag::ext_flexible_array_union_ms
17616                        : getLangOpts().CPlusPlus
17617                              ? diag::ext_flexible_array_union_gnu
17618                              : diag::err_flexible_array_union;
17619         else if (NumNamedMembers < 1)
17620           DiagID = getLangOpts().MicrosoftExt
17621                        ? diag::ext_flexible_array_empty_aggregate_ms
17622                        : getLangOpts().CPlusPlus
17623                              ? diag::ext_flexible_array_empty_aggregate_gnu
17624                              : diag::err_flexible_array_empty_aggregate;
17625 
17626         if (DiagID)
17627           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17628                                           << Record->getTagKind();
17629         // While the layout of types that contain virtual bases is not specified
17630         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17631         // virtual bases after the derived members.  This would make a flexible
17632         // array member declared at the end of an object not adjacent to the end
17633         // of the type.
17634         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17635           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17636               << FD->getDeclName() << Record->getTagKind();
17637         if (!getLangOpts().C99)
17638           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17639             << FD->getDeclName() << Record->getTagKind();
17640 
17641         // If the element type has a non-trivial destructor, we would not
17642         // implicitly destroy the elements, so disallow it for now.
17643         //
17644         // FIXME: GCC allows this. We should probably either implicitly delete
17645         // the destructor of the containing class, or just allow this.
17646         QualType BaseElem = Context.getBaseElementType(FD->getType());
17647         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17648           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17649             << FD->getDeclName() << FD->getType();
17650           FD->setInvalidDecl();
17651           EnclosingDecl->setInvalidDecl();
17652           continue;
17653         }
17654         // Okay, we have a legal flexible array member at the end of the struct.
17655         Record->setHasFlexibleArrayMember(true);
17656       } else {
17657         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17658         // unless they are followed by another ivar. That check is done
17659         // elsewhere, after synthesized ivars are known.
17660       }
17661     } else if (!FDTy->isDependentType() &&
17662                RequireCompleteSizedType(
17663                    FD->getLocation(), FD->getType(),
17664                    diag::err_field_incomplete_or_sizeless)) {
17665       // Incomplete type
17666       FD->setInvalidDecl();
17667       EnclosingDecl->setInvalidDecl();
17668       continue;
17669     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17670       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17671         // A type which contains a flexible array member is considered to be a
17672         // flexible array member.
17673         Record->setHasFlexibleArrayMember(true);
17674         if (!Record->isUnion()) {
17675           // If this is a struct/class and this is not the last element, reject
17676           // it.  Note that GCC supports variable sized arrays in the middle of
17677           // structures.
17678           if (!IsLastField)
17679             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17680               << FD->getDeclName() << FD->getType();
17681           else {
17682             // We support flexible arrays at the end of structs in
17683             // other structs as an extension.
17684             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17685               << FD->getDeclName();
17686           }
17687         }
17688       }
17689       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17690           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17691                                  diag::err_abstract_type_in_decl,
17692                                  AbstractIvarType)) {
17693         // Ivars can not have abstract class types
17694         FD->setInvalidDecl();
17695       }
17696       if (Record && FDTTy->getDecl()->hasObjectMember())
17697         Record->setHasObjectMember(true);
17698       if (Record && FDTTy->getDecl()->hasVolatileMember())
17699         Record->setHasVolatileMember(true);
17700     } else if (FDTy->isObjCObjectType()) {
17701       /// A field cannot be an Objective-c object
17702       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17703         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17704       QualType T = Context.getObjCObjectPointerType(FD->getType());
17705       FD->setType(T);
17706     } else if (Record && Record->isUnion() &&
17707                FD->getType().hasNonTrivialObjCLifetime() &&
17708                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17709                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17710                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17711                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17712       // For backward compatibility, fields of C unions declared in system
17713       // headers that have non-trivial ObjC ownership qualifications are marked
17714       // as unavailable unless the qualifier is explicit and __strong. This can
17715       // break ABI compatibility between programs compiled with ARC and MRR, but
17716       // is a better option than rejecting programs using those unions under
17717       // ARC.
17718       FD->addAttr(UnavailableAttr::CreateImplicit(
17719           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17720           FD->getLocation()));
17721     } else if (getLangOpts().ObjC &&
17722                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17723                !Record->hasObjectMember()) {
17724       if (FD->getType()->isObjCObjectPointerType() ||
17725           FD->getType().isObjCGCStrong())
17726         Record->setHasObjectMember(true);
17727       else if (Context.getAsArrayType(FD->getType())) {
17728         QualType BaseType = Context.getBaseElementType(FD->getType());
17729         if (BaseType->isRecordType() &&
17730             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17731           Record->setHasObjectMember(true);
17732         else if (BaseType->isObjCObjectPointerType() ||
17733                  BaseType.isObjCGCStrong())
17734                Record->setHasObjectMember(true);
17735       }
17736     }
17737 
17738     if (Record && !getLangOpts().CPlusPlus &&
17739         !shouldIgnoreForRecordTriviality(FD)) {
17740       QualType FT = FD->getType();
17741       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17742         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17743         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17744             Record->isUnion())
17745           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17746       }
17747       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17748       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17749         Record->setNonTrivialToPrimitiveCopy(true);
17750         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17751           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17752       }
17753       if (FT.isDestructedType()) {
17754         Record->setNonTrivialToPrimitiveDestroy(true);
17755         Record->setParamDestroyedInCallee(true);
17756         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17757           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17758       }
17759 
17760       if (const auto *RT = FT->getAs<RecordType>()) {
17761         if (RT->getDecl()->getArgPassingRestrictions() ==
17762             RecordDecl::APK_CanNeverPassInRegs)
17763           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17764       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17765         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17766     }
17767 
17768     if (Record && FD->getType().isVolatileQualified())
17769       Record->setHasVolatileMember(true);
17770     // Keep track of the number of named members.
17771     if (FD->getIdentifier())
17772       ++NumNamedMembers;
17773   }
17774 
17775   // Okay, we successfully defined 'Record'.
17776   if (Record) {
17777     bool Completed = false;
17778     if (CXXRecord) {
17779       if (!CXXRecord->isInvalidDecl()) {
17780         // Set access bits correctly on the directly-declared conversions.
17781         for (CXXRecordDecl::conversion_iterator
17782                I = CXXRecord->conversion_begin(),
17783                E = CXXRecord->conversion_end(); I != E; ++I)
17784           I.setAccess((*I)->getAccess());
17785       }
17786 
17787       // Add any implicitly-declared members to this class.
17788       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17789 
17790       if (!CXXRecord->isDependentType()) {
17791         if (!CXXRecord->isInvalidDecl()) {
17792           // If we have virtual base classes, we may end up finding multiple
17793           // final overriders for a given virtual function. Check for this
17794           // problem now.
17795           if (CXXRecord->getNumVBases()) {
17796             CXXFinalOverriderMap FinalOverriders;
17797             CXXRecord->getFinalOverriders(FinalOverriders);
17798 
17799             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17800                                              MEnd = FinalOverriders.end();
17801                  M != MEnd; ++M) {
17802               for (OverridingMethods::iterator SO = M->second.begin(),
17803                                             SOEnd = M->second.end();
17804                    SO != SOEnd; ++SO) {
17805                 assert(SO->second.size() > 0 &&
17806                        "Virtual function without overriding functions?");
17807                 if (SO->second.size() == 1)
17808                   continue;
17809 
17810                 // C++ [class.virtual]p2:
17811                 //   In a derived class, if a virtual member function of a base
17812                 //   class subobject has more than one final overrider the
17813                 //   program is ill-formed.
17814                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17815                   << (const NamedDecl *)M->first << Record;
17816                 Diag(M->first->getLocation(),
17817                      diag::note_overridden_virtual_function);
17818                 for (OverridingMethods::overriding_iterator
17819                           OM = SO->second.begin(),
17820                        OMEnd = SO->second.end();
17821                      OM != OMEnd; ++OM)
17822                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17823                     << (const NamedDecl *)M->first << OM->Method->getParent();
17824 
17825                 Record->setInvalidDecl();
17826               }
17827             }
17828             CXXRecord->completeDefinition(&FinalOverriders);
17829             Completed = true;
17830           }
17831         }
17832       }
17833     }
17834 
17835     if (!Completed)
17836       Record->completeDefinition();
17837 
17838     // Handle attributes before checking the layout.
17839     ProcessDeclAttributeList(S, Record, Attrs);
17840 
17841     // We may have deferred checking for a deleted destructor. Check now.
17842     if (CXXRecord) {
17843       auto *Dtor = CXXRecord->getDestructor();
17844       if (Dtor && Dtor->isImplicit() &&
17845           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17846         CXXRecord->setImplicitDestructorIsDeleted();
17847         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17848       }
17849     }
17850 
17851     if (Record->hasAttrs()) {
17852       CheckAlignasUnderalignment(Record);
17853 
17854       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17855         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17856                                            IA->getRange(), IA->getBestCase(),
17857                                            IA->getInheritanceModel());
17858     }
17859 
17860     // Check if the structure/union declaration is a type that can have zero
17861     // size in C. For C this is a language extension, for C++ it may cause
17862     // compatibility problems.
17863     bool CheckForZeroSize;
17864     if (!getLangOpts().CPlusPlus) {
17865       CheckForZeroSize = true;
17866     } else {
17867       // For C++ filter out types that cannot be referenced in C code.
17868       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17869       CheckForZeroSize =
17870           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17871           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17872           CXXRecord->isCLike();
17873     }
17874     if (CheckForZeroSize) {
17875       bool ZeroSize = true;
17876       bool IsEmpty = true;
17877       unsigned NonBitFields = 0;
17878       for (RecordDecl::field_iterator I = Record->field_begin(),
17879                                       E = Record->field_end();
17880            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17881         IsEmpty = false;
17882         if (I->isUnnamedBitfield()) {
17883           if (!I->isZeroLengthBitField(Context))
17884             ZeroSize = false;
17885         } else {
17886           ++NonBitFields;
17887           QualType FieldType = I->getType();
17888           if (FieldType->isIncompleteType() ||
17889               !Context.getTypeSizeInChars(FieldType).isZero())
17890             ZeroSize = false;
17891         }
17892       }
17893 
17894       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17895       // allowed in C++, but warn if its declaration is inside
17896       // extern "C" block.
17897       if (ZeroSize) {
17898         Diag(RecLoc, getLangOpts().CPlusPlus ?
17899                          diag::warn_zero_size_struct_union_in_extern_c :
17900                          diag::warn_zero_size_struct_union_compat)
17901           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17902       }
17903 
17904       // Structs without named members are extension in C (C99 6.7.2.1p7),
17905       // but are accepted by GCC.
17906       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17907         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17908                                diag::ext_no_named_members_in_struct_union)
17909           << Record->isUnion();
17910       }
17911     }
17912   } else {
17913     ObjCIvarDecl **ClsFields =
17914       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17915     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17916       ID->setEndOfDefinitionLoc(RBrac);
17917       // Add ivar's to class's DeclContext.
17918       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17919         ClsFields[i]->setLexicalDeclContext(ID);
17920         ID->addDecl(ClsFields[i]);
17921       }
17922       // Must enforce the rule that ivars in the base classes may not be
17923       // duplicates.
17924       if (ID->getSuperClass())
17925         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17926     } else if (ObjCImplementationDecl *IMPDecl =
17927                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17928       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17929       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17930         // Ivar declared in @implementation never belongs to the implementation.
17931         // Only it is in implementation's lexical context.
17932         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17933       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17934       IMPDecl->setIvarLBraceLoc(LBrac);
17935       IMPDecl->setIvarRBraceLoc(RBrac);
17936     } else if (ObjCCategoryDecl *CDecl =
17937                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17938       // case of ivars in class extension; all other cases have been
17939       // reported as errors elsewhere.
17940       // FIXME. Class extension does not have a LocEnd field.
17941       // CDecl->setLocEnd(RBrac);
17942       // Add ivar's to class extension's DeclContext.
17943       // Diagnose redeclaration of private ivars.
17944       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17945       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17946         if (IDecl) {
17947           if (const ObjCIvarDecl *ClsIvar =
17948               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17949             Diag(ClsFields[i]->getLocation(),
17950                  diag::err_duplicate_ivar_declaration);
17951             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17952             continue;
17953           }
17954           for (const auto *Ext : IDecl->known_extensions()) {
17955             if (const ObjCIvarDecl *ClsExtIvar
17956                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17957               Diag(ClsFields[i]->getLocation(),
17958                    diag::err_duplicate_ivar_declaration);
17959               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17960               continue;
17961             }
17962           }
17963         }
17964         ClsFields[i]->setLexicalDeclContext(CDecl);
17965         CDecl->addDecl(ClsFields[i]);
17966       }
17967       CDecl->setIvarLBraceLoc(LBrac);
17968       CDecl->setIvarRBraceLoc(RBrac);
17969     }
17970   }
17971 }
17972 
17973 /// Determine whether the given integral value is representable within
17974 /// the given type T.
17975 static bool isRepresentableIntegerValue(ASTContext &Context,
17976                                         llvm::APSInt &Value,
17977                                         QualType T) {
17978   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17979          "Integral type required!");
17980   unsigned BitWidth = Context.getIntWidth(T);
17981 
17982   if (Value.isUnsigned() || Value.isNonNegative()) {
17983     if (T->isSignedIntegerOrEnumerationType())
17984       --BitWidth;
17985     return Value.getActiveBits() <= BitWidth;
17986   }
17987   return Value.getMinSignedBits() <= BitWidth;
17988 }
17989 
17990 // Given an integral type, return the next larger integral type
17991 // (or a NULL type of no such type exists).
17992 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17993   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17994   // enum checking below.
17995   assert((T->isIntegralType(Context) ||
17996          T->isEnumeralType()) && "Integral type required!");
17997   const unsigned NumTypes = 4;
17998   QualType SignedIntegralTypes[NumTypes] = {
17999     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18000   };
18001   QualType UnsignedIntegralTypes[NumTypes] = {
18002     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18003     Context.UnsignedLongLongTy
18004   };
18005 
18006   unsigned BitWidth = Context.getTypeSize(T);
18007   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18008                                                         : UnsignedIntegralTypes;
18009   for (unsigned I = 0; I != NumTypes; ++I)
18010     if (Context.getTypeSize(Types[I]) > BitWidth)
18011       return Types[I];
18012 
18013   return QualType();
18014 }
18015 
18016 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18017                                           EnumConstantDecl *LastEnumConst,
18018                                           SourceLocation IdLoc,
18019                                           IdentifierInfo *Id,
18020                                           Expr *Val) {
18021   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18022   llvm::APSInt EnumVal(IntWidth);
18023   QualType EltTy;
18024 
18025   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18026     Val = nullptr;
18027 
18028   if (Val)
18029     Val = DefaultLvalueConversion(Val).get();
18030 
18031   if (Val) {
18032     if (Enum->isDependentType() || Val->isTypeDependent() ||
18033         Val->containsErrors())
18034       EltTy = Context.DependentTy;
18035     else {
18036       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18037       // underlying type, but do allow it in all other contexts.
18038       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18039         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18040         // constant-expression in the enumerator-definition shall be a converted
18041         // constant expression of the underlying type.
18042         EltTy = Enum->getIntegerType();
18043         ExprResult Converted =
18044           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18045                                            CCEK_Enumerator);
18046         if (Converted.isInvalid())
18047           Val = nullptr;
18048         else
18049           Val = Converted.get();
18050       } else if (!Val->isValueDependent() &&
18051                  !(Val =
18052                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18053                            .get())) {
18054         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18055       } else {
18056         if (Enum->isComplete()) {
18057           EltTy = Enum->getIntegerType();
18058 
18059           // In Obj-C and Microsoft mode, require the enumeration value to be
18060           // representable in the underlying type of the enumeration. In C++11,
18061           // we perform a non-narrowing conversion as part of converted constant
18062           // expression checking.
18063           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18064             if (Context.getTargetInfo()
18065                     .getTriple()
18066                     .isWindowsMSVCEnvironment()) {
18067               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18068             } else {
18069               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18070             }
18071           }
18072 
18073           // Cast to the underlying type.
18074           Val = ImpCastExprToType(Val, EltTy,
18075                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18076                                                          : CK_IntegralCast)
18077                     .get();
18078         } else if (getLangOpts().CPlusPlus) {
18079           // C++11 [dcl.enum]p5:
18080           //   If the underlying type is not fixed, the type of each enumerator
18081           //   is the type of its initializing value:
18082           //     - If an initializer is specified for an enumerator, the
18083           //       initializing value has the same type as the expression.
18084           EltTy = Val->getType();
18085         } else {
18086           // C99 6.7.2.2p2:
18087           //   The expression that defines the value of an enumeration constant
18088           //   shall be an integer constant expression that has a value
18089           //   representable as an int.
18090 
18091           // Complain if the value is not representable in an int.
18092           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18093             Diag(IdLoc, diag::ext_enum_value_not_int)
18094               << toString(EnumVal, 10) << Val->getSourceRange()
18095               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18096           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18097             // Force the type of the expression to 'int'.
18098             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18099           }
18100           EltTy = Val->getType();
18101         }
18102       }
18103     }
18104   }
18105 
18106   if (!Val) {
18107     if (Enum->isDependentType())
18108       EltTy = Context.DependentTy;
18109     else if (!LastEnumConst) {
18110       // C++0x [dcl.enum]p5:
18111       //   If the underlying type is not fixed, the type of each enumerator
18112       //   is the type of its initializing value:
18113       //     - If no initializer is specified for the first enumerator, the
18114       //       initializing value has an unspecified integral type.
18115       //
18116       // GCC uses 'int' for its unspecified integral type, as does
18117       // C99 6.7.2.2p3.
18118       if (Enum->isFixed()) {
18119         EltTy = Enum->getIntegerType();
18120       }
18121       else {
18122         EltTy = Context.IntTy;
18123       }
18124     } else {
18125       // Assign the last value + 1.
18126       EnumVal = LastEnumConst->getInitVal();
18127       ++EnumVal;
18128       EltTy = LastEnumConst->getType();
18129 
18130       // Check for overflow on increment.
18131       if (EnumVal < LastEnumConst->getInitVal()) {
18132         // C++0x [dcl.enum]p5:
18133         //   If the underlying type is not fixed, the type of each enumerator
18134         //   is the type of its initializing value:
18135         //
18136         //     - Otherwise the type of the initializing value is the same as
18137         //       the type of the initializing value of the preceding enumerator
18138         //       unless the incremented value is not representable in that type,
18139         //       in which case the type is an unspecified integral type
18140         //       sufficient to contain the incremented value. If no such type
18141         //       exists, the program is ill-formed.
18142         QualType T = getNextLargerIntegralType(Context, EltTy);
18143         if (T.isNull() || Enum->isFixed()) {
18144           // There is no integral type larger enough to represent this
18145           // value. Complain, then allow the value to wrap around.
18146           EnumVal = LastEnumConst->getInitVal();
18147           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18148           ++EnumVal;
18149           if (Enum->isFixed())
18150             // When the underlying type is fixed, this is ill-formed.
18151             Diag(IdLoc, diag::err_enumerator_wrapped)
18152               << toString(EnumVal, 10)
18153               << EltTy;
18154           else
18155             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18156               << toString(EnumVal, 10);
18157         } else {
18158           EltTy = T;
18159         }
18160 
18161         // Retrieve the last enumerator's value, extent that type to the
18162         // type that is supposed to be large enough to represent the incremented
18163         // value, then increment.
18164         EnumVal = LastEnumConst->getInitVal();
18165         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18166         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18167         ++EnumVal;
18168 
18169         // If we're not in C++, diagnose the overflow of enumerator values,
18170         // which in C99 means that the enumerator value is not representable in
18171         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18172         // permits enumerator values that are representable in some larger
18173         // integral type.
18174         if (!getLangOpts().CPlusPlus && !T.isNull())
18175           Diag(IdLoc, diag::warn_enum_value_overflow);
18176       } else if (!getLangOpts().CPlusPlus &&
18177                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18178         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18179         Diag(IdLoc, diag::ext_enum_value_not_int)
18180           << toString(EnumVal, 10) << 1;
18181       }
18182     }
18183   }
18184 
18185   if (!EltTy->isDependentType()) {
18186     // Make the enumerator value match the signedness and size of the
18187     // enumerator's type.
18188     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18189     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18190   }
18191 
18192   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18193                                   Val, EnumVal);
18194 }
18195 
18196 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18197                                                 SourceLocation IILoc) {
18198   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18199       !getLangOpts().CPlusPlus)
18200     return SkipBodyInfo();
18201 
18202   // We have an anonymous enum definition. Look up the first enumerator to
18203   // determine if we should merge the definition with an existing one and
18204   // skip the body.
18205   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18206                                          forRedeclarationInCurContext());
18207   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18208   if (!PrevECD)
18209     return SkipBodyInfo();
18210 
18211   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18212   NamedDecl *Hidden;
18213   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18214     SkipBodyInfo Skip;
18215     Skip.Previous = Hidden;
18216     return Skip;
18217   }
18218 
18219   return SkipBodyInfo();
18220 }
18221 
18222 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18223                               SourceLocation IdLoc, IdentifierInfo *Id,
18224                               const ParsedAttributesView &Attrs,
18225                               SourceLocation EqualLoc, Expr *Val) {
18226   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18227   EnumConstantDecl *LastEnumConst =
18228     cast_or_null<EnumConstantDecl>(lastEnumConst);
18229 
18230   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18231   // we find one that is.
18232   S = getNonFieldDeclScope(S);
18233 
18234   // Verify that there isn't already something declared with this name in this
18235   // scope.
18236   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18237   LookupName(R, S);
18238   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18239 
18240   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18241     // Maybe we will complain about the shadowed template parameter.
18242     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18243     // Just pretend that we didn't see the previous declaration.
18244     PrevDecl = nullptr;
18245   }
18246 
18247   // C++ [class.mem]p15:
18248   // If T is the name of a class, then each of the following shall have a name
18249   // different from T:
18250   // - every enumerator of every member of class T that is an unscoped
18251   // enumerated type
18252   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18253     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18254                             DeclarationNameInfo(Id, IdLoc));
18255 
18256   EnumConstantDecl *New =
18257     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18258   if (!New)
18259     return nullptr;
18260 
18261   if (PrevDecl) {
18262     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18263       // Check for other kinds of shadowing not already handled.
18264       CheckShadow(New, PrevDecl, R);
18265     }
18266 
18267     // When in C++, we may get a TagDecl with the same name; in this case the
18268     // enum constant will 'hide' the tag.
18269     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18270            "Received TagDecl when not in C++!");
18271     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18272       if (isa<EnumConstantDecl>(PrevDecl))
18273         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18274       else
18275         Diag(IdLoc, diag::err_redefinition) << Id;
18276       notePreviousDefinition(PrevDecl, IdLoc);
18277       return nullptr;
18278     }
18279   }
18280 
18281   // Process attributes.
18282   ProcessDeclAttributeList(S, New, Attrs);
18283   AddPragmaAttributes(S, New);
18284 
18285   // Register this decl in the current scope stack.
18286   New->setAccess(TheEnumDecl->getAccess());
18287   PushOnScopeChains(New, S);
18288 
18289   ActOnDocumentableDecl(New);
18290 
18291   return New;
18292 }
18293 
18294 // Returns true when the enum initial expression does not trigger the
18295 // duplicate enum warning.  A few common cases are exempted as follows:
18296 // Element2 = Element1
18297 // Element2 = Element1 + 1
18298 // Element2 = Element1 - 1
18299 // Where Element2 and Element1 are from the same enum.
18300 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18301   Expr *InitExpr = ECD->getInitExpr();
18302   if (!InitExpr)
18303     return true;
18304   InitExpr = InitExpr->IgnoreImpCasts();
18305 
18306   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18307     if (!BO->isAdditiveOp())
18308       return true;
18309     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18310     if (!IL)
18311       return true;
18312     if (IL->getValue() != 1)
18313       return true;
18314 
18315     InitExpr = BO->getLHS();
18316   }
18317 
18318   // This checks if the elements are from the same enum.
18319   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18320   if (!DRE)
18321     return true;
18322 
18323   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18324   if (!EnumConstant)
18325     return true;
18326 
18327   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18328       Enum)
18329     return true;
18330 
18331   return false;
18332 }
18333 
18334 // Emits a warning when an element is implicitly set a value that
18335 // a previous element has already been set to.
18336 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18337                                         EnumDecl *Enum, QualType EnumType) {
18338   // Avoid anonymous enums
18339   if (!Enum->getIdentifier())
18340     return;
18341 
18342   // Only check for small enums.
18343   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18344     return;
18345 
18346   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18347     return;
18348 
18349   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18350   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18351 
18352   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18353 
18354   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18355   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18356 
18357   // Use int64_t as a key to avoid needing special handling for map keys.
18358   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18359     llvm::APSInt Val = D->getInitVal();
18360     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18361   };
18362 
18363   DuplicatesVector DupVector;
18364   ValueToVectorMap EnumMap;
18365 
18366   // Populate the EnumMap with all values represented by enum constants without
18367   // an initializer.
18368   for (auto *Element : Elements) {
18369     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18370 
18371     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18372     // this constant.  Skip this enum since it may be ill-formed.
18373     if (!ECD) {
18374       return;
18375     }
18376 
18377     // Constants with initalizers are handled in the next loop.
18378     if (ECD->getInitExpr())
18379       continue;
18380 
18381     // Duplicate values are handled in the next loop.
18382     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18383   }
18384 
18385   if (EnumMap.size() == 0)
18386     return;
18387 
18388   // Create vectors for any values that has duplicates.
18389   for (auto *Element : Elements) {
18390     // The last loop returned if any constant was null.
18391     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18392     if (!ValidDuplicateEnum(ECD, Enum))
18393       continue;
18394 
18395     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18396     if (Iter == EnumMap.end())
18397       continue;
18398 
18399     DeclOrVector& Entry = Iter->second;
18400     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18401       // Ensure constants are different.
18402       if (D == ECD)
18403         continue;
18404 
18405       // Create new vector and push values onto it.
18406       auto Vec = std::make_unique<ECDVector>();
18407       Vec->push_back(D);
18408       Vec->push_back(ECD);
18409 
18410       // Update entry to point to the duplicates vector.
18411       Entry = Vec.get();
18412 
18413       // Store the vector somewhere we can consult later for quick emission of
18414       // diagnostics.
18415       DupVector.emplace_back(std::move(Vec));
18416       continue;
18417     }
18418 
18419     ECDVector *Vec = Entry.get<ECDVector*>();
18420     // Make sure constants are not added more than once.
18421     if (*Vec->begin() == ECD)
18422       continue;
18423 
18424     Vec->push_back(ECD);
18425   }
18426 
18427   // Emit diagnostics.
18428   for (const auto &Vec : DupVector) {
18429     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18430 
18431     // Emit warning for one enum constant.
18432     auto *FirstECD = Vec->front();
18433     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18434       << FirstECD << toString(FirstECD->getInitVal(), 10)
18435       << FirstECD->getSourceRange();
18436 
18437     // Emit one note for each of the remaining enum constants with
18438     // the same value.
18439     for (auto *ECD : llvm::drop_begin(*Vec))
18440       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18441         << ECD << toString(ECD->getInitVal(), 10)
18442         << ECD->getSourceRange();
18443   }
18444 }
18445 
18446 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18447                              bool AllowMask) const {
18448   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18449   assert(ED->isCompleteDefinition() && "expected enum definition");
18450 
18451   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18452   llvm::APInt &FlagBits = R.first->second;
18453 
18454   if (R.second) {
18455     for (auto *E : ED->enumerators()) {
18456       const auto &EVal = E->getInitVal();
18457       // Only single-bit enumerators introduce new flag values.
18458       if (EVal.isPowerOf2())
18459         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18460     }
18461   }
18462 
18463   // A value is in a flag enum if either its bits are a subset of the enum's
18464   // flag bits (the first condition) or we are allowing masks and the same is
18465   // true of its complement (the second condition). When masks are allowed, we
18466   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18467   //
18468   // While it's true that any value could be used as a mask, the assumption is
18469   // that a mask will have all of the insignificant bits set. Anything else is
18470   // likely a logic error.
18471   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18472   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18473 }
18474 
18475 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18476                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18477                          const ParsedAttributesView &Attrs) {
18478   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18479   QualType EnumType = Context.getTypeDeclType(Enum);
18480 
18481   ProcessDeclAttributeList(S, Enum, Attrs);
18482 
18483   if (Enum->isDependentType()) {
18484     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18485       EnumConstantDecl *ECD =
18486         cast_or_null<EnumConstantDecl>(Elements[i]);
18487       if (!ECD) continue;
18488 
18489       ECD->setType(EnumType);
18490     }
18491 
18492     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18493     return;
18494   }
18495 
18496   // TODO: If the result value doesn't fit in an int, it must be a long or long
18497   // long value.  ISO C does not support this, but GCC does as an extension,
18498   // emit a warning.
18499   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18500   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18501   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18502 
18503   // Verify that all the values are okay, compute the size of the values, and
18504   // reverse the list.
18505   unsigned NumNegativeBits = 0;
18506   unsigned NumPositiveBits = 0;
18507 
18508   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18509     EnumConstantDecl *ECD =
18510       cast_or_null<EnumConstantDecl>(Elements[i]);
18511     if (!ECD) continue;  // Already issued a diagnostic.
18512 
18513     const llvm::APSInt &InitVal = ECD->getInitVal();
18514 
18515     // Keep track of the size of positive and negative values.
18516     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18517       NumPositiveBits = std::max(NumPositiveBits,
18518                                  (unsigned)InitVal.getActiveBits());
18519     else
18520       NumNegativeBits = std::max(NumNegativeBits,
18521                                  (unsigned)InitVal.getMinSignedBits());
18522   }
18523 
18524   // Figure out the type that should be used for this enum.
18525   QualType BestType;
18526   unsigned BestWidth;
18527 
18528   // C++0x N3000 [conv.prom]p3:
18529   //   An rvalue of an unscoped enumeration type whose underlying
18530   //   type is not fixed can be converted to an rvalue of the first
18531   //   of the following types that can represent all the values of
18532   //   the enumeration: int, unsigned int, long int, unsigned long
18533   //   int, long long int, or unsigned long long int.
18534   // C99 6.4.4.3p2:
18535   //   An identifier declared as an enumeration constant has type int.
18536   // The C99 rule is modified by a gcc extension
18537   QualType BestPromotionType;
18538 
18539   bool Packed = Enum->hasAttr<PackedAttr>();
18540   // -fshort-enums is the equivalent to specifying the packed attribute on all
18541   // enum definitions.
18542   if (LangOpts.ShortEnums)
18543     Packed = true;
18544 
18545   // If the enum already has a type because it is fixed or dictated by the
18546   // target, promote that type instead of analyzing the enumerators.
18547   if (Enum->isComplete()) {
18548     BestType = Enum->getIntegerType();
18549     if (BestType->isPromotableIntegerType())
18550       BestPromotionType = Context.getPromotedIntegerType(BestType);
18551     else
18552       BestPromotionType = BestType;
18553 
18554     BestWidth = Context.getIntWidth(BestType);
18555   }
18556   else if (NumNegativeBits) {
18557     // If there is a negative value, figure out the smallest integer type (of
18558     // int/long/longlong) that fits.
18559     // If it's packed, check also if it fits a char or a short.
18560     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18561       BestType = Context.SignedCharTy;
18562       BestWidth = CharWidth;
18563     } else if (Packed && NumNegativeBits <= ShortWidth &&
18564                NumPositiveBits < ShortWidth) {
18565       BestType = Context.ShortTy;
18566       BestWidth = ShortWidth;
18567     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18568       BestType = Context.IntTy;
18569       BestWidth = IntWidth;
18570     } else {
18571       BestWidth = Context.getTargetInfo().getLongWidth();
18572 
18573       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18574         BestType = Context.LongTy;
18575       } else {
18576         BestWidth = Context.getTargetInfo().getLongLongWidth();
18577 
18578         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18579           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18580         BestType = Context.LongLongTy;
18581       }
18582     }
18583     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18584   } else {
18585     // If there is no negative value, figure out the smallest type that fits
18586     // all of the enumerator values.
18587     // If it's packed, check also if it fits a char or a short.
18588     if (Packed && NumPositiveBits <= CharWidth) {
18589       BestType = Context.UnsignedCharTy;
18590       BestPromotionType = Context.IntTy;
18591       BestWidth = CharWidth;
18592     } else if (Packed && NumPositiveBits <= ShortWidth) {
18593       BestType = Context.UnsignedShortTy;
18594       BestPromotionType = Context.IntTy;
18595       BestWidth = ShortWidth;
18596     } else if (NumPositiveBits <= IntWidth) {
18597       BestType = Context.UnsignedIntTy;
18598       BestWidth = IntWidth;
18599       BestPromotionType
18600         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18601                            ? Context.UnsignedIntTy : Context.IntTy;
18602     } else if (NumPositiveBits <=
18603                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18604       BestType = Context.UnsignedLongTy;
18605       BestPromotionType
18606         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18607                            ? Context.UnsignedLongTy : Context.LongTy;
18608     } else {
18609       BestWidth = Context.getTargetInfo().getLongLongWidth();
18610       assert(NumPositiveBits <= BestWidth &&
18611              "How could an initializer get larger than ULL?");
18612       BestType = Context.UnsignedLongLongTy;
18613       BestPromotionType
18614         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18615                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18616     }
18617   }
18618 
18619   // Loop over all of the enumerator constants, changing their types to match
18620   // the type of the enum if needed.
18621   for (auto *D : Elements) {
18622     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18623     if (!ECD) continue;  // Already issued a diagnostic.
18624 
18625     // Standard C says the enumerators have int type, but we allow, as an
18626     // extension, the enumerators to be larger than int size.  If each
18627     // enumerator value fits in an int, type it as an int, otherwise type it the
18628     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18629     // that X has type 'int', not 'unsigned'.
18630 
18631     // Determine whether the value fits into an int.
18632     llvm::APSInt InitVal = ECD->getInitVal();
18633 
18634     // If it fits into an integer type, force it.  Otherwise force it to match
18635     // the enum decl type.
18636     QualType NewTy;
18637     unsigned NewWidth;
18638     bool NewSign;
18639     if (!getLangOpts().CPlusPlus &&
18640         !Enum->isFixed() &&
18641         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18642       NewTy = Context.IntTy;
18643       NewWidth = IntWidth;
18644       NewSign = true;
18645     } else if (ECD->getType() == BestType) {
18646       // Already the right type!
18647       if (getLangOpts().CPlusPlus)
18648         // C++ [dcl.enum]p4: Following the closing brace of an
18649         // enum-specifier, each enumerator has the type of its
18650         // enumeration.
18651         ECD->setType(EnumType);
18652       continue;
18653     } else {
18654       NewTy = BestType;
18655       NewWidth = BestWidth;
18656       NewSign = BestType->isSignedIntegerOrEnumerationType();
18657     }
18658 
18659     // Adjust the APSInt value.
18660     InitVal = InitVal.extOrTrunc(NewWidth);
18661     InitVal.setIsSigned(NewSign);
18662     ECD->setInitVal(InitVal);
18663 
18664     // Adjust the Expr initializer and type.
18665     if (ECD->getInitExpr() &&
18666         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18667       ECD->setInitExpr(ImplicitCastExpr::Create(
18668           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18669           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18670     if (getLangOpts().CPlusPlus)
18671       // C++ [dcl.enum]p4: Following the closing brace of an
18672       // enum-specifier, each enumerator has the type of its
18673       // enumeration.
18674       ECD->setType(EnumType);
18675     else
18676       ECD->setType(NewTy);
18677   }
18678 
18679   Enum->completeDefinition(BestType, BestPromotionType,
18680                            NumPositiveBits, NumNegativeBits);
18681 
18682   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18683 
18684   if (Enum->isClosedFlag()) {
18685     for (Decl *D : Elements) {
18686       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18687       if (!ECD) continue;  // Already issued a diagnostic.
18688 
18689       llvm::APSInt InitVal = ECD->getInitVal();
18690       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18691           !IsValueInFlagEnum(Enum, InitVal, true))
18692         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18693           << ECD << Enum;
18694     }
18695   }
18696 
18697   // Now that the enum type is defined, ensure it's not been underaligned.
18698   if (Enum->hasAttrs())
18699     CheckAlignasUnderalignment(Enum);
18700 }
18701 
18702 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18703                                   SourceLocation StartLoc,
18704                                   SourceLocation EndLoc) {
18705   StringLiteral *AsmString = cast<StringLiteral>(expr);
18706 
18707   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18708                                                    AsmString, StartLoc,
18709                                                    EndLoc);
18710   CurContext->addDecl(New);
18711   return New;
18712 }
18713 
18714 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18715                                       IdentifierInfo* AliasName,
18716                                       SourceLocation PragmaLoc,
18717                                       SourceLocation NameLoc,
18718                                       SourceLocation AliasNameLoc) {
18719   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18720                                          LookupOrdinaryName);
18721   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18722                            AttributeCommonInfo::AS_Pragma);
18723   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18724       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18725 
18726   // If a declaration that:
18727   // 1) declares a function or a variable
18728   // 2) has external linkage
18729   // already exists, add a label attribute to it.
18730   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18731     if (isDeclExternC(PrevDecl))
18732       PrevDecl->addAttr(Attr);
18733     else
18734       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18735           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18736   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18737   } else
18738     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18739 }
18740 
18741 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18742                              SourceLocation PragmaLoc,
18743                              SourceLocation NameLoc) {
18744   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18745 
18746   if (PrevDecl) {
18747     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18748   } else {
18749     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18750   }
18751 }
18752 
18753 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18754                                 IdentifierInfo* AliasName,
18755                                 SourceLocation PragmaLoc,
18756                                 SourceLocation NameLoc,
18757                                 SourceLocation AliasNameLoc) {
18758   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18759                                     LookupOrdinaryName);
18760   WeakInfo W = WeakInfo(Name, NameLoc);
18761 
18762   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18763     if (!PrevDecl->hasAttr<AliasAttr>())
18764       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18765         DeclApplyPragmaWeak(TUScope, ND, W);
18766   } else {
18767     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18768   }
18769 }
18770 
18771 Decl *Sema::getObjCDeclContext() const {
18772   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18773 }
18774 
18775 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18776                                                      bool Final) {
18777   assert(FD && "Expected non-null FunctionDecl");
18778 
18779   // SYCL functions can be template, so we check if they have appropriate
18780   // attribute prior to checking if it is a template.
18781   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18782     return FunctionEmissionStatus::Emitted;
18783 
18784   // Templates are emitted when they're instantiated.
18785   if (FD->isDependentContext())
18786     return FunctionEmissionStatus::TemplateDiscarded;
18787 
18788   // Check whether this function is an externally visible definition.
18789   auto IsEmittedForExternalSymbol = [this, FD]() {
18790     // We have to check the GVA linkage of the function's *definition* -- if we
18791     // only have a declaration, we don't know whether or not the function will
18792     // be emitted, because (say) the definition could include "inline".
18793     FunctionDecl *Def = FD->getDefinition();
18794 
18795     return Def && !isDiscardableGVALinkage(
18796                       getASTContext().GetGVALinkageForFunction(Def));
18797   };
18798 
18799   if (LangOpts.OpenMPIsDevice) {
18800     // In OpenMP device mode we will not emit host only functions, or functions
18801     // we don't need due to their linkage.
18802     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18803         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18804     // DevTy may be changed later by
18805     //  #pragma omp declare target to(*) device_type(*).
18806     // Therefore DevTy having no value does not imply host. The emission status
18807     // will be checked again at the end of compilation unit with Final = true.
18808     if (DevTy.hasValue())
18809       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18810         return FunctionEmissionStatus::OMPDiscarded;
18811     // If we have an explicit value for the device type, or we are in a target
18812     // declare context, we need to emit all extern and used symbols.
18813     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18814       if (IsEmittedForExternalSymbol())
18815         return FunctionEmissionStatus::Emitted;
18816     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18817     // we'll omit it.
18818     if (Final)
18819       return FunctionEmissionStatus::OMPDiscarded;
18820   } else if (LangOpts.OpenMP > 45) {
18821     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18822     // function. In 5.0, no_host was introduced which might cause a function to
18823     // be ommitted.
18824     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18825         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18826     if (DevTy.hasValue())
18827       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18828         return FunctionEmissionStatus::OMPDiscarded;
18829   }
18830 
18831   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18832     return FunctionEmissionStatus::Emitted;
18833 
18834   if (LangOpts.CUDA) {
18835     // When compiling for device, host functions are never emitted.  Similarly,
18836     // when compiling for host, device and global functions are never emitted.
18837     // (Technically, we do emit a host-side stub for global functions, but this
18838     // doesn't count for our purposes here.)
18839     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18840     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18841       return FunctionEmissionStatus::CUDADiscarded;
18842     if (!LangOpts.CUDAIsDevice &&
18843         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18844       return FunctionEmissionStatus::CUDADiscarded;
18845 
18846     if (IsEmittedForExternalSymbol())
18847       return FunctionEmissionStatus::Emitted;
18848   }
18849 
18850   // Otherwise, the function is known-emitted if it's in our set of
18851   // known-emitted functions.
18852   return FunctionEmissionStatus::Unknown;
18853 }
18854 
18855 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18856   // Host-side references to a __global__ function refer to the stub, so the
18857   // function itself is never emitted and therefore should not be marked.
18858   // If we have host fn calls kernel fn calls host+device, the HD function
18859   // does not get instantiated on the host. We model this by omitting at the
18860   // call to the kernel from the callgraph. This ensures that, when compiling
18861   // for host, only HD functions actually called from the host get marked as
18862   // known-emitted.
18863   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18864          IdentifyCUDATarget(Callee) == CFT_Global;
18865 }
18866